Do not use the bitwise
AND (&, ampersand) or bitwise
OR (|, pipe) operator in place of a logical operator, or vice versa. Use &
or |
only for bitwise operations, and use &&
or ||
only for logical operations.
Noncompliant Code Example
In this noncompliant code example, a bitwise
expression is used in a conditional expression:
if (!(getuid() & geteuid() == 0)) { /* ... */ }
Compliant Solution
This compliant solution uses the &&
operator for the logical operation within the conditional expression:
if (!(getuid() && geteuid() == 0)) { /* ... */ }
Risk Assessment
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP17-C | low | likely | low | P3 | L3 |
Automated Detection
Tool | Version | Checker | Description |
---|---|---|---|
2017.07 | CONSTANT_EXPRESSION_RESULT | Can detect the specific instance where bitwise operator is used in place of logical operator, or vice versa. The behavior might be desirable in some situations, so further verification is necessary | |
PRQA QA-C | Unable to render {include} The included page could not be found. | 3344,4502 |
Related Guidelines
ISO/IEC TR 24772:2013 | Likely Incorrect Expression [KOA] |
MITRE CWE | CWE-480, Use of incorrect operator |
Bibliography
[Hatton 1995] | Section 2.7.2, "Errors of Omission and Addition" |