Mohaimin Malik
Mohaimin Malik

Reputation: 47

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

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

Upvotes: 2

Views: 1743

Answers (1)

dbush
dbush

Reputation: 224377

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.

Upvotes: 6

Related Questions