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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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_BITis at least 8, it may be greater.