Versions Compared

Key

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

Although many common implementations use a two's complement representation of signed integers, the C99 standard declares this as C standard declares such use as implementation-defined , and allows all of the following representations:

  • Sign sign and magnitude
  • Twotwo's complement
  • Onesones' complement

This is a specific example of the recommendation MSC14-C. Do not introduce unnecessary platform dependencies.

...

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

Code Block
bgColor#ffcccc
langc

int value;

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

...

Code Block
bgColor#ccccff
langc

int value;

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

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

INT16-C

medium

unlikely

high

P2

L3

Related Guidelines

ISO/IEC 9899:19992011 Section 6.2.6.2, "Integer types"

Bibliography

...