What is the explanation for “warning: assuming that the loop is not infinite”

前端 未结 3 1210
旧巷少年郎
旧巷少年郎 2021-02-19 09:17

I had just taken the decision to change as many variables from unsigned to int and upon recompiling the code in question, was greeted by this warning m

3条回答
  •  滥情空心
    2021-02-19 09:30

    The reason GCC warns you is because it have pulled of an unsafe optimization. Instead of

    for (x = startx; x <= endx; ++x, ++xptr)
    

    it basically uses:

    for( x = startx; x < (endx+1); ++x, ++xptr)
    

    which is correct only if endx+1 doesn't overflow, but this happens when endx is the largest possible value which means that x <= endx is always true. The compiler assumes that this doesn't happen.

    The warning is sometimes a bit confusing because it's not actually the finiteness of the loop that is the point here. I don't know if there's a better candidate for a message that would be short enough for a compiler warning.

    One example is the case where for example x and endx are integers the optimization could actually be interpreted as being allowed by the standard, if endx==MAX_INT you would have the condition being true which will lead to that x eventually overflows which is undefined behavior, this mean that the compiler may assume that this doesn't happen. To skip the loop entirely is a standard conforming behavior according to this interpretations.

    Another case is if the program doesn't terminate during the loop or alters volatile memory (ie have observable behavior) which means that an infinite loop means undefined behavior (IIRC, at least the compiler is allowed to assume that this doesn't happen).

提交回复
热议问题