Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

exceeding range for signed char data type

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading