Search code examples
c++unsigned-char

Signed and unsigned char


Why are two char like signed char and unsigned char with the same value not equal?

char a = 0xfb; 
unsigned char b = 0xfb;
bool f;
f = (a == b); 
cout << f;

In the above code, the value of f is 0.
Why it's so when both a and b have the same value?


Solution

  • There are no arithmetic operators that accept integers smaller than int. Hence, both char values get promoted to int first, see integral promotion for full details.

    char is signed on your platform, so 0xfb gets promoted to int(-5), whereas unsigned char gets promoted to int(0x000000fb). These two integers do not compare equal.

    On the other hand, the standard in [basic.fundamental] requires that all char types occupy the same amount of storage and have the same alignment requirements; that is, they have the same object representation and all bits of the object representation participate in the value representation. Hence, memcmp(&a, &b, 1) == 0 is true.