Home > Article > Backend Development > Why does multiplying integer literal constants overflow even when assigning to a `long long` variable?
Overflowing Long Long Multiplication
Consider the following code:
long long int n = 2000*2000*2000*2000; // overflow
Why does this code result in an overflow when multiplying integer literal constants and assigning the result to a long long variable?
Compared to the following that work:
long long int n = pow(2000,4); // works long long int n = 16000000000000; // works
Integer literals in C have a default type that depends on their value. In this case, 2000 can fit in an int variable, which is usually a 32-bit type.
Arithmetic operations are performed with the larger type of the operands, but not smaller than int. Thus, in the first case, the multiplication is performed as int*int, resulting in an int result.
The problem arises because the int result may overflow, but the code attempts to store it in a long long variable. C does not infer types based on the destination, so the assignment does not prevent the overflow.
To avoid this issue, you can explicitly cast the integer literals to long long before multiplying them:
long long int n = (long long int)2000*2000*2000*2000;
The above is the detailed content of Why does multiplying integer literal constants overflow even when assigning to a `long long` variable?. For more information, please follow other related articles on the PHP Chinese website!