-fwrapv 有什么作用? [英] What does -fwrapv do?
问题描述
任何人都可以提供一些代码示例,它们在使用 fwrapv 与没有编译时表现不同.
Can anyone provide some code examples that act differently when compiled with fwrapv vs without.
它说 -fwrapv 应该假设加法、减法和乘法的有符号算术溢出,使用二进制补码表示进行换行."
It says -fwrapv is supposed to "assume that signed arithmetic overflow of addition, subtraction, and multiplication, wraps using two's-complement representation."
但每当我尝试溢出时,无论是否使用 fwrapv,结果都是一样的.
But whenever I try overflowing the result is the same with or without fwrapv.
推荐答案
想想这个函数:
int f(int i) {
return i+1 > i;
}
从数学上讲,对于任何整数 i
,i+1
应该总是大于 i
.但是,对于 32 位 int
,i
的一个值会使该语句为假,即 2147483647
(即 0x7FFFFFFF
,即INT_MAX
).向该数字添加 1 将导致溢出,并且根据 2 的互补表示,新值将环绕并变为 -2147483648
.因此,i+1>i
变为 -2147483648>2147483647
这是错误的.
Mathematically speaking, i+1
should always be greater than i
for any integer i
. However, for a 32-bit int
, there is one value of i
that makes that statement false, which is 2147483647
(i.e. 0x7FFFFFFF
, i.e. INT_MAX
). Adding one to that number will cause an overflow and the new value, according to the 2's compliment representation, will wrap-around and become -2147483648
. Hence, i+1>i
becomes -2147483648>2147483647
which is false.
当你编译不带-fwrapv
时,编译器会假设溢出是'non-wrapping'并且它会优化那个函数总是返回1
(忽略溢出情况).
When you compile without -fwrapv
, the compiler will assume that the overflow is 'non-wrapping' and it will optimize that function to always return 1
(ignoring the overflow case).
用-fwrapv
编译时,函数不会优化,会有加1比较的逻辑两个值,因为现在溢出是 'wrapping' (即溢出的数字将根据 2 的补码表示来换行).
When you compile with -fwrapv
, the function will not be optimized, and it will have the logic of adding 1 and comparing the two values, because now the overflow is 'wrapping' (i.e. the overflown number will wrap according to the 2's compliment representation).
在生成的程序集中可以很容易地看到差异 - 在右侧窗格中,没有 -fwrapv
,函数总是返回1
(true
).
The difference can be easily seen in the generated assembly - in the right pane, without -fwrapv
, function always returns 1
(true
).
这篇关于-fwrapv 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!