I wrote this small piece of code, after executing the code I had this output:
Inside the function: 2
Outside the function: 2
This is not what I expected. I would like to have my "test" array untouched by the function div2. I expected the fucniton div2 just copying the array "test" to "test2" without changing its content.
TarikNeaj is right. Arrays are passed by reference only. In fact, you don't even need to include & in the function heading because pass by reference is always expected for arrays.
In the div2 function, you will have to make a copy of test2 so you can have your working copy of the array for that function without changing the original array.
If you want to pass array by value, here is what you can do:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// const is a promise that you will not change the referenced variable. If you include const and
// try to change that const variable, the compiler will generate an error message
// This prevents accidental changes to the referenced array / variables
void div2 ( constint test2[2] ) {
int copyOfTest2 [2]; // Create a working copy of test2
for ( int index = 0 ; index < 2 ; index ++ ) // Use for-loop to copy the values of the array
copyOfTest2 [index] = test2 [index];
copyOfTest2 [0] /= 2;
copyOfTest2 [1] /= 2;
cout << "Inside the function: " << copyOfTest2 [0] << endl;
return;
}
Here is a sample run:
1 2 3 4 5
Inside the function: 2
Outside the function: 4
Process returned 1 (0x1) execution time : 0.047 s
Press any key to continue.
EDIT: Another thing to add. It's a good practice to pass the size of the array as int variable when you are passing an array to a function.
void div2 ( int test2[] , int size )
Another secret: You don't have to include a number inside the square brackets in the function heading. The compiler ignores it anyways. But you can if you want to.
TarikNeaj is right. Arrays are passed by reference only. In fact, you don't even need to include & in the function heading because pass by reference is always expected for arrays.
When arrays are passed to functions it is a pointer to the first element (and that pointer is passed by value.) This pointer is not a reference in the sense of C++ references. Passing an array by reference is a different thing.