Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> This is not true if a, b and c are unsigned

True, but this is not valid if they are signed, either. Take

  a = INT_MIN
  b = 1
  c = 2
Then

  a < b + c
is true. But

  a - b < c
invokes undefined behavior.

Edit: missed

> Say that a, b and c are small integers (we don't worry about addition overflow)

Ah, well that makes this example vacuously true, however I'm not sure what the utility in that restriction is. We've only moved the goalposts from "bend[ing] the rules of arithmetic around zero" to bending the rules of arithmetic outside of "small integers".



> however I'm not sure what the utility in that restriction is.

We have moved the goalposts much farther apart.

If we are using a 32 bit integer type, all we need is that a, b and c fit into 31 bits. Then there is no way that b + c or a - b overflow. For a single addition or subtraction, we just need one bit of headroom.

I.e. the values do not actually have to be that small.

There are all kinds of situations in which programs work with small integers, where the calculations could bork if an unsigned creeps in.

A cliff near zero is qualitatively different from clipping at two extremes. An electronic device that clips everything below zero volts will distort even the faintest waveform. One that clips near the power rails has clean headroom.


If b = 0x7fffffff and c = 0x7fffffff, b and c both fit in 31 bits, and b + c overflows to -2 in signed int32 twos-complement math (I think).

If b = 0x40000000 and c = 0x40000000, b and c both fit in 31 bits, and b + c overflows to -2147483648 in signed int32 twos-complement math (I think).

Maybe the definition of "32 bit integer type" you're using is meant to encompass only 32 bits as all unsigned (but then there are a - b terms that would overflow if b > a).

Or perhaps I've gotten something else wrong.


> b and c both fit in 31 bits

They don't fit into a 31 bit two's complement (i.e. signed) representation, in terms of representing their interpretation as the familiar 32 bit INT_MAX.

31 bit two's complement goes from -0x40000000 to 0x3FFFFFFF. There is a 0x7FFFFFFF bit pattern, which represents -0x00000001. It has a sign bit which is 1. (So, adding that to itself does go to -2, but under that interpretation there is no overflow.)

Any pair of values in that range can be added or subtracted in 32 bit two's complement.

Including the most negative value: -0x40000000 + -0x40000000 = -0x80000000.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: