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

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -