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 C Standard declares such use as implementation-defined and allows all of the following representations:

  • Sign and magnitude
  • Two's complement
  • One's 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 one's complement implementations:

Code Block
bgColor#ffcccc
langc
int value;

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

Compliant Solution

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

Code Block
bgColor#ccccff
langc
int value;

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

Automated Detection

Tool

Version

Checker

Description

PRQA QA-C

Include Page
PRQA QA-C_v
PRQA QA-C_v

2940, 2941, 2942, 2943, 2945, 2946, 2947, 2948