Here is my code.
#include <stdio.h>
#define PRINT3(x,y,z) printf("x=%d\ty=%d\tz=%d\n",x,y,z)
int main()
{
int x,y,z;
x = y = z = 1;
++x || ++y && ++z; PRINT3(x,y,z);
return 0;
}
The output is,
x=2 y=1 z=1
I don't understand how this happens. What I would expect is, since ++
has higher precedence than &&
or ||
, the prefix operations here will get evaluated first. That is, ++x
, ++y
and ++z
will get evaluated first. So the output I expected was,
x=2 y=2 z=2
Could someone help me understand please? Thanks in advance.
I looked at this question, but I still don't understand why the compiler decides to evaluate ||
before evaluating all the ++s
. Is this compiler dependent, or is it defined in the standard that whenever an operand of ||
is 1, it should be evaluated before evaluating other higher precedence operations in the other operand.
Higher precedence of an operator doesn't guarantee that it will be evaluated first but it guarantees that the operands will be binds (parenthesize) to it first.
++x || ++y && ++z;
will be parenthesize as
( (++x) || ( (++y) && (++z) ) );
Since ||
operator guarantees the evaluation of its operand from left-to-right, (++x)
will be evaluated first. Due to its short circuit behavior on becoming left operand true
, right operand will not be evaluated.