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?
- AON is printed
- BOFF is printed
- 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.