-fwrapv是做什么的? [英] What does -fwrapv do?
问题描述
它表示-fwrapv应该假设加法符号的算术溢出,减法和乘法,使用二进制补码表示进行包装。
但是,每当我尝试溢出时,结果都会与fwrapv相同或不相同。
$ b
int f(int i){
return i + 1> ;一世;
$ / code>
从数学上讲, i + 1 $ c对于任何整数
i
,$ c>应该总是大于 i
。但是,对于32位 int
,有一个值 i
使得该语句为false,即 2147483647
(即 0x7FFFFFFF
,即 INT_MAX
)。根据2的恭维表示,向该数字加1会导致溢出,并且新值将环绕并变为 -2147483648
。因此, i + 1> 1
变成 -2147483648> 2147483647
这是错误的。
当你编译时,如果没有 -fwrapv
,编译器会认为溢出是'不换行',它会优化该函数总是返回 1
(忽略溢出情况)。
当您使用 -fwrapv
编译时,该函数不会是优化,它将具有加1和比较两个值的逻辑,因为现在溢出是'包装'(即溢出的数字将根据2的恭维表示进行包装)。
Can anyone provide some code examples that act differently when compiled with fwrapv vs without.
It says -fwrapv is supposed to "assume that signed arithmetic overflow of addition, subtraction, and multiplication, wraps using two's-complement representation."
But whenever I try overflowing the result is the same with or without fwrapv.
Think of this function:
int f(int i) {
return i+1 > i;
}
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>1
becomes -2147483648>2147483647
which is false.
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).
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是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!