Short Circuit Evaluation

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 is 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

expr1 expr2 Result
0 X (0) 0
0 X (1) 0
1 0 0
1 1 1

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

Example

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.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.