2 ms·
It would have never occurred to me that: for (i = 0; i <= N; ++i) { ... } Has a potential bug in it depending on compiler optimizations (where N=INT_MAX, a
by ghshephard 12y ago
It would have never occurred to me that:
for (i = 0; i <= N; ++i) { ... }
Has a potential bug in it depending on compiler optimizations (where N=INT_MAX, and the results of ++i may or may not be defined - with the compiler using the "UNDEFINED" behavior to ensure that the above loop runs N+1 times.)
- kazinator 12y agoIf N is INT_MAX, and the loop does not have a break statement in in anywhere, then the ++i will evaluate on the last iteration and overflow past INT_MAX. That is undefined; there is no may or may not about it. Behavior which depends on compiler optimizations isn't a potential bug, it's almost always a bug. (The one exception might be programs whose specification is that they explore behaviors that depend on optimization!) The compiler can help here by diagnosing the suspicious comparison i <= N, if N is a constant known to be INT_MAX. warning: comparison always true The programmer can shut up the diagnostic by removing the expression, if it really is the intent that the loop guard is always true: for (i = 0; ; i++) { /* conditional break; somewhere in the loop prevents i++ overflow. */ }