Discussion
What will be the output of the following C code?
#include <stdio.h>
int main()
{
int x = -2;
x = x >> 1;
printf("%d\n", x);
}
Answer: B
Correct answer: -1
\( -2 \) in two's complement is ...11111110. Right-shifting a signed negative value is implementation-defined, and every common compiler performs an arithmetic shift, propagating the sign bit into the vacated position.
That gives ...11111111, which is \( -1 \). The result is also what integer division would give with truncation towards negative infinity, which is why the arithmetic shift is chosen. A logical shift would bring in a zero at the top and give a large positive number instead.
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