I have compiled the following C Program in Code::Blocks 10.05 on Windows 7.
int main() { unsigned char a=-5; signed char b=-5; char c=-5; printf("%d %d %d \n",a,b,c); printf("%u %u %u \n",a,b,c); } I expected the following output
251 -5 -5 251 251 251 I have reasoned like this,
-5 is represented as 1111 1011 in 2's Complement Notation. Hence 251 will be printed.
But I got the following output.
251 -5 -5 251 4294967291 4294967291 I know 4294967291 is the 32 bit 2's Complement representation of -5.
But why the unsigned char a is printed as 251 instead of 4294967291?
printf()is variadic; it's arguments are promoted – as part of usual arithmetic conversions – tointif they are narrower thanint. See e.g. the relevant C part of cppreference%dshould be used for all character types. (There are other specifiers but they are unnecessary).%ucan only be used withunsigned char(out of the character types). Your%uline causes undefined behaviour.