C Programming Short Circuit Evaluation

Last modified by Microchip on 2023/11/09 09:06

In C, when a logical operation is being evaluated, if the result is known before all sub-expressions have been evaluated, then the evaluation stops, or short circuits. The two situations where this can occur are when the first expression of a logical AND operation is FALSE (zero) or the first expression of a logical OR operation is TRUE (non-zero). In both of these cases, the result is already known. For AND, if either of the two expressions is FALSE, the result will be FALSE. For OR, if either of the two expressions is TRUE, then the result will be TRUE.

In most situations, this won't be a problem, but you need to be careful not to use the results of the second expression somewhere else in your code because there is no guarantee that it will ever be evaluated.

Example

If we have two expressions being tested in a logical AND operation:
expr1 && expr2
The expressions are evaluated from left to right. If expr1 is 0 (FALSE), then expr2 would not be evaluated at all since the overall result is already known to be false.

Truth table for AND (&&)
FALSE=0
TRUE=1

expr1expr2Result
0X (0)0
0X (1)0
100
111

expr2 is not evaluated in the first two cases since its value is not relevant to the result.

Example

1
2
3
4
5
if !((z = x + y) && (c = a + b))  //If z=0, then c will NOT be evaluated
{
    z += 5;
    c += 10;                      //Initial value of c may not be correct
}

It is perfectly legal in C to logically compare two assignment expressions in this way, though it is not usually good programming practice.
A similar problem exists when using function calls in logical operations, which is a very common practice. The second function may never be evaluated.