Versions Compared

Key

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

Do not use the bitwise AND (&, ampersand) or bitwise OR (|, pipe) operator in a conditional expression because this typically indicates programmer error and can result in unexpected behavior. 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.

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)) {
  /* ... */
}

Automated Detection

Tool

Version

Checker

Description

Section

Coverity Prevent

Include Page
c:Coverity_V
c:Coverity_V
Section

CONSTANT_EXPRESSION_RESULT

Section

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 situation, so further verification is necessary.

Related Guidelines

ISO/IEC TR 24772 "KOA Likely Incorrect Expressions"

MITRE CWE: CWE-480, "Use of Incorrect Operator"

Bibliography

Wiki Markup
\[Hatton 1995\] Section 2.7.2, "Errors of omission and addition" 


      03. Expressions (EXP)      EXP18-C. Do not perform assignments in selection statements