Why is a signed char from -127 to 127 in C ++ 11?

I read Bjarne Stroustrup on the fourth edition of the C ++ Programming Language, and I was not able to fully understand the next paragraph mentioned on page 141.

Each character has an integer value in the character set used by the implementation. For example, the value of 'b' is 98 in the ASCII character set. Here is a loop that prints the integer value of any character you want to enter:

void intval() { for (char c; cin >> c; ) cout << "the value of '" << c << "' is " << int{c} << '\n'; } 

The notation int {c} gives an integer value for the character c ('' int, which we can build from c). The ability to convert char to an integer raises the question: is char signed or unsigned? 256 values ​​represented by an 8-bit byte can be interpreted as values ​​from 0 to 255 or as values ​​from -127 to 127. No, not from -128 to 127, as you might expect: the C ++ standard leaves open the possibility of of them - addition of equipment and excludes one value; thus, using -128 is intolerable. Unfortunately, the choice of signed or unsigned for a simple char is determined by the implementation. C ++ provides two types for which the answer is defined: signed char, which can contain at least values ​​from -127 to 127, and unsigned char, which can contain at least values ​​from 0 to 255.

What is the possibility of using one additional equipment, which leaves the C ++ standard? Should the same representations of +128 and -128 in 8 bits be avoided?

+5
source share
2 answers

An 8-bit signed integer using one complement representation can only have values ​​from -127 to -0 and from +0 to +127. This is because there are two ways to represent zero; positive zero and negative zero.

Same thing with the declaration of a signed value.

And please change the name of your question. A “sing” char is one that has come too close to the fire.

+11
source

There are several ways to represent signed numbers, and which method is used by the arithmetic unit of the CPU. Although the view with two additions has become dominant, C and C ++ are still betting that older hardware using different views should be supported.

Note that a signed char can have a much wider range, such as -2 31 to 2 31 - 1, if the byte is 32-bit on a specific architecture. -127 to 127 is the minimum minimum level required to complete any compatible implementation.

+2
source

All Articles