If your input qualifier is signed
, be careful of sign bit, if sign bit is 1, you will get negative value. Though x
is signed char
, you are expecting 1 byte
value but you are getting 4 byte
value because of sign bit copy mechanism.
x value :
x = -1 = 0000 0000 0000 0000 0000 0000 1111 1111
|
sign bit, this bit get's copied into remaining bytes, so it becomes like
= 1111 1111 1111 1111 1111 11111 1111 1111 => calculates this => 4294967295
= |
sign bit , now you are printing in %u format i.e unsigned so it will ignore signed bit and you are getting big value.
Same if you are printing in %d
or %i
format
printf("%d\n", x); // it prints -1 bcz %d will check sign bit which is 1 i.e it will prints -ve value, so it's prints -1
I just tried to explains why you are getting such output but It's undefined behaviour
as mentioned in some comments if you are not using correct format specifier. you can refer different C standard.
EDIT : to justify my point(linux machine) let's consider below code
int main()
{
unsigned char x = -1;
printf("%u\n",x);
/*In above printf input is unsigned, so compiler won't
check sign bit, even though sign bit is 1, result
will be +ve only. */
printf("%d\n",x);//some of you may expects -1 because of %d, it's wrong.
/* In above printf it's printing 255 not because of format
specifier, it's because of your input qualifier(which is
unsigned in this case) */
return 0;
}