Search code examples
c++binarycharsigned

Value of char c = 255 converted to int


My question is about a paragraph in Stroustrup's book the C++ programming language, 4th edition. He brings an example of having

char c = 255; // 255 is ‘‘all ones,’ ’ hexadecimal 0xFF
int i = c;

and explanation of how it will be converted on machines where char is either signed or unsigned.

What will be the value of i? Unfortunately, the answer is undefined. On an implementation with 8-bit bytes, the answer depends on the meaning of the ‘‘all ones’’ char bit pattern when extended into an int. On a machine where a char is unsigned, the answer is 255. On a machine where a char is signed, the answer is −1.

My question is why it will be -1, doesn't it depends on what representation of binary numbers is used on machine? Wouldn't it be 0(-0) if it uses ones' complement and -1 if two's complement?


Solution

  • Quoting C++03 4.7/3:

    If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

    Assuming bytes are 8 bits, this means that in theory you get one of the following:

    • -127 if signed magnitude computer.
    • -0 if one's complement computer.
    • -1 if two's complement computer.

    The former two barely exist in the real world.