-2

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

pmg
  • 106,608
  • 13
  • 126
  • 198
  • 2
    In C, overflow with `int` can cause anything to happen: it's technically **undefined behavior**. `unsigned int` however is well-behaved and computes stuff `mod (UINT_MAX + 1)`. – pmg May 06 '22 at 15:17
  • 4
    Just a quick hint on good practice: have a look at [*Why should I not #include ?*](https://stackoverflow.com/a/31816096/10805404) – Simon Doppler May 06 '22 at 15:19
  • I compiled this code couple of times and it gives the same output. – Shivam Rana May 06 '22 at 15:21
  • 1
    Have you tried another compiler? another OS? another architecture? another day-of-the-week? – pmg May 06 '22 at 15:23
  • Other compiler-flags, other compiler version, OS update? – Sebastian May 06 '22 at 15:29
  • And it is not only about undefined output, it is about undefined state of the program. It is like overwriting memory or jumping into the middle of the program. – Sebastian May 06 '22 at 15:31

1 Answers1

2

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?

eerorika
  • 232,697
  • 12
  • 197
  • 326