Search code examples
c++operator-precedence

How does compiler read these expressions? Why am I getting these outputs(All variables are initialized as 1)?


int x = 1 , y = 1 , z = 1  ;

Now check these lines of code :-

cout << (++x || ++y)<<endl;     //Output 1
cout << x <<" " << y;          // now x = 2 and y = 1 . Why 'y' is not incremented ?

again values are initialized to 1

cout <<(++x && ++y )<<endl;     //Output 1
cout << x <<" " << y;         //now x = 2 and y = 2 . Why 'y' is incremented ?

again values are initialized to 1

cout << (++x ||++y && ++z )<<endl;  //Output 1
cout << x<<" "<< y<<" "<<z ;       //now x = 2 , y = 1 , z = 1.Why these outputs? 

Can some one explain me how compiler reads these codes ? I read about the Precedence order but I can't figure out how compiler works on these types of code.Even a Small help will be appreciated!


Solution

  • It is called short circuiting.

    1. In your first case, since x has value of 1 on the left side, the right side of operator || is never called (because result would be true in any case in case with ||)- and hence y is never incremented.

    2. Similarly in your second example, since x is one on the left side, that means nothing for && - you still need to evaluate right side to see final result; if right hand side is false, then result is false, otherwise true. So in this case both left side and right side are evaluated. And values of x and y are increased.

    3. Again in your third case, due to short circuit, the right hand side involving y and z is never executed (because x has value of 1) - hence value of y and z is 1.

    Here is some more info.