C Programming Basics

unsigned int reg = 0x04;
if (reg & 0x04 == 0x04)
    printf("ON\n");
else
    printf("OFF\n");

The code above was written to check whether bit 2 of the register value reg is 1. Which of the following is the result when it is executed?

  1. AON is printed
  2. BOFF is printed
  3. CIt is a compile error, because & and == cannot be written together
Show answer and explanation

Answer: B. OFF is printed

In C, the comparison == has higher precedence than the bitwise AND &. So the condition is parsed as reg & (0x04 == 0x04); since 0x04 == 0x04 is 1, the result is 0x04 & 1 = 0, which is false, and OFF is printed. To get the intended meaning, add parentheses as in (reg & 0x04) == 0x04. It is grammatically valid, so there is no error, but gcc's -Wall gives a warning.

  • A. == is evaluated first, so the condition becomes reg & 1, which is 0 and false.
  • B. Correct. It is parsed as reg & (0x04 == 0x04), giving 0x04 & 1 = 0.
  • C. The expression is grammatically valid, so it compiles. gcc's -Wall gives a warning.
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. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above is executed?
  2. uint8_t is an 8-bit unsigned integer type. Which of the following is the output when the code above, which increments x ten times, is executed?
  3. unsigned char is 8 bits and int is 32 bits. Which of the following is the output when the code above is executed?
  4. 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?
  5. int and unsigned int are 32 bits. Which of the following is the result when the code above is executed?