Discussion
What will be the output of the following C code?
#include <stdio.h>
int main()
{
unsigned int a = 10;
a = ~a;
printf("%d\n", a);
}
Answer: C
Correct answer: -11
Two things happen here. ~ inverts every bit of a, and on a 32-bit machine 10 is 0x0000000A, so ~a is 0xFFFFFFF5.
Then %d prints that bit pattern as a signed int, even though a was declared unsigned. Interpreted as two's complement, 0xFFFFFFF5 is \( -11 \). The general identity is worth remembering:
\[ \mathtt{\sim}x = -x - 1 \]
so \( \mathtt{\sim}10 = -11 \) directly. Printing an unsigned value with %d is itself a mismatch, which is what exposes the bit pattern.
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