-1
#include<iostream>
using namespace std;
int main(){
    int x=4;
    cout<<x++<<x<<++x;
}

In the following code if we assume that the expressions are evaluated from right to left then the output should be 555 and for left to right evaluation the output should be 456. But after running the program the output comes out to be 566. How is this happening? How are the expressions actually evaluated in C or C++?

Tas
  • 7,023
  • 3
  • 36
  • 51
  • C and C++ are not the same language; that said, this is undefined behavior in the C version of this code. – ad absurdum Sep 02 '17 at 04:42
  • @David Bowling will it even compile in C? – MCG Sep 02 '17 at 04:44
  • @MCG-- of course not; updated my comment – ad absurdum Sep 02 '17 at 04:45
  • [Here is another informative link](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – ad absurdum Sep 02 '17 at 04:52
  • These notes have very good explanation on [Order of evaluation](https://www.eskimo.com/~scs/cclass/notes/sx7c.html). And a wonderful quote from K&R "...if you don't know how they are done on various machines, that innocence may help to protect you." – Milind Deore Sep 02 '17 at 05:11

1 Answers1

1

The order of evaluation of operator arguments (and function arguments) in C++ is unspecified. It can be left to right, right to left, or without any order...

Because you had an access and a modification of x at more than one point in an unsequenced expression, you hit undefined behaviour.

See this for more details.

Khoyo
  • 1,253
  • 11
  • 20