Source:

#include <climits> #include <iostream> int add(int a, int b) { return a + b; } int main() { std::cout << add(INT_MAX, 1) << std::endl; return 0; } 

Conclusion:

-2147483648

Why did this happen? searched did not find the answer.

  • four
    Does the name INT_MAX suggest anything? And in fact - there was a normal overflow. - KoVadim

2 answers 2

You have an int value overflow when adding 1 to the maximum value.

You can try to translate INT_MAX into a binary representation by hand, get a set of units and a zero at the beginning that is responsible for the plus sign. Add 1 in binary form, and get in the sign bit 1 instead of 0 and all the other zeros. If you look at how negative numbers are printed in the machine, you will see that this represents INT_MIN - 1 and all the remaining zeros. Look, for example, in the Windows calculator.

    If, for example, the int type occupies 4 bytes and the system of representation of integers is used with the addition to 2, then INT_MAX can be represented in hexadecimal form as follows

     7FFFFFFF 

    that is, all bits except the sign bit are set to one.

    If we add 1 to this number, we get

     80000000 

    that is, a number with a sign bit set. This is the representation of the smallest negative value for an int type that is INT_MIN .

    This value was displayed on the console in decimal form.

    In the general case, such an assignment for signed integers when overflow occurs is indefinite behavior.