CodeSlayer007's blog

By CodeSlayer007, history, 5 years ago, In English
int i,j;
    i = j = 5;
    j = i++ + (i*10);
    cout<<i<<" "<< j <<" "<<i++;

The above code is giving two different output in C++14 and C++17.Can anyone explain why?? In c++14 its showing 7 65 6 In C++17 its showing 6 65 6

  • Vote: I like it
  • +11
  • Vote: I do not like it

»
5 years ago, # |
  Vote: I like it +3 Vote: I do not like it

Perks of undefined behaviour.

»
5 years ago, # |
Rev. 4   Vote: I like it +19 Vote: I do not like it

First of all operator<< is just a function. So the last line could be translated into :
operator<<( operator<<( operator<<( cout, i ), j ), i++ );
for simplicity let's replace operator<< with f
f(f(f(cout, i), j), i++)
In C++ order of evaluation of function arguments is unspecified. So it is not guaranteed to get executed from left to right. That's why in my computer with my compiler it gives 6 65 6 regarding any standard.
In your case, at first i++ is evaluated which increments i but returns previous value of i. So the first i = 7 and the last i = 6.
Conclusion : DON'T RELY ON ORDER OF EVALUATION OF FUNCTION ARGUMENTS

»
5 years ago, # |
  Vote: I like it +6 Vote: I do not like it

It's possible that running this code will trigger a world war, the C++ standard allows that.

  • »
    »
    5 years ago, # ^ |
      Vote: I like it +10 Vote: I do not like it

    Btw, I'm curious, does the C++ standard somehow imply that other code constructions with defined behavior don't trigger a world war? :)

    • »
      »
      »
      5 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Well, running well defined code cannot directly start a world war. However, if the code running has any observable side effects, that may contribute.