How to check if plain chars are signed or unsigned?

c++, char, syntax

Solution

Some alternatives:

const bool char_is_signed = (char)-1 < 0;

#include <climits>
const bool char_is_signed = CHAR_MIN < 0;

And yes, some systems do make plain `char` an unsigned type. Examples I've encountered: Cray T90, Cray SV1, Cray T3E, SGI MIPS IRIX, IBM PowerPC AIX. And any system that uses EBCDIC pretty much has to make plain `char` unsigned so that all basic characters have non-negative values. (And some compilers have an option to control the signedness of `char`, such as gcc's `-fsigned-char` and `-funsigned-char`.)

But `std::numeric_limits<char>::is_signed`, as suggested by Benjamin Lindley's answer, probably expresses the intent more clearly.

(On the other hand, the methods I suggested can also be applied to C.)

Problem

Apparently there is a possibility that plain `char` can be either signed or unsigned by default. Stroustrup writes: It is implementation-defined whether a plain char is considered signed or unsigned. This opens the possibility for some nasty surprises and implementation dependencies. How do I check whether my chars are signed or unsigned? I might want to convert them to `int` later, and I don't want them to be negative. Should I always use `unsigned char` explicitly?

Original source

Related problems