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:
char
type is unsigned by default, botha
andb
are assigned the value251
and the program will printSame
.char
type is signed by default, which is alas the most common case, the definitionchar a = 0xfb;
has implementation defined behavior as0xfb
(251
in decimal) is probably out of range for thechar
type (typically-128
to127
). Most likely the value-5
will be stored intoa
anda == b
evaluates to0
as both arguments are promoted toint
before the comparison, hence-5 == 251
will be false.The behavior of
printf("a=%c,b=%c", a, b);
is also system dependent as the non ASCII characters-5
and251
may print in unexpected ways if at all. Note however that both will print the same as the%c
format specifies that the argument is converted tounsigned char
before 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-char
to see how the behavior will differ.