C Programming Basics
uint8_t a = 0x0F;
if (~a == 0xF0)
printf("equal\n");
else
printf("not equal\n");uint8_t is an 8-bit unsigned integer type and int is 32 bits. Which of the following is the result when the code above is executed?
- Aequal is printed
- BIt is a compile error, because ~ cannot be applied to a uint8_t value
- Cnot equal is printed
Show answer and explanation
Answer: C. not equal is printed
Before ~a is computed, a is converted by integer promotion to the int 0x0000000F. So ~a is not the 8-bit 0xF0 but the 32-bit 0xFFFFFFF0 (−16 as an int), which is not equal to 0xF0 (240). To compare in 8 bits, convert back to an 8-bit type first, as in (uint8_t)~a == 0xF0. This is a mistake that often occurs when inverting and comparing register values.
- A. ~a is computed as an int and becomes 0xFFFFFFF0, so it is not equal to 0xF0.
- B. ~ can be applied to uint8_t values. The value is converted to int before being inverted.
- C. Correct. ~a becomes 0xFFFFFFF0 (−16), which is not equal to 0xF0.