How to know whether char is signed or unsigned on your system?
How do I go about this in c++?
Re: How to know whether char is signed or unsigned on your system?
I got help from someone. So we are basically setting char variable x with 255. Then if x is less than 0 then char is unsigned, signed otherwise. Can you explain what is happening when char x = 255? Or is it as simple as storing 255 inside x?
Code:
char x = 0xFF;
if (x < 0) {
printf("char is unsigned\n");
} else if (x >= 0){
printf("char is signed\n");
}
Re: How to know whether char is signed or unsigned on your system?
Note that the code can be simplified because if x is not less than 0 then it must be greater than 0! Also note that the logic is wrong. If char is of type unsigned then x will be greater than 0 and if the type of x is signed then it will be less than 0!
Code:
char x = 0xff;
(x < 0) ? puts("char is signed") : puts("char is unsigned");
eg
Code:
unsigned char u = 0xff;
(u < 0) ? puts("u char is signed") : puts("u char is unsigned");
signed char s = 0xff;
(s < 0) ? puts("s char is signed") : puts("s char is unsigned");
displays
Code:
u char is unsigned
s char is signed
This is all to do with how the bits used to store the data are interpreted. Setting x to 0xff sets all the 8 bits (assuming a char is 1 byte) to 1. If x is unsigned this this is the unsigned value 255, but if x is signed then this is interpreted as -1 using what's called two's complement arithmetic. See https://en.wikipedia.org/wiki/Two%27s_complement
However, as the question refers to c++, there are other c++ ways of doing this using type traits. Consider
Code:
#include <type_traits>
...
cout << boolalpha << is_unsigned<char>::value << endl;
cout << boolalpha << is_signed<char>::value << endl;
which will display true false if char is unsigned and false true if char is signed. See http://www.cplusplus.com/reference/type_traits/
so
Code:
(is_signed<char>::value) ? cout << "char is signed\n" : cout << "char is unsigned\n";
Re: How to know whether char is signed or unsigned on your system?
Thanks, yes I saw my error.