Home  >  Article  >  Backend Development  >  Why does `long long` behave differently than expected in C/C ?

Why does `long long` behave differently than expected in C/C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-08 10:04:01134browse

Why does  `long long` behave differently than expected in C/C  ?

Understanding Long Long in C/C

When working with various data types in C and C , it's crucial to understand the nuances of each type. One common misconception is the behavior of long long.

Consider the following code snippet:

#include <stdio.h>

int main()
{
    int  num1 = 1000000000;
    long num2 = 1000000000;
    long long num3;
    //num3 = 100000000000;
    long long num4 = ~0;

    printf("%u %u %u", sizeof(num1), sizeof(num2), sizeof(num3));
    printf("%d %ld %lld %llu", num1, num2, num3, num4);
    return 0;
}

Compiling this code raises an error when uncommenting the line assigning 100000000000 to num3: "integer constant is too large for long type." However, executing the code with the commented line still prints values larger than 10000000000.

This behavior stems from a misconception about type inference. The literal 100000000000 is an integer constant, but its value exceeds the range of the int data type (32 bits). Therefore, it's intended as a long type constant. However, by default, C and C consider such literals as int, leading to the error.

To resolve this, it's necessary to explicitly specify the type of the literal using a suffix. The LL suffix declares num3 as a long long type:

long long num3 = 100000000000LL;

This change allows the code to compile successfully without any errors or unexpected behavior.

The above is the detailed content of Why does `long long` behave differently than expected in C/C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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