What I know about unsigned numerics (unsigned short, int and longs), that It contains positive numbers only, but the following simple program successfully assigned a negativ
Signed int and unsigned int are the same size in memory, the only difference between them is how you intepret them. Signed values use a twos complement representation.
If you put 0xFFFFFFFF in a 4 byte memory location, and then ask what is the value in there? Well if we interpret it as a signed int, then it is -1, but if we interpret it as an unsigned int then the value is 4294967295. Either way it's the same bit pattern, the difference is what meaning you give it.
When you assigned 10 - 20 into an unsigned int, you calculated a value of -10 (C doesn't do overflow or underflow checking), that's a bit pattern of 0xFFFFFFF6, which means -10 in a signed int or 4294967286 in an unsigned int. If you then tell the compiler (by using %i) to print a signed int then it interprets that bit pattern as a signed int and prints -10, if you told the compiler (by using %u) to print an unsigned int then it interprets that bit pattern as unsigned and prints 4294967286.
%i
is the format specifier for a signed integer; you need to use %u
to print an unsigned integer.
Because unsigned int value that is stored in sum is treated like signed decimal integer in printf %i
With printf
, the %i
format outputs a signed int
. Use %u
to output an unsigned int
. This is a common issue when beginning C programming. To address your question, the result of v1 - v2
is -10, but sum
is an unsigned int
, so the real answer is probably something like 4294967286 (232 - 10). See what you get when you use The subtraction of %i from %i is %u \n
. :)