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 values or sign-extended for signed types. Arithmetic operations performed on ints yield the same values as on chars and shorts (at least in the low-order bits). HoweverConsequently, bitwise operations on integer types smaller than int
may have unexpected results.
...
In this example, a bitwise complement of port
is first computed and then shifted 4 bits to the right. If both of these operations were are performed on an 8-bit unsigned integer, then result_8
would will have the value 0x0a
. However, port
will is first be promoted to a signed int
, with the following results (on a typical architecture where type int
is 32 bits wide):
...
In this compliant solution, we truncate the negation back down the bitwise complement of port
is converted back to 8 bits. Consequently, result_8
receives is assigned the expected value of 0x0aU
.
...