Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Mixing bitwise and relational operators in the same full expression can be a sign of a logic error in the expression where a logical operator is usually the intended operator. Do not use the bitwise AND (&), bitwise OR (|), or bitwise XOR (^) operators with an operand of type _Bool, or the result of a relational-expression or equality-expression. If the bitwise operator is intended, it should be indicated with use of a parenthesized expression.

Noncompliant Code Example

In this noncompliant code example, a bitwise & operator is used with the results of an equality-expression:

Code Block
bgColor#FFcccc
langc
if (!(getuid() & geteuid() == 0)) { 
  /* ... */ 
} 

Compliant Solution

This compliant solution uses the && operator for the logical operation within the conditional expression:

Code Block
bgColor#ccccff
langc
if (!(getuid() && geteuid() == 0)) {
  /* ... */
}

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP46-C

Low

Likely

Low

P9

L2

Automated Detection

Tool

Version

Checker

Description

Coverity

Include Page
Coverity_V
Coverity_V

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
Include Page
PRQA QA-C_v
PRQA QA-C_v
3344,4502 

Related Guidelines

ISO/IEC TR 24772:2013Likely Incorrect Expression [KOA]
MITRE CWECWE-480, Use of incorrect operator

Bibliography

[Hatton 1995]Section 2.7.2, "Errors of Omission and Addition"