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

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);
    }

 

  • A.-9
  • B.-10
  • C.-11
  • D.10

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.