Search code examples
logicshort-circuiting

Does all conditions get checked in an if statement even if the first one is false?


If I have:

bool foo = false; bool bar = true;

If(foo && bar)

Doea the if-statement check if bar is true or does it skip it because foo already is false?


Solution

  • What you are referring to is called short-circuit evaluation, and whether it will happen depends on:

    • the language you are programming in
    • in some cases, the implementation (where the language definition neither mandates nor prohibits it)
    • in some cases, the exact situation (where the language explicitly allows but does not guarantee it, and the implementation may choose whether to short-circuit on a case-by-case basis)
    • the exact operator you use (some languages provide two ways of writing "and", one "eager" and one "short-circuit"

    Note that it is not a property of the if statement, which is just taking a single boolean expression which has resulted from you using logical operators; the expression could equally be assigned to a boolean variable, passed as a function parameter, etc.