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

后端 未结 5 1124
夕颜
夕颜 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:54

    Try it in decimal. Suppose we can only have 3 digits. So our unsigned range is 0 - 999.

    Let's see if 999 can actually behave as -1 (signed):

    42 + 999 = 1041
    

    Because we can only have 3 digits, we drop the highest order digit (the carry):

    041 = 42 - 1
    

    This is a general rule that applies to any number base.

提交回复
热议问题