Passing array of int is like passing reference?

Why is it passing by reference and not making copies?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void hmm(int x[])
{
   for(int i=0;i<4;++i)
	x[i]=20;
}

int main()
{
   int g[4];

   hmm(g);

   for(int i=0;i<4;++i)
	cout << g[i] << endl;

}


the result is 20, 20, 20, 20.... :S
Built-in arrays cannot be passed by value because they cannot be copied. Therefore they are always passed by reference.

If you want to pass by value, you will need to use a container class, like vector, or valarray.
What is being passed is a pointer to the first element in the array. x is a pointer so you could have written line 1 as void hmm(int* x) with the exact same result.
ahh ok ty for reply
You are wrong! In your example the array is passed by value. To pass an array by reference you have to declare the function as

1
2
3
4
5
void hmm(int ( &x )[4])
{
   for(int i=0;i<4;++i)
	x[i]=20;
}


As in your original example the array is passed by value then a copy of the address of the first element is created.

It is semantically equivalent to the statement

int *x = new int[4];

that is a copy of the address of the first element of unnamed array is assigned to x.

Take into account that if you have an array as for example

int a[4];

then using the name of an array as for example

*a = 10;

means that name a is implicitly converted to the address of the first element of the array. The same mechanism works then the name is passed to a function but in this last case a copy of the address of the first element of the array is created. So changing this copy does not change the original value of the array name.
Last edited on
Topic archived. No new replies allowed.