tags:

views:

101

answers:

2

hello,

I have this piece of code can you explain me the output

unsigned int x=3;
~x;
printf("%d",x);

output is 10 I am not able to make it how.

I have compiled the code on turbo c

+2  A: 

To print out unsigned values, especially when manipulating bits, use the unsigned format for printf:

printf("%u", x);

I'm not sure you've actually run the code you show. See this:

#include <stdio.h>

int main()
{
    unsigned int x = 3;
    unsigned int y = ~x;

    printf("Decimal. x=%u y=%u\n", x, y);
    printf("Hex. 0x%08X y=0x%08X\n", x, y);
    return 0;
}

Outputs:

Decimal. x=3 y=4294967292
Hex. 0x00000003 y=0xFFFFFFFC

Why the values are as they are should be obvious by basic binary arithmetic (and keeping in mind that C's ~ operator flips the bits of its argument).

Eli Bendersky
+2  A: 

The code as you've posted it won't compile. It will compile if you change ~x to x = ~x;, but then it won't give the output "10".

The ~ operator creates a bitwise inverse of the number given. In binary, the number 3 as an eight-bit integer is represented by the bits 00000011. The ~ operator will replace every one of those bits with its opposite, giving 11111100, which is 252 unsigned, or -4 signed.

You declared x as an unsigned int, which means a 32-bit unsigned value on most platforms. So your original value is 00000000 00000000 00000000 00000011, and the inverse is 11111111 11111111 11111111 11111100, or 4294967292.

JSBangs
The posted code *will* compile, it just won't do anything to `x`...
Mark E
@Mark: no, when JS Bangs wrote his answer there was a missing ; (see edits in question) so the code *wouldn't* compile.
Ramashalanka
@Ramashalanka, fair enough.
Mark E