cshort-circuiting

The semantics of checking if conditions


If I have a condition like this:

if (X && Y) {}

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


Solution

  • 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.