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?

  1. Aequal is printed
  2. BIt is a compile error, because ~ cannot be applied to a uint8_t value
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. int and unsigned int are 32 bits. Which of the following is the result when the code above is executed?
  2. unsigned int is 32 bits. Which of the following describes the behavior when the code above is executed?
  3. A program that sets "char c = 200;" and prints c with %d in printf printed −56 when compiled and run with gcc for x86-64 Linux, and 200 with gcc for Arm Linux. Which of the following is the reason for the difference?
  4. Which of the following is the output when the code above, with b++ on the right side of && and ||, is executed?
  5. Which of the following is the output when the switch statement above, which contains a case without break, is executed?