Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why there is a integer overflow in this multiplication? [duplicate]

Tags:

c++

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
like image 939
Oliver Avatar asked Mar 26 '13 22:03

Oliver


People also ask

Why does integer overflow happen?

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

How do you prevent integer overflow in multiplication?

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.

What is integer overflow problem?

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.

How do you solve integer overflow problems?

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.


1 Answers

Add some Ls*. 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.

like image 136
Jesse Good Avatar answered Sep 27 '22 22:09

Jesse Good