Topics / C Programming / Q17
Is char signed or unsigned, and why does it matter?
Short answer: It is implementation-defined. Plain char is a distinct type from both signed char and unsigned char, and it behaves like one of them depending on the platform: signed on x86 (and on Arm for Windows/macOS), unsigned on most Arm Linux and Arm bare-metal toolchains (AAPCS), PowerPC and RISC-V. Code that stores byte values above 127 in a plain char can behave differently on different targets.
char c = 0xE9; /* 233 if unsigned, -23 if signed */
if (c > 127) { ... } /* never true where char is signed */
int table[256];
table[c]++; /* table[-23] where char is signed: out of bounds! */
while ((c = getchar()) != EOF) { ... } /* bug: getchar returns int; with unsigned char
the loop never ends, with signed char a 0xFF byte
looks like EOF */
Rules to follow
- Use
charonly for text. - Use
uint8_t(orunsigned char) for raw bytes, buffers, and protocol data. - Cast to
unsigned charbefore passing acharto<ctype.h>functions (isdigit((unsigned char)c)) and before using it as an array index. - Store the result of
getchar()/fgetc()in anint. - GCC options
-funsigned-char/-fsigned-charforce one behaviour;-Wchar-subscriptswarns on indexing withchar.
Related trivia: sizeof(char) is 1 by definition (a "byte" in C is a char, which is CHAR_BIT bits, almost always 8). In C, a character constant like 'a' has type int, so sizeof('a') is 4 on a 32-bit target, while in C++ it is char and sizeof('a') is 1.