Versions Compared

Key

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

...

Noncompliant Code Example

One way to check whether a number is even or odd is to examine the least significant bit. This will give inconsistent results. Specifically, this example will give unexpected behavior on all ones' complement implementations.

Code Block
bgColor#FFcccc

...

#ffcccc

int value;

if (scanf("%d", &value) == 1) {
  if (value & 0x1 == 1) {
    /* do something if value is odd */
  }
}

Compliant Solution

The same thing can be achieved compliantly using the modulo operator.

Code Block
bgColor#ccccff

int value;

if (scanf("%d", &value) == 1) {
  if (value % 2 == 1) {
    /* do something if value is odd */
  }
}

Risk Assessment

Incorrect assumptions about integer representation can lead to execution of unintended code branches and other unexpected behavior.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

 

medium

unlikely

medium

P4

L3

References

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.6.2