g++ strict overflow, optimization, and warnings

前端 未结 1 496
野的像风
野的像风 2021-01-14 10:38

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


        
相关标签:
1条回答
  • 2021-01-14 11:21

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

    0 讨论(0)
提交回复
热议问题