I am puzzled on this code snippet:
#include <climits>
#include <iostream>
int main(void) {
using namespace std;
cout << "long max " << LONG_MAX << endl;
long x = 2 * 1024 * 1024 * 1024;
cout << "2 * 1024 * 1024 * 1024 = " << x << endl;
return 0;
}
I was expecting 2147483648 as it should be, instead I am getting. Using unsigned doesn't seem to help. what gives?
long max 9223372036854775807
2 * 1024 * 1024 * 1024 = -2147483648
An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).
The pseudocode to check against overflow for positive numbers follows: if (a > max_int64 / b) then "overflow" else "ok". To handle zeroes and negative numbers you should add more checks. To calculate carry we can use approach to split number into two 32-digits and multiply them as we do this on the paper.
An integer overflow is a type of an arithmetic overflow error when the result of an integer operation does not fit within the allocated memory space. Instead of an error in the program, it usually causes the result to be unexpected.
In languages where integer overflow can occur, you can reduce its likelihood by using larger integer types, like Java's long or C's long long int. If you need to store something even bigger, there are libraries built to handle arbitrarily large numbers.
Add some L
s*. long x = 2L * 1024L * 1024L * 1024L;
(Technically, as long as one literal is of type long
the others will be promoted to long
)
The overflow happens because 2
, etc. is of type int
by default and the overflow happens before the assignment.
See integer literals which explains the different literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With