Home > Article > Backend Development > Why Does Multiplying Integer Literals in a `long long int` Assignment Lead to Overflow?
Overflow in Long Long Int Assignment: Why Multiplying Integer Literals Fails
In the provided code snippet, three long long integer assignments are attempted:
long long int n = 2000*2000*2000*2000; // overflow long long int n = pow(2000,4); // works long long int n = 16000000000000; // works
While the third assignment succeeds, why does the first one overflow despite using a long long int?
Understanding Integer Types
The reason for the overflow lies in the nature of integer types. By default, integer literals are assigned the smallest type that can represent their value without being smaller than int. In the given case, 2000 is an int, which typically occupies 32 bits on most systems.
Multiplication Rules
Arithmetic operators, such as multiplication, are invoked with the larger of the two types involved, but not smaller than int. For instance:
However, int * int still invokes operator*(int,int) -> int.
Type Promotion and Overflow
In the overflowing assignment, 2000*2000*2000*2000 involves multiplying 4 int values, resulting in an integer larger than what int can hold. Despite the final result being stored in a long long int variable, the multiplication occurs with ints.
Resolving the Overflow
To avoid the overflow, one can use the following approaches:
The above is the detailed content of Why Does Multiplying Integer Literals in a `long long int` Assignment Lead to Overflow?. For more information, please follow other related articles on the PHP Chinese website!