Given unsigned char i = 0x80 in C, what decimal value is printed?\n\n#include<stdio.h>\n\nint main()\n{\n unsigned char i = 0x80; // 128\n printf("%d\n", i << 1);\n return 0;\n}\n\nAssume usual integer promotions apply before the shift.

Difficulty: Easy

Correct Answer: 256

Explanation:


Introduction / Context:
This item checks knowledge of the “usual integer promotions” and how bit shifts are performed in C when the operand is smaller than int. An unsigned char is promoted to int before shifting.



Given Data / Assumptions:

  • i = 0x80 (hex) = 128 (decimal).
  • Left shift by 1 bit → multiply by 2 when no overflow in promoted type.
  • printf uses %d, so it prints the decimal form of the resulting int.


Concept / Approach:
Before evaluating i << 1, i is promoted to int. Thus the operation is 128 << 1 as an int, yielding 256 without truncation during the operation. The result is then passed to printf and printed as a decimal integer.



Step-by-Step Solution:
unsigned char i = 128.Promote: (int)128 << 1 → 256.printf("%d") outputs 256.



Verification / Alternative check:
If you had stored the result back into an unsigned char (e.g., i = i << 1), it would wrap modulo 256 and become 0; but the code prints the promoted result directly.



Why Other Options Are Wrong:
0: would occur only if storing back into 8 bits.100 / 80: unrelated decimal values.



Common Pitfalls:
Forgetting promotions; assuming 8-bit wrap happens during the shift expression itself.



Final Answer:
256

Discussion & Comments

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