Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The semantics of checking if conditions

Tags:

c

If I have a condition like this:

if (X && Y) {}

Will the compiler check Y if X is false? Is it compiler dependent?

like image 845
Iceman Avatar asked Nov 30 '22 13:11

Iceman


2 Answers

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.

like image 136
ThiefMaster Avatar answered Dec 05 '22 03:12

ThiefMaster


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.

like image 36
Mike Avatar answered Dec 05 '22 03:12

Mike