Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this C program outputs a negative number?

Tags:

c

unsigned

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;
}
like image 951
user366312 Avatar asked May 02 '10 09:05

user366312


1 Answers

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

like image 94
Marcelo Cantos Avatar answered Oct 01 '22 19:10

Marcelo Cantos