You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 20 Next »

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

  • sign and magnitude
  • two's complement
  • ones' complement

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

Noncompliant Code Example

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

int value;

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

Compliant Solution

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

int value;

if (scanf("%d", &value) == 1) {
  if (value % 2 != 0) {
    /* 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

INT16-C

medium

unlikely

high

P2

L3

Related Guidelines

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

Bibliography


  • No labels