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;
}
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 (eg 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, eg by using the semicolon ( ;
). Everything before the semicolon gets executed before anything after the semicolon can start.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.