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]
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.