Discussion
What will be the output of the program?
#include <stdio.h>
int main()
{
int i = 4;
i = i << 2 | i >> 1;
printf("%d", i);
return 0;
}
Answer: C
Correct answer: 18
The key is operator precedence: the shift operators bind more tightly than the bitwise OR, so the expression groups as (i << 2) | (i >> 1), not as some left-to-right reading.
With \( i = 4 \), which is 00000100:
i << 2 moves the bits two places left, giving 00010000 = 16 - a left shift by \( n \) multiplies by \( 2^{n} \), and \( 4 \times 4 = 16 \).i >> 1 moves them one place right, giving 00000010 = 2, that is \( 4 / 2 \).
ORing the two combines their set bits, and since they occupy different positions nothing overlaps: 00010000 | 00000010 = 00010010 = \( 16 + 2 = \) 18.
Both shifts read the original value of i; the assignment happens only once the whole right-hand side has been evaluated, so the left shift does not feed the right one.
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