Search code examples
ccharsigned

Why stores 255 in a char variable give its value -1 in C?


I am reading a C book, and there is a text the author mentioned:

"if ch (a char variable) is a signed type, then storing 255 in the ch variable gives it the value -1".

Can anyone elaborate on that?


Solution

  • Assuming 8-bit chars, that is actually implementation-defined behaviour. The value 255 cannot be represented as a signed 8-bit integer.

    However, most implementations simply store the bit-pattern, which for 255 is 0xFF. With a two's-complement interpretation, as a signed 8-bit integer, that is the bit-pattern of -1. On a rarer ones'-complement architecture, that would be the bit pattern of negative zero or a trap representation, with sign-and-magnitude, it would be -127.

    If either of the two assumptions (signedness and 8-bit chars) doesn't hold, the value will be¹ 255, since 255 is representable as an unsigned 8-bit integer or as a signed (or unsigned) integer with more than 8 bits.

    ¹ The standard guarantees that CHAR_BIT is at least 8, it may be greater.