Reputation: 698
What should be the output of this C program?
#include<stdio.h>
int main(){
int x,y,z;
x=y=z=1;
z = ++x || ++y && ++z;
printf("x=%d y=%d z=%d\n",x,y,z);
return 0;
}
The given output is :
x=2 y=1 z=1
I understand the output for x, but fail to see how y and z values don't get incremented.
Upvotes: 3
Views: 1741
Reputation: 95
In C, any thing other than 0 is treated as true, And the evaluation for the || start from left to right.
Hence the compiler will check first left operand and if it is true then the compiler will not check other operands. ex. A || B - In this case if A is true then compiler will return true only, and will not check whether B is true or False. But if A is false then it will check B and return accordingly means if B is true then will return true or if B is false then it will return false.
In your program compiler first will check ++x(i.e 2) and anything other than 0 is true in C. Hence it will not check/increment other expressions.
Upvotes: 1
Reputation: 437734
This is a result of short-circuit evaluation.
The expression ++x
evaluates to 2
, and the compiler knows that 2 || anything
always evaluates to 1
("true") no matter what anything
is. Therefore it does not proceed to evaluate anything
and the values of y
and z
do not change.
If you try with
x=-1;
y=z=1;
You will see that y
and z
will be incremented, because the compiler has to evaluate the right hand side of the OR to determine the result of the expression.
Edit: asaerl answered your follow-up question in the comments first so I 'll just expand on his correct answer a little.
Operator precedence determines how the parts that make up an expression bind together. Because AND has higher precedence than OR, the compiler knows that you wrote
++x || (++y && ++z)
instead of
(++x || ++y) && ++z
This leaves it tasked to do an OR between ++x
and ++y && ++z
. At this point it would normally be free to select if it would "prefer" to evaluate one or the other expression first -- as per the standard -- and you would not normally be able to depend on the specific order. This order has nothing to do with operator precedence.
However, specifically for ||
and &&
the standard demands that evaluation will always proceed from left to right so that short-circuiting can work and developers can depend on the rhs expression not being evaluated if the result of evaluating the lhs tells.
Upvotes: 12