为什么我会得到整数溢出,我该如何解决?

时间:2016-12-21 01:26:17

标签: c overflow

尝试在我的代码中断中编译以下行:

printf("%llu\n", 0x12345678 * 0x12345678);

我明白了:

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

[按照@Lundin]评论

接受更正后

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

signed long * signed long仍然是signed long,可能会遇到带符号整数溢出,即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