没有类型转换的奇怪输出

Sne*_*ish 5 c casting

我试图通过gcc编译器执行此代码:

#include <stdio.h>
int main()
{
    unsigned long long int x;
    x = 75000 * 75000;
    printf ("%llu\n", x);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但它给出了错误的输出.

然后我尝试了这个:

#include <stdio.h>
int main()
{
    unsigned long long int x;
    x = (unsigned long long)75000 * (unsigned long long)75000;
    printf ("%llu\n", x);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它给出了正确的输出!

为什么会这样?

Mar*_*ers 9

表达式75000 * 75000是两个整数常量的乘法.该表达式的结果也是一个整数,可以溢出.然后将结果分配给unsigned long long,但它已经溢出,因此结果是错误的.

要编写无符号长long常量,请使用ULL后缀.

x = 75000ULL * 75000ULL;
Run Code Online (Sandbox Code Playgroud)

现在乘法不会溢出.