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

267 views Asked by At

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?

2

There are 2 answers

0
Sourav Ghosh On BEST ANSWER

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.

0
Mark Adelsberger On

In C both && and || "sort-circuit", meaning if evaluation of the left operand is enough to determine the outcome then the right operand is not evaluated.