I am trying to understand the phenomenon of overflow and decided to demonstrate the same by executing the piece of code provided below:
#include <bits/stdc .h>
using namespace std;
int main(){
int a = 100000;
int b = 100000;
cout << a * b << endl;
long int c = a * 1LL * b;
cout << c;
return 0;
}
The idea is that simply multiplying a and b (as done in line 6) would result in an integer overflow as 10^10 falls outside the range of the integer data type. To overcome this, the product (a*b) is multiplied with the literal '1LL' (as shown in line 7). The problem is that integer overflow still takes place as the output of the program is:
1410065408
1410065408
It's possible that I am making a super silly mistake somewhere, but I have spent a sufficient amount of time trying to understand where it's going wrong and am yet to find the reason. Hoping for some help/guidance here :)
CodePudding user response:
Type of 1LL
is long long int
. Its size is at least 8 bytes. Type of c
is long int
. Its size is at least 4 bytes. Thus you may still have overflow. To avoid this you may use auto
:
#include <iostream>
#include <cstdint>
int main() {
std::uint32_t a = 100'000;
std::uint32_t b = 100'000;
auto r1 = a * b;
auto r2 = static_cast<std::uint64_t>(a) * b;
std::cout << "r1 = " << r1 << '\n'
<< "r2 = " << r2 << '\n';
}
CodePudding user response:
Seems to be environment problem - works fine for me.
cat long_int_ex.cpp; g -O2 long_int_ex.cpp ; a.out; g --version
#include <bits/stdc .h>
using namespace std;
int main(){
int a = 100000;
int b = 100000;
cout << a * b << endl;
long int c = a * 1LL * b;
cout << c << endl;
return 0;
}
1410065408
10000000000
g (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.