C Unsigned int providing a negative value?

Solution 1:

Printing %d will read the integer as a signed decimal number, regardless of its defined type.

To print unsigned numbers, use %u.

This happens because of C's way to handle variable arguments. The compiler just pulls values from the stack (typed as void* and pointing to the call stack) and printf has to figure out what the data contains from the format string you give it to.

This is why you need to supply the format string - C has no way of RTTI or a 'base class' (Object in Java, for example) to get a generic or predefined toString from.

Solution 2:

This should work:

unsigned int a;
printf("%u\n", a);

Explanation: On most architectures, signed integers are represented in two's complement. In this system, positive numbers less than 2**(N-1) (where N = sizeof(int)) are represented the same way regardless whether you are using an int or a unsigned int. However, if the number in your unsigned int is larger than 2**(N-1), it represents a negative signed number under two's complement -- which is what printf gave you when you passed it "%d".

Solution 3:

%d means printf will interpret the value as an int(which is signed). use %u if it is an unsigned int.