Evaluate bitwise precedence and grouping. For i = 4 and j = 8, what is printed by the following expression sequence using & (AND), ^ (XOR), and | (OR)?
#include
int main()
{
int i = 4, j = 8;
printf("%d, %d, %d
", i | j & j | i, i | j & j | i, i ^ j);
return 0;
}
-
A12, 12, 12
-
B112, 1, 12
-
C32, 1, 12
-
D-64, 1, 12
Answer
Correct Answer: 12, 12, 12
Explanation
Introduction / Context: The task tests operator precedence for bitwise operators in C: & has higher precedence than ^, which has higher precedence than |. Understanding this avoids accidental mis-grouping.
Given Data / Assumptions:
- i = 4 (binary 0100), j = 8 (binary 1000).
- Expression: i | j & j | i, evaluated twice, then i ^ j.
Concept / Approach: Evaluate j & j first, then apply |. For XOR, evaluate directly. No parentheses are present, so rely on precedence rules (& before ^ before |) and left-to-right association within the same precedence level for | and ^.
Step-by-Step Solution:
j & j = 8 i | (j & j) | i = 4 | 8 | 4 = 12 Repeat same calculation for the second field -> 12 i ^ j = 4 ^ 8 = 12Verification / Alternative check: Compute using binary: 0100 | 1000 = 1100 (12); 0100 ^ 1000 = 1100 (12). Both confirm the same decimal result.
Why Other Options Are Wrong:
- 112, 1, 12 and 32, 1, 12 and -64, 1, 12: These ignore precedence and invent unintended groupings or arithmetic.
Common Pitfalls: Assuming all bitwise operators have the same precedence or that evaluation is strictly left-to-right without considering operator ranks.
Final Answer: 12, 12, 12