0

The arrays are passed by reference. Any changes made to the array within the function changeArray will be observed in the calling scope (main function here).

However the codes below print 0 1 in the 1st cout, and print 2 in the 2nd "cout". What I don't understand is that why the first cout prints the original value of array[0]=1 instead of the changed value of array[0]=2?

Thanks a lot.

#include <iostream>

using namespace std;

int changeArray(int array[]) {
    array[0]=2*array[0];
    return 0;
}

int main() {
    int array[]={1,2,3,4};
    cout << changeArray(array) << " " << array[0] << endl;
    cout << array[0] << endl;
    return 0;
}
cgao
  • 155
  • 4
  • 15
  • similar to http://stackoverflow.com/questions/10782863/what-is-the-correct-answer-for-cout-c-c and many other order-of-evaluation questions – Cubbi Oct 07 '13 at 19:04
  • Arrays are not passed by reference; in fact, arrays cannot be passed as arguments at all. `int changeArray(int array[])` really means `int changeArray(int *array)` (it's adjusted at compile time), and the array expression `array` in `changeArray(array)` is implicitly converted to ("decays" to) a pointer the array's first element for reasons unrelated to the fact that it's used as an argument in a function call. – Keith Thompson Oct 07 '13 at 19:59
  • 1
    @KeithThompson "arrays cannot be passed as arguments at all" Arrays can be passed by reference in C++: `int changeArray(int (&array)[4])` However, arrays of *unknown bound* cannot be passed by reference. – dyp Oct 07 '13 at 20:06
  • @DyP: Good point. (I'd go back and edit my comment if I could.) – Keith Thompson Oct 07 '13 at 20:09

1 Answers1

3

To make sure that the compiler doesn't reorder the execution:

cout << array[0] << endl;
changeArray(array);
cout << array[0] << endl;

This prints 1 and then 2.

The C++ compiler is allowed to optimize the code by reordering the execution of code within a single expression (e.g. cout << changeArray(array) << " " << array[0] << endl). To avoid that, and to make sure changeArray gets called first, you need to split your expression to separate statements, e.g. by using the semicolon (;). Everything before the semicolon gets executed before anything after the semicolon can start.

pts
  • 80,836
  • 20
  • 110
  • 183