Versions Compared

Key

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

...

Every integer type has an integer conversion rank that determines how conversions are performed. The ranking is based on the concept that each integer type contains at least as many bits as the types ranked below it. The following rules for determining integer conversion rank are defined in the C Standard, Section section 6.3.1.1 [ISO/IEC 9899:2011]:

...

The programmer must be careful when performing operations on mixed types. This noncompliant code example shows an idiosyncrasy of integer promotions.:

Code Block
bgColor#FFcccc
langc
int si = -1;
unsigned int ui = 1;
printf("%d\n", si < ui);

In this example, the comparison operator operates on a signed int and an unsigned int. By the conversion rules, si is converted to an unsigned int. Because −1 cannot be represented as an unsigned int value, the −1 is converted to UINT_MAX in accordance with the C Standard, Section section 6.3.1.3, paragraph 2 [ISO/IEC 9899:2011]:

...

The noncompliant code example can be modified to produce the intuitive result by forcing the comparison to be performed using signed int values.:

Code Block
bgColor#ccccff
langc
int si = -1;
unsigned ui = 1;
printf("%d\n", si < (int)ui);

...

This noncompliant code example demonstrates how performing bitwise operations on integer types smaller than int may have unexpected results.:

Code Block
bgColor#FFcccc
langc
uint8_t port = 0x5a;
uint8_t result_8 = ( ~port ) >> 4;

...

Expression

Type

Value

Notes

port

uint8_t

0x5a

 

~port

int

0xffffffa5

 

~port >> 4

int

0x0ffffffa

Whether or not value is negative is implementation-defined.

result_8

uint8_t

0xfa

 

Compliant Solution

...

CERT C++ Secure Coding StandardINT02-CPP. Understand integer conversion rules
ISO/IEC TR 24772:2013Numeric Conversion Errors [FLC]
MISRA - C:2012Rule 10.1 (required)
Rule 10.3 (required)
Rule 10.4 (required)
Rule 10.56 (required)
Rule 10.7 (required)
Rule 12.910.8 (required)
MITRE CWECWE-192, Integer coercion error
CWE-197, Numeric truncation error

...

[Dowd 2006]Chapter 6, "C Language Issues" ("Type Conversions," pp. 223–270)
[ISO/IEC 9899:2011]

Section 6.3.1.1, "Boolean, Characters, and Integers"
Section 6.3.1.3, "Signed and Unsigned Integers"

[Seacord 2013]

Chapter 5, "Integer Security"

 

...