C-为什么我会得到整数溢出,以及如何修复它



试图编译我的代码中的以下行:

printf("%llun", 0x12345678 * 0x12345678);

我明白了:

program.c:45:34: warning: integer overflow in expression [-Woverflow]
     printf("%llun", (0x12345678 * 0x12345678));

我该如何修复?

[在接受校正后@lundin]注释

在您的机器上,0x12345678unsigned long long窄 - 当然是signed longint

signed long * signed long仍然是signed long,可能会遭受签名的整数溢出,即UB。您的signed long的范围小于0x12345678 * 0x12345678的数学产品。通过使用ULL后缀,至少使用unsigned long long数学完成数学。@bluepixy

printf("%llun", 0x12345678ULL * 0x12345678);
// or if the constant can not be changed
printf("%llun", 1ULL * SOME_BIG_CONSTANT * SOME_BIG_CONSTANT);

pedantic注意:当打印可能比int/unsigned宽的整数类型时,确保最终计算结果与指定符匹配。考虑到某些_big_constant可能比unsigned long long宽。或放下铸件,并应对潜在的编译器警告。

printf("%llun", (unsigned long long) (1ULL * SOME_BIG_CONSTANT * SOME_BIG_CONSTANT));

另请参见为什么在C?而且有理由不使用1000 * 1000 * 1000

最新更新