Search code examples
coptimizationlogical-operatorsevaluationlogical-and

"And" and "Or" operators in conditionals in C


I always wondered about something and couldn`t find an answer somewhere else. If I have this piece of code:

if ((cond1) &&(cond2) && (cond 3) && (cond 4))
 {
       // do something
 }

Let`s say the first condition is false, then my program will verify the other conditions too, or just skip verifying them?

But if I have

if ((cond1) ||(cond2) || (cond 3) || (cond 4))
 {
       // do something
 }

and cond 1 is true, will my program go instantly on the if part or continue to verify the other conditions too?


Solution

  • Quoting C11 standard, chapter §6.5.13, Logical AND operator (emphasis mine)

    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, if the first condition (LHS operand) evaluates to false, the later conditions, i.e., RHS operand of the && is not evaluated.

    Similarly (Ironically, rather), for Logical "OR" operator,

    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.