...
The program must be careful when performing operations on mixed types. This noncompliant code example shows an idiosyncracy of integer promotions.
| Code Block | ||||
|---|---|---|---|---|
| ||||
int si = -1;
unsigned int ui = 1;
printf("%d\n", si < ui);
|
...
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 | ||||
|---|---|---|---|---|
| ||||
int si = -1;
unsigned ui = 1;
printf("%d\n", si < (int)ui);
|
This program prints 1 as expected. Note that (int)ui is correct in this case only because the value of ui is known to be representable as an int. If this were not known, the compliant solution would need to be written as
| Code Block | ||||
|---|---|---|---|---|
| ||||
int si = /* some signed value */;
unsigned ui = /* some unsigned value */;
printf("%d\n", (si < 0 || (unsigned)si < ui));
|
...
This noncompliant code example demonstrates how performing bitwise operations on integer types smaller than int may have unexpected results.
| Code Block | ||||
|---|---|---|---|---|
| ||||
uint8_t port = 0x5a; uint8_t result_8 = ( ~port ) >> 4; |
...
In this compliant solution, the bitwise complement of port is converted back to 8 bits. Consequently, result_8 is assigned the expected value of 0x0aU.
| Code Block | ||||
|---|---|---|---|---|
| ||||
uint8_t port = 0x5a; uint8_t result_8 = (uint8_t) (~port) >> 4; |
...