Reputation: 117
void revalue(int r, int ar[], int n)
{
for(int i=0; i<n;i++)
{
ar[i]*=r;
}
}
So I'm really confused with how this code works and why it changes the ar[]. The thing is I thought that everytime you pass variables that aren't reference or pointers into a function a copy of the variable is made, then the copy is deleted after it goes out of scope of the function. Yet this function changes the array values.
How is this possible?
Upvotes: 0
Views: 122
Reputation: 153840
I guess, the confusion is with int ar[]
which, in this context, is equivalent to writing int* ar
: In C++ you cannot pass built-in arrays by value. However, they easily decay into pointers and the above is an alternative notation. Note that you could have used int ar[10]
or int ar[20]
and it would have been identical, too.
Upvotes: 3
Reputation: 490128
Pretty simple really: when you use array notation for a parameter in C or C++, it's silently adjusted by the compiler to actually pass a pointer.
IOW, your function is really:
void revalue(int r, int *ar, int n)
...and from there, most of it is pretty clear.
Upvotes: 3
Reputation: 8726
Arrays are passed by reference by default in c++ being adjusted to a pointer to the first element of the array.
Upvotes: 0