#include <stdio.h>
int main(void) {
int a = 0, b = 0, c = 0;
++a || ++b && ++c;
printf("%d %d %d", a, b, c);
return 0;
}
The outputs are 1
, 0
, 0
by gcc 8.1.0. The &&
‘s precedence should higher than ||
.
Why are the b
and c
are still 0
?
There are three issues here:
Order of precedence implies that ++a || ++b && ++c
is evaluated as ++a || (++b && ++c)
.
However, due to the short circuiting requirements of logical operators, ++a
is evaluated first. Only if that evaluates to false
will (++b && ++c)
be evaluated. In your case, ++a
evaluates to true
. Hence, (++b && ++c)
is never evaluated.
The expression ++a || ++b && ++c
is grouped as ++a || (++b && ++c)
. But, the right hand side of ||
is only evaluated if ++a
is 0
, which it isn't.
The logical OR operator ||
(as well as the logical AND operator &&
) is one of the few operators that perform short circut operation.
Section 6.5.14 of the C standard says the following about the logical OR operator:
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.
Because ++a
evaluates to 1, the result of the ||
operator is guaranteed to be 1 and the right hand side is not evaluated. Also, because &&
has higher precedence than ||
, the right side of the ||
operator is ++b && ++c
, meaning that neither ++b
or ++c
is evaluated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With