I have the following code:
#include <stdio.h>
int main() {
unsigned int a = -1;
int b = -1;
printf("%x\n", a);
printf("%x\n", b);
printf("%d\n", a);
printf("%d\n", b);
printf("%u\n", a);
printf("%u\n", b);
return 0;
}
The output is:
ffffffff
ffffffff
-1
-1
4294967295
4294967295
I can see that a value is interpreted as signed or unsigned according to the value passed to printf
function. In both cases, the bytes are the same (ffffffff
). Then, what is the unsigned
word for?
In the hexadecimal it can't get a negative value. So it shows it like ffffffff.
The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).
When you initialize unsigned int a to -1;
it means that you are storing the 2's
complement of -1
into the memory of a
.
Which is nothing but 0xffffffff
or 4294967295
.
Hence when you print it using %x or %u
format specifier you get that output.
By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.
Like with unsigned int
: the range is from 0 to 4,294,967,295
and int
: the range is from -2,147,483,648 to 2,147,483,647
For more info on signedness refer this
Having unsigned
in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1
and 4294967295
have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.
The statement unsigned int a = -1;
is converting -1
in two's complement and assigning the bit representation in a
. The printf()
specifier x
, d
and u
are showing how the bit representation stored in variable a
looks like in different format.
Source: Stackoverflow.com