C++ Array passed by reference, but how to understand this? -
the arrays passed reference. changes made array within function changearray observed in calling scope (main function here).
however codes below print 0 1 in 1st cout, , print 2 in 2nd "cout". don't understand why first cout prints original value of array[0]=1 instead of changed value of array[0]=2?
thanks 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 compiler doesn't reorder execution:
cout << array[0] << endl; changearray(array); cout << array[0] << endl; this prints 1 , 2.
the c++ compiler allowed optimize code reordering execution of code within single expression (e.g. cout << changearray(array) << " " << array[0] << endl). avoid that, , make sure changearray gets called first, need split expression separate statements, e.g. using semicolon (;). before semicolon gets executed before after semicolon can start.
Comments
Post a Comment