The behavior of this code is well defined due to the sequence point introduced by the &&
operator. This is spelled out in section 6.5.13p4 of the C standard regarding the logical AND operator &&
:
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.
Going through the code:
a = (a = 5) && (b = 0);
The left side of the &&
operator, i.e. (a = 5)
is evaluated first, which sets a
to 5. This evaluates to true, so there is then a sequence point before the right side, i.e. (b = 0)
is evaluated. This sets b
to 0 and evaluates to false, so the &&
operator results in the value 0. This value is then assigned to a
.