0

can you explain why i am getting an integer overflow in first code but not in second?

#include<bits/stdc++.h>
using namespace std;
#define ch "\n"
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long int g = (1000000 * 2) * 1000000;
    // long long int k = f * 1000000;
    cout << g % 10000003;
    return 0;
}

'''

#include<bits/stdc++.h>
using namespace std;
#define ch "\n"
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long int f = 1000000 * 2;
    long long int k = f * 1000000;
    cout << k % 10000003;
    return 0;
}

second code is giving correct output while first is showing error. error is shown below.

 warning: integer overflow in expression of type 'int' results in '-1454759936' [-Woverflow]
    8 |  long long int g = (1000000 * 2) * 1000000;
      |                    ~~~~~~~~~~~~~~^~~~~~~~~
[Finished in 0.8s]
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • note that its a warning, not an error. Its a warning that you should treat as error, but still the distinction is relevant, because warnings can be missed, errors not – 463035818_is_not_an_ai Mar 17 '21 at 12:23

1 Answers1

2

All the literals in (1000000 * 2) * 1000000 are int types, and the compiler is warning you that this overflows the int on your platform.

It doesn't matter that you are assigning the result of this expression to a different type.

One solution is to use (2ll * 1000000) * 1000000 which forces the implicit conversion of the other terms.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483