g++ strict overflow, optimization, and warnings

為{幸葍}努か 提交于 2019-12-01 06:20:17

问题


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;
        }
    }

The error is:

/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;

回答1:


EDIT: I removed my first answer, because it was invalid. Here is completely new version. Thanks to @Neil Kirk for pointing out my errors.

Answer for the question is here: https://stackoverflow.com/a/18521660/2468549

GCC always assumes, that signed overflow does never occur, and, on that assumption, it (always) optimizes out the inner if (r < 0) block.

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).



来源:https://stackoverflow.com/questions/22798709/g-strict-overflow-optimization-and-warnings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!