# c - Why unsigned int contained negative number

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 negative number to an unsigned int:

`` 1 /*2 * =====================================================================================3 *4 * Filename: prog4.c5 *6 * =====================================================================================7 */89 #include <stdio.h>1011 int main(void){1213 int v1 =0, v2=0;14 unsigned int sum;1516 v1 = 10;17 v2 = 20;1819 sum = v1 - v2;2021 printf("The subtraction of %i from %i is %i \n" , v1, v2, sum);2223 return 0;24 }``

The output is :

`The subtraction of 10 from 20 is -10`

`%i` is the format specifier for a signed integer; you need to use `%u` to print an unsigned integer.

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`. :)

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.

Because unsigned int value that is stored in sum is treated like signed decimal integer in printf %i