Home > Backend Development > C++ > Why Does Multiplying Integer Literals in a `long long int` Assignment Lead to Overflow?

Why Does Multiplying Integer Literals in a `long long int` Assignment Lead to Overflow?

DDD
Release: 2024-11-08 08:28:01
Original
506 people have browsed it

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

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:

  • char * char will invoke operator*(int,int) -> int
  • char * int will invoke operator*(int,int) -> int
  • long * int will invoke operator*(long,long) -> long

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:

  • Use 2000LL explicitly, which represents a long long int literal.
  • Use pow(2000,4) to perform the calculation as a double and then assign it to the long long int variable.
  • Directly assign the large integer value, such as 16000000000000, to the long long int variable.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template