Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the range of signed char -127 to 127 in C++11? [duplicate]

Tags:

c++

c++11

I was reading through The C++ Programing language 4th Edition by Bjarne Stroustrup and i was not able to fully understand the following paragraph mentioned in 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 outputs the the integer value of any character you care to input:

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

The notation int{c} gives the integer value for a character c (‘‘the int we can construct from c’’). The possibility of converting a char to an integer raises the question: is a char signed or unsigned? The 256 values represented by an 8-bit byte can be interpreted as the values 0 to 255 or as the values −127 to 127. No, not −128 to 127 as one might expect: the C++ standard leaves open the possibility of one’s-complement hardware and that eliminates one value; thus, a use of −128 is nonportable. Unfortunately, the choice of signed or unsigned for a plain char is implementation defined. C++ provides two types for which the answer is definite: signed char, which can hold at least the values −127 to 127, and unsigned char, which can hold at least the values 0 to 255.

What is the possibility of one's complement hardware that c++ standard leaves? Is it to avoid the same representation of +128 and -128 in 8 bit?

like image 230
Shobhit Sharma Avatar asked Apr 16 '15 09:04

Shobhit Sharma


2 Answers

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

Same with signed magnitude representation.

like image 186
gnasher729 Avatar answered Nov 15 '22 23:11

gnasher729


There are several ways to represent signed numbers, and which method is used is dictated by the hardware of arithmetic unit of the CPU. Although the 2's complement representation has become dominant, C and C++ still make it a point that old hardware that uses different representations must be supported.

Note that a signed char may have a much wider range, such as –231 to 231 – 1, if byte is 32-bit on a particular architecture. –127 to 127 is the minimum minimorum that any compliant implementation is required to permit.

like image 26
ach Avatar answered Nov 16 '22 00:11

ach