VMS VMS - 3 years ago 257
C Question

Why unsigned int stills signed?

I create an unsigned int and unsigned char. Then I assign the -10 value, and the char remains unsigned and gives me a value of 246, but the unsigned int takes the -10 value.

#include <stdio.h>
int main ()

unsigned char a;
unsigned int b;
printf("%d\t%d\n", a,b);


Compiling and executing I have this:

246 -10

I have no idea why the unsigned int stills signed, and why the char is unsigned.

Reading the book "The C programming language 2nd edition" I can see char can be unsigned by default depending on the machine.

(I'm running
as a operating system.)

Why the int is signed while I'm declaring as unsigned int, and why the char is taking the value 246?

Is this a compiler or system operating "feature" ?

Answer Source

This is undefined behavior when you pass unsigned integers to %d. Wrong format specifier is UB.

If you assign a negative value to an unsigned variable, it's fine and the value will be taken modulo UINT_MAX + 1 (or UCHAR_MAX + 1), so (-10) % (UCHAR_MAX + 1) = 256 - 10 = 246, and b is 4294967296 - 10 = 4294967286. Unsigned integral overflow is required to wrap-around.

When printf is interpreting these numbers, it finds 246 is suitable for %d, the format specifier for signed int, and 4294967286 is reinterpreted as -10. That's all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download