What will be the output of the program?
#include <stdio.h>
int main()
{
unsigned char i = 0x80;
printf("%d\n", i<<1);
return 0;
}
Answer: A
Correct answer: 256
The key step is integer promotion. i is an unsigned char holding 0x80, which is 128, but before the shift it is promoted to int - the usual arithmetic conversions apply to the operand of a shift.
The shift therefore happens in a type wide enough to hold the result:
\[ 128 \ll 1 = 256 \]
Had the arithmetic been done in the original 8-bit width, the 1 would have shifted out of the top and the answer would have been 0. Promotion is why it is not, and why %d prints an int rather than a char.
Please log in or register to report this question.