Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

#include <stdio.h>

int main()
{
    unsigned char i = 0x80;
    printf("%d\n", i<<1);
    return 0;
}

 

  • A.256
  • B.100
  • C.80

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.