6

I have assigned the complement value in an unsigned variable.

Then why this C program outputs a negative number?

#include<stdio.h>
#include<conio.h>

int main()
{
    unsigned int Value = 4;         /*   4 = 0000 0000  0000 0100 */  
    unsigned int result = 0;

    result = ~ Value;               /* -5 = 1111 1111  1111 1011 */  

    printf("result = %d", result);  /* -5             */

    getch();

    return 0;
}
user366312
  • 16,949
  • 65
  • 235
  • 452
  • Your question should be: "Why does the compiler not emit a warning when I compile this code?". The answer is: "Turn up the warnings on the compiler. (eg -Wall)" – William Pursell May 02 '10 at 09:59

2 Answers2

14

The %d format specifier instructs printf to treat the argument as a signed integer. Use %u instead.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
4

It's because %d is the signed int format placeholder, so it's getting converted. Use %u for unsigned.

Adam Ruth
  • 3,575
  • 1
  • 21
  • 20