Home > Backend Development > C++ > Why Do Large Integer Literals in For Loops Behave Differently Than Expected?

Why Do Large Integer Literals in For Loops Behave Differently Than Expected?

Linda Hamilton
Release: 2024-12-14 15:47:11
Original
1000 people have browsed it

Why Do Large Integer Literals in For Loops Behave Differently Than Expected?

Type of Integer Literals: Not Int by Default?

Question:

Why does a for loop iterating up to 10 billion take longer than one iterating up to 1 billion?

Answer:

The iteration variable in the loop is 32-bit and overflows, causing an infinite loop. The literal representing 10 billion, despite not having an L suffix, is automatically promoted to a fitting range (at least 64-bit in this case) by the compiler.

C :

According to the C 11 standard ([lex.icon] ¶2), the type of an integer literal without a suffix is the first one from Table 6 where its value can be represented:

Type
int
long int
long long int

Therefore, in this case, the literal is interpreted as a long int or long long int (if long int is 32-bit).

C:

In C99 ([§6.4.4.1]), the rule is similar. The type of an integer constant is determined by the first type from a similar list where its value can be represented.

Implementation-Defined Types:

Both C 11 ([lex.icon] ¶3) and C99 ([§6.4.4.1 ¶5]) allow integer literals to be of "extended integer types" (implementation-specific integer types) if no other valid type is found.

The above is the detailed content of Why Do Large Integer Literals in For Loops Behave Differently Than Expected?. 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