Short-circuit evaluation on C
The &&
operator uses lazy evaluation. If either side of the &&
operator is false
, then the whole expression is false
.
C checks the truth value of the left hand side of the operator, which in your case is 0
. Since 0
is false in c, then the right hand side expression of the operation, (a = b = 777)
, is never evaluated.
The second case is similar, except that ||
returns true
if the left hand side expression returns true
. Also remember that in c, anything that is not 0
is considered true
.
Hope this helps.
From the C Standard (6.5.13 Logical AND operator)
3 The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
and
4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.
In this expression statement
x = 0 && (a = b = 777);
the first operand compares equal to 0. So the second operand is not evaluated that is the values of the variables a
and b
are not changed. So the variable x
will be set to 0
according to the paragraph #3 of the section.
From the C Standard (6.5.14 Logical OR operator)
3 The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.
and
4 Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.
In this expression statement
x = 777 || (a = ++b);
the first operand compares unequal to 0. So the second operand is not evaluated that is the values of the variables a
and b
are not changed.. So the variable x
will be set to 1
according to the paragraph #3 of the section.
If you will change the order of the operands in the expressions like
x = (a = b = 777) && 0;
x = (a = ++b) || 777;
you get the expected by you result.