C++ When 1 is added to INT_MAX, why does it returns value of INT_MIN?

Viewed 93

why INT_MAX + 1 returns -2147483648? Can someone please explain why does this happen and does it have to do with 2's compliment?

1 Answers

When you add 1 to INT_MAX you're actually causing signed integer overflow. Formally, this triggers undefined behavior, which means you can't depend on any specific result.

What often happens in practice is that the value will "wrap around". Assuming two's complement representation, INT_MAX is represented as 0x7fffffff. Adding 1 to this gives you 0x80000000 which is the representation of INT_MIN.

But again, this is undefined behavior. There's no guarantee that this will actually happen.

Related