尝试在我的代码中断中编译以下行:
printf("%llu\n", 0x12345678 * 0x12345678);
我明白了:
program.c:45:34: warning: integer overflow in expression [-Woverflow]
printf("%llu\n", (0x12345678 * 0x12345678));
我该如何解决这个问题?
答案 0 :(得分:1)
[按照@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("%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