All char and short integer types are promoted to int or unsigned int before they are used in expressions. Consequently, they receive high-order bits. These bits are either Integer types smaller than int
are promoted when an operation is performed on them. If all values of the original type can be represented as an int
, the value of the smaller type is converted to an int
; otherwise, it is converted to an unsigned int
(see INT02-C. Understand integer conversion rules). If the conversion is to a wider type, the original value is zero-extended for unsigned chars and shorts, or are signvalues or zero-extended for signed chars and shortstypes. Arithmetic operations performed on ints yield the same values as on chars and shorts (at least in the low-order bits). However, bitwise operations may yield surprising effectshave unexpected results..
Noncompliant Code Example
This noncompliant code example demonstrates how promotion to int
yields surprising effectsperforming bitwise operations on short types can result in unexpected behavior.
Code Block | ||
---|---|---|
| ||
uint8_t port = 0x5aU; uint8_t result_8 = ( ~port ) >> 4; |
...