Evaluate this macro-based C program: what integer does it print? #define P printf("%d ", -1 ^ ~0) #define M(P) int main()\ {\ P\ return 0;\ } M(P) Assume typical two’s-complement semantics.
-
A1
-
B0
-
C-1
-
D2
-
ENone of the above
Answer
Correct Answer: 0
Explanation
Introduction / Context:The item tests bitwise reasoning with XOR and NOT, and macro expansion. Understanding two’s-complement behavior for ~0 and the identity x ^ x = 0 is key.
Given Data / Assumptions:
- Expression: -1 ^ ~0.
- In two’s complement, ~0 is all 1 bits, which corresponds to -1 for signed int.
- printf prints a signed decimal integer.
Concept / Approach:If two values have identical bit patterns, their XOR is zero: a ^ a = 0. Since -1 and ~0 are the same all-ones bit pattern, the result is 0.
Step-by-Step Solution:Compute ~0 → all bits 1 → value equals -1 in two’s complement.Compute -1 ^ -1 → 0.printf prints 0.
Verification / Alternative check:Try evaluating with fixed width (e.g., int32): ~0x00000000 = 0xffffffff; -1 is also 0xffffffff; XOR → 0x00000000.
Why Other Options Are Wrong:1, 2, -1: those would require differing bit patterns.
Common Pitfalls:Confusing arithmetic negation with bitwise NOT; assuming ~0 is 0 (it is the opposite).
Final Answer:0