for every int x: x+1 > x … is this always true?

后端 未结 4 1904
鱼传尺愫
鱼传尺愫 2021-01-18 00:27

I\'m just starting to learn C at school, I\'m trying to get a hold of the basic concepts.

Our homework has a question,

for every int x: x+1 > x

4条回答
  •  感情败类
    2021-01-18 00:58

    Yes, x + 1 adds to the decimal value of 1.

    This will be true almost all of the time. But if you add 1 to INT_MAX (which is 215 - 1 or greater), you might flip the sign. Think about the decimal representation of 0111111 versus 11111111. (Obviously not 32 bits, but the ideas hold.)

    Look up two's complement if you're confused about why it flips. It's a pretty clever implementation of integers that makes addition easy.

    EDIT: INT_MAX + 1 is undefined behavior. Doesn't necessarily become INT_MIN. But since x + 1 is not necessarily > x when x == INT_MAX, then the answer is clearly false!

提交回复
热议问题