1

With sufficiently large intA * intB result, this overflows at the 2^31 boundary and you unsurprisingly do not get the intended result.

int64_t value = (intA * intB) - int64A

This, however, produces the expected value.

int value = (intA * intB) - int64A

What's going on at the low level that means that the same (bad) operation stored in an int does the right thing but in an int64_t it does not?

birarduh
  • 762
  • 8
  • 19

2 Answers2

6

It's undefined behavior. Signed overflow is undefined. Undefined means that anything might happen, including the program working just fine.

To go beyond standard boundaries and explain the way this particular instance of undefined behavior behaves, you need low-level information such as the GCC version and the architecture.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
1

Signed integer overflow results in undefined behaviour. You may get the expected value on your machine, but do not rely on it. It may crash on other machines, or give the wrong answer.

What's likely happening is that on your machine, int obeys the laws of modular arithmetic modulo 2^32, and the conversion from int64_t to int simply takes the remainder modulo 2^32 (discarding high-order bits). So, if the expected value fits into an int, that's the value you get, but if you store it in a int64_t, the high order bits are garbage.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312