Search code examples
c++precisioninteger-overflow

Is it possible to calculate the value after overflow?


I understand that if 1 is added to INT_MAX it will overflow and we will get the negative maximum. It is connected in a cycle. In the code below can I calculate the value after overflow.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a = 100000;
    int b = 100000;
    int c = a*b;
    cout<<c;
    return 0;
}

Output: 1410065408

Is it possible to calculate this number. How is multiplication happening internally in this case


Solution

  • I understand that if 1 is added to INT_MAX it will overflow and we will get the negative maximum.

    You've misuderstood. If 1 is added to INT_MAX, then the behaviour of the program is undefined.

    can I calculate the value after overflow.

    After signed integer overflow, the behaviour of the program is undefined, so doing anything is pointless.


    If you were to use unsigned integers, then the result of any operation will be congruent with the "mathematically correct" result modulo M where M is the number of representable values i.e. max+1.

    For example if unsigned is 32 bits, 100'000u * 100'000u would be 10'000'000'000 which is congruent with 1'410'065'408 modulo M=4'294'967'295. You can find the representable congruent value by repeatedly subtracting or adding M until the result is representable.

    Another example of modular arithmetic that you may be familiar with is the clock. If you add 123 hours to a 24 hour clock starting from midnight, then what time will it show? If you add 10'000'000'000 hours to a 4'294'967'295 hour clock, what time will it show?