g ++严格溢出,优化和警告 [英] g++ strict overflow, optimization, and warnings
问题描述
在使用严格溢出标志编译以下内容时,它在第二个测试中告诉我,r可能不是我认为的:
When compiling the following with the strict overflow flag, it tells me, on the 2nd test that r may not be what I think it could be:
int32_t r(my_rand());
if(r < 0) {
r = -r;
if(r < 0) { // <-- error on this line
r = 0;
}
}
错误是:
/build/buildd/libqtcassandra-0.5.5/tests/cassandra_value.cpp:
In function 'int main(int, char**)':
/build/buildd/libqtcassandra-0.5.5/tests/cassandra_value.cpp:2341:13:
error: assuming signed overflow does not occur when simplifying
conditional to constant [-Werror=strict-overflow]
if(r < 0) {
^
我不明白的是:为什么不会在之前的行上生成错误?因为真的溢出发生在我这样做,对吗?
What I do not understand is: why wouldn't the error be generated on the line before that? Because really the overflow happens when I do this, right?
r = -r;
推荐答案
EDIT:我的第一个答案,因为它是无效的。这里是全新的版本。感谢@Neil Kirk指出我的错误。
I removed my first answer, because it was invalid. Here is completely new version. Thanks to @Neil Kirk for pointing out my errors.
回答问题在这里: http://stackoverflow.com/a/18521660/2468549
GCC总是假定,签名溢出从不会发生,假设,它总是优化内部 if(r <0)
块。
GCC always assumes, that signed overflow does never occur, and, on that assumption, it (always) optimizes out the inner if (r < 0)
block.
-Wstrict-overflow
,然后编译器发现, r = -r
r < 0
可能仍然为真(如果 r == -2 ^ 31
最初),这导致错误(错误由基于假设溢出从不会发生,不是通过溢出可能性本身 - 这是 -Wstrict-overflow
工作原理)。
If you turn -Wstrict-overflow
on, then compiler finds out, that after r = -r
r < 0
may still be true (if r == -2^31
initially), which causes an error (error is caused by optimization based on assumption of overflow never occurring, not by overflow possibility itself - that's how -Wstrict-overflow
works).
这篇关于g ++严格溢出,优化和警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!