I just executed the following code
main()
{
char a = 0xfb;
unsigned char b = 0xfb;
printf("a=%c,b=%c",a,b);
if(a==b) {
printf("\nSame");
}
else {
printf("\nNot Same");
}
}
For this code I got the answer as
a=? b=?
Different
Why don't I get Same, and what is the value for a and b?
There are 2 cases to consider:
chartype is unsigned by default, bothaandbare assigned the value251and the program will printSame.chartype is signed by default, which is alas the most common case, the definitionchar a = 0xfb;has implementation defined behavior as0xfb(251in decimal) is probably out of range for thechartype (typically-128to127). Most likely the value-5will be stored intoaanda == bevaluates to0as both arguments are promoted tointbefore the comparison, hence-5 == 251will be false.The behavior of
printf("a=%c,b=%c", a, b);is also system dependent as the non ASCII characters-5and251may print in unexpected ways if at all. Note however that both will print the same as the%cformat specifies that the argument is converted tounsigned charbefore printing. It would be safer and more explicit to tryprintf("a=%d, b=%d\n", a, b);With gcc or clang, you can try recompiling your program with
-funsigned-charto see how the behavior will differ.