Here is the piece of code from GNU C reference manual Pg 74:
If your code uses a signed loop index, make sure that the index cannot overflow, along with all signed expressions derived from the index. Here is a contrived example of problematic code with two instances of overflow.
for( i = INT_MAX - 10 ; i <= INT_MAX; i++)
if( i+1 < 0 ) //first overflow
{
report_overflow();
break;
}
Because of the two overflows, a compiler might optimize away or transform the two comparisons in a way that is incompatible with the wraparound assumption.
What GNU C reference manual means is that you have two possible overflows. The first one is the i++
statement in
for( i = INT_MAX - 10 ; i <= INT_MAX; i++)
and the second one would be i+1
in
if( i+1 < 0 ) //first overflow
The example C code avoids an eternal loop with the
if( i+1 < 0 ) //first overflow
{
report_overflow();
break;
}
piece of code, and to do that you're relying in signed wraparound behaviour.
However the A.3 apendix tells you that you shouldn't rely on signed wraparound behaviour because the optimizer exploits its undefined behaviour and could generate code that would behave differently from what you expect. This is the case with if( i+1 < 0 )
piece of code, which relies in that wraparound will happen when i
is INT_MAX
.
As a conclusion, above code could fail after being optimized by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With