Evaluate this macro-based C program: what integer does it print?\n\n#define P printf("%d\n", -1 ^ ~0)\n#define M(P) int main()\\n {\\n P\\n return 0;\\n }\nM(P)\n\nAssume typical two’s-complement semantics.

Difficulty: Easy

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

More Questions from Bitwise Operators

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion