Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 * 1000000000 overflows as an int, but the variable is long long. Why? [duplicate]

I have a simple c++ app that performs the following calculations

long long calcOne = 3 * 100000000;     // 3e8, essentially
long long calcTwo = 3 * 1000000000;    // 3e9, essentially
long long calcThree = 3 * 10000000000; // 3e10, essentially

If I write the result of each calculation I get the following output:

calcOne = 300000000
calcTwo = -1294967296
calcThree = 30000000000

So why does the second calculation fail? As far as I can tell it is within the limits of a long long type (calcThree was larger...).

I am using Visual Studio 2015 on Windows 10. Thanks in advance.

like image 507
John Voss Avatar asked Mar 22 '17 18:03

John Voss


2 Answers

Integer constants are, by default ints.

1000000000

That can fit into an int. So, this constant gets parsed as an int. But multiplying it by 3 overflows int.

10000000000

This is too big to an int, so this constant is a long long, so the resulting multiplication does not overflow.

Solution: explicitly use long long constants:

long long calcOne = 3 * 100000000LL;     // 3e8, essentially
long long calcTwo = 3 * 1000000000LL;    // 3e9, essentially
long long calcThree = 3 * 10000000000LL; // 3e10, essentially
like image 84
Sam Varshavchik Avatar answered Sep 20 '22 03:09

Sam Varshavchik


What you do with a result doesn't affect how that result is calculated. So the fact that you store the result in a long long doesn't change the fact that the numbers you multiplied in the second line of code were not long longs and so they overflowed. In the third line of code, the constant is a long long, so the multiplication is performed on long longs.

like image 42
David Schwartz Avatar answered Sep 24 '22 03:09

David Schwartz