The logical AND and logical OR operators (&&
, ||
) exhibit "short circuit" operation. That is, the second operand is not evaluated if the result can be deduced solely by evaluating the first operand. Consequently, the second operand should not contain side effects because, if it does, it is not apparent whether the side effect occurs.
Non-Compliant Code Example
int i; int max; if ( (i >= 0 && (i++) <= max) ) { /* code */ }
It is unclear whether the value of i
will be incremented as a result of evaluating the condition.
Compliant Solution
In this compliant solution, the behavior is much clearer.
int i; int max; if ( (i >= 0 && i <= max) ) { i++; /* code */ }
Risk Assessment
Attempting to modify an object that is the second operand to the logical OR or AND operator may cause that object to take on an unexpected value. This can lead to unintended program behavior.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
EXP02-A |
1 (low) |
1 (unlikely) |
2 (medium) |
P2 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[ISO/IEC 9899-1999]] Section 6.5.13, "Logical AND operator," and Section 6.5.14, "Logical OR operator"
EXP01-A. Do not take the size of a pointer to determine the size of a type 03. Expressions (EXP) EXP03-A. Do not assume the size of a structure is the sum of the of the sizes of its members