If I have a condition like this:
if (X && Y) {}
Will the compiler check Y
if X
is false? Is it compiler dependent?
In C and most other languages short-circuit evaluation is guaranteed. So Y
is only evaluated if X
evaluates to true.
The same applies to X || Y
- in this case Y
is only evaluated if X
evaluates to false.
See Mike's answer for a reference to the C specification where this behavior is mentioned and guaranteed.
The C specs (6.5.13) clarifies this point for you:
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.
So the C language itself defineds that if X == 0
then Y
will not be checked.
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