c - 为什么会出现整数溢出,如何解决?

标签 c overflow

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

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

我明白了:

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

我该如何解决这个问题?

最佳答案

[根据 @Lundin 接受更正后] 评论

在你的机器上,0x12345678unsigned 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/

相关文章:

java - Java中的整数溢出

HTML,溢出 :scroll, 和 float

c - for循环无故停止

c - C 中的二进制搜索

将多个数组复制到一个数组中

javascript - jQuery 问题 : body overflow vs body margin

html - 列表溢出滚动

html - 使用 scrollme js 脚本时,它会在手机上从左到右滚动

c - 结构体动态链表中的内存分配

c - 将 Tcl_Filesystem 替换为副本时,tcl "open"命令不起作用