试图编译我的代码中的以下行:
printf("%llun", 0x12345678 * 0x12345678);
我明白了:
program.c:45:34: warning: integer overflow in expression [-Woverflow]
printf("%llun", (0x12345678 * 0x12345678));
我该如何修复?
[在接受校正后@lundin]注释
在您的机器上,0x12345678
比unsigned long long
窄 - 当然是signed long
或int
。
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