If we are on a platform which supports unsigned char data type then, the char range is from 0 to 255. So,
char c = 255 ;
c ;
cout << c ; // 0 gets stored to c, which corresponds to null character.
But what if we are on a platform which supports signed char (-128 to 127)
char d = 127 ;
d ;
cout << d ; // will it get the value of -128 or 0 ?
If -128, then how can we know the corresponding ASCII symbol for it? (As most websites show symbols for ASCII 0 to 255) Thank you :)
CodePudding user response:
Signed integral types are always a ring of -2^b .. 2^b - 1 since C 20, where b is the number of bits. So, in your second example, if char is 8-bit, you'll likely have -128
[1]. I say 'likely', because technically signed integer overflow is still an UB and anything might happen, so that's one more reason not to depend on it (see below for further reasons).
If you wanted the range and char is 8-bit, 0 .. 255 [1], you'd need to use unsigned char
. This is not a platform-dependent feature.
Strictly speaking, there's no such thing as ASCII codes > 127, however, most platforms indeed define character images for 0..255. In that case, the character printed is as-if you'd reinterpret the char
to unsigned char
. So -1
-> 255
, -2
-> 254
, etc., as long as char
is 8 bits.
Strictly speaking, character range is not necessarily 8 bits; there are platforms with different char size, e.g. 9 bits used to be very common, so you souldn't depend on it at all.
CodePudding user response:
unsigned integer (and as such, the unsigned char
is an integer type) overflow is well-defined; your c == 0
.
But for (signed
) char
§5 [expr]/p4:
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.
So, d
might be anything. -128, 0, 13, 255.
if -128, then how can we know the corresponding ASCII symbol for it?
ASCII is just an interpretation of code points. There's no interpretation for a negative value. So, this question makes no sense.