0

There is an interview question in C as below.

int main()
{
   unsigned int a = 9;
   a = ~a;
   printf("%d\n", a);

}

I though it was supposed to be 6 but it is -10. ~a is assinged back to an unsigned integer then printed out. It should not be a negative value. Isn't it? Hoe come?

codexplorer
  • 541
  • 5
  • 21
  • 1
    What was your method for getting 6? – Ry- Jun 17 '20 at 05:44
  • You know the difference between `%d` and `%u`? Doesn't matter what the type of `a` is, it's interpreted matching the format specifier. – Ext3h Jun 17 '20 at 05:45
  • `%d` is for signed numbers. Use `%u` for unsigned. – Barmar Jun 17 '20 at 05:45
  • 1
    `~` does a bitwise NOT, so every bit that was `0` becomes `1` and vice-versa, so the result is basically the largest possible number that can be stored in an `unsigned int`, minus `9`. It's definitively not 6. – Havenard Jun 17 '20 at 05:48
  • By the way the largest possible number that can be stored in an `unsigned int`, if print as `signed`, is `-1`, hence why you got `-10`. – Havenard Jun 17 '20 at 05:49

0 Answers0