user366312
user366312

Reputation: 16998

Why this C program outputs a negative number?

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

Upvotes: 6

Views: 1851

Answers (2)

Adam Ruth
Adam Ruth

Reputation: 3655

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

Upvotes: 4

Marcelo Cantos
Marcelo Cantos

Reputation: 186058

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

Upvotes: 14

Related Questions