尝试在我的代码中断中编译以下行:
printf("%llu\n", 0x12345678 * 0x12345678);
我明白了:
program.c:45:34: warning: integer overflow in expression [-Woverflow]
printf("%llu\n", (0x12345678 * 0x12345678));
我该如何解决这个问题?
最佳答案
[根据 @Lundin 接受更正后] 评论
在你的机器上,0x12345678
比 unsigned long long
窄 - 当然是 signed long
或者可能是 int
.
signed long * signed long
仍然是 signed long
并且可能会发生 signed integer 溢出,即 UB。 signed long
的范围小于 0x12345678 * 0x12345678
的数学乘积。通过使用 ULL
后缀,至少可以使用 unsigned long long
数学来完成数学运算。 @BLUEPIXY
printf("%llu\n", 0x12345678ULL * 0x12345678);
// or if the constant can not be changed
printf("%llu\n", 1ULL * SOME_BIG_CONSTANT * SOME_BIG_CONSTANT);
学究注:打印可能比int/unsigned
宽的整数类型时,确保最终计算结果与说明符匹配。考虑到 SOME_BIG_CONSTANT 可能比 unsigned long long
更宽。或者不进行强制转换,并应对潜在的编译器警告。
printf("%llu\n", (unsigned long long) (1ULL * SOME_BIG_CONSTANT * SOME_BIG_CONSTANT));
另见 Why write 1,000,000,000 as 1000*1000*1000 in C?
和 There are reasons not to use 1000 * 1000 * 1000
关于c - 为什么会出现整数溢出,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41253787/