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;
}
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.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development