CertC-INT16

Do not make assumptions about representation of signed integers

Required inputs: IR

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:

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:

int value;

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

Using bitwise operators is safe on unsigned integers:

unsigned int value;

if (scanf("%u", &value) == 1) {
  if (value & 0x1 != 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 Detectable Repairable Priority Level
INT16-C Medium Unlikely No No P2 L3
Excerpt from SEI CERT C Coding Standard: Rules for Developing Safe, Reliable, and Secure Systems (2016 Edition) and SEI CERT C Coding Standard [https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int16-c], Copyright (C) 1995-2026 Carnegie Mellon University. See 9.4 3rd-Party Licenses in the documentation for full details.

Possible Messages

Key

Text

Severity

Disabled

bitop_on_enum

Do not make assumptions about representation of signed integers

None

False

bitop_on_signed

Do not make assumptions about representation of signed integers

None

False

Options

allow_shift_of_constant_if_sign_unchanged

allow_shift_of_constant_if_sign_unchanged : bool = False

Allow shifting (signed) constant expressions, if no set bit is shifted into or beyond the most significant bit (which is used to indicate signedness).
 

require_possibly_negative_operand

require_possibly_negative_operand : bool = True

Only report operands that could actually hold a negative value. The signed representations the C Standard permits (sign/magnitude, ones complement, twos complement) only disagree on how negative values are stored, so this excludes operands known to be non-negative (e.g. OR-combined bit-flag macros).