Placeholder Placeholder - 9 days ago 5
C Question

Does while loop check every condition?

Let's say I have the following loop in C: while(x1 && x2).
If the first condition is false (x1==0) then will the while loop check the second condition?

usr usr
Answer

If the first condition is false (x1==0) then will the while loop check the second condition?

No. It won't.

It's called short circuit evaluation.

From C11, 6.5.13:

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.


Similarly in cond1 || cond2, if cond1 evaluates to true then cond2 won't be evaluated. See: C11, 6.5.14:

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.

Comments