Home > Backend Development > C++ > body text

Why does multiplying integer literal constants overflow even when assigning to a `long long` variable?

Barbara Streisand
Release: 2024-11-11 06:08:02
Original
675 people have browsed it

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
Copy after login

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
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template