1

Assuming this code

int main(){
    int i=0, j=0;

    cout << i << " " << f1(&i,&j) << " " << j << endl;

    cout << i << " " << j << endl;
}

int f1(int *i, int *j){
    *i = 20;
    *j = 30;

    return 10;
}

The result is

20 10 0
20 30

I am puzzled as to why j would be 0 while i correctly shows 20

EDIT: I have read up on the sequence point but I am still unsure of how to explain this. Should I assume j is evaluated first before f1 is evaluated hence j is 0 and i is 20?

Alex Teoh
  • 29
  • 7
  • Probably not a dupe, but related: http://stackoverflow.com/questions/9566187/function-parameter-evaluation-order – Tas Aug 24 '16 at 05:27
  • 3
    [Also related (if not a duplicate)](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points). – Some programmer dude Aug 24 '16 at 05:30

1 Answers1

2

Here the thing:

cout << i << " " << f1(&i,&j) << " " << j << endl;

if you consider from right to left evaluation, j was initially 0 and printed. Then, f1 get called and j value is changed to 30. But this order of evaluation is unpredictable

piet.t
  • 11,718
  • 21
  • 43
  • 52