Dannul
Dannul

Reputation: 81

C Unsigned int providing a negative value?

I have an unsigned integer but when i print it out using %d there is sometimes a negative value there?

Upvotes: 7

Views: 12554

Answers (3)

LiraNuna
LiraNuna

Reputation: 67330

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.

Upvotes: 29

int3
int3

Reputation: 13201

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".

Upvotes: 10

nos
nos

Reputation: 229342

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

Upvotes: 4

Related Questions