I want to add two numbers which is the largest values that a long long integer can hold; and print it. If I don\'t store the value of sum in a variable, I just print it usin
Since long long
is signed, the addition overflows. This is Undefined Behavior and anything may happen. It's unlikely to format your harddisk, especially in this simple case.
Once Undefined Behavior happens, you can't even count on std::cout
working after that.
If you don't want to overflow, then you need to use a "long integer" library, such as Boost.Multiprecision. You can then perform arbitrary-long integer/f.p. operations, such as
#include <iostream>
#include <limits>
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
using namespace boost::multiprecision;
cpp_int i; // multi-precision integer
i = std::numeric_limits<long long>::max();
std::cout << "Max long long: " << i << std::endl;
std::cout << "Sum: " << i + i << std::endl;
}
In particular, Boost.Multiprecision is extremely easy to use and integrates "naturally" with C++ streams, allowing you to treat the type almost like a built-in one.
No, at first it counts (theLastValueOfLongLong + theLastValueOfLongLong)
(which causes overflow or freezes at max value available) and then it sends result into cout.<<(long long)
operator
It's the same as:
long long temp = theLastValueOfLongLong + theLastValueOfLongLong;
cout << temp;
temp
will contain the result of the addition, which will be undefined because you get an overflow, and then it will cout that result what ever it's value is.