How to predict output of such unary expressions?

128 views Asked by At
#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++?

1

There are 1 answers

0
Khoyo On BEST ANSWER

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.