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

后端 未结 5 1131
夕颜
夕颜 2021-01-03 06:29

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

5条回答
  •  鱼传尺愫
    2021-01-03 06:59

    That is not guaranteed behavior. To quote ANSI/ISO/IEC 9899:1999 §6.3.1.3 (converting between signed and unsigned integers) clause 3:

    Otherwise, the new type is signed and the value cannot be represented in it;
    either the result is implementation-defined or an implementation-defined signal
    is raised.
    

    I'll leave the bitwise/2's complement explanations to the other answers, but standards-compliant signed chars aren't even guaranteed to be too small to hold 255; they might work just fine (giving the value 255.)

提交回复
热议问题