Reputation: 47
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
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