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!
It is called short circuiting.
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.
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.
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.