In C, when a logical operation is being evaluated, if the result is known before all subexpressions 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. However, 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
Although it is not considered good programming practice, it is legal in C to logically compare two assignment expressions in this manner. A similar problem exists with another common practice - using function calls in logical operations. The second function may never be evaluated.