3 ms·
The inequality argument would seem to apply only to for loops with constant iteration counts, yeah? The compiler can't know that "i < n; i++" won't overflow if
by kalkin 4y ago
The inequality argument would seem to apply only to for loops with constant iteration counts, yeah? The compiler can't know that "i < n; i++" won't overflow if "i" could start out higher than "n". (wrong)
I am not an expert on compiler optimization, but having reasoned through a few cases where a compiler is _unable_ to correctly make an obvious-seeming optimization, I tend to think that compiler writers have good reasons for the things they want to be able to assume.
- dooglius 4y agoIf "i" started out higher than "n", the loop would exit immediately and there would be no increment. More generally, if "n" is an int, then even if n is modified each iteration, the "i < n; i++" still can't overflow because it will always exit at INT_MAX if not before. If "n" is something else like a long then that's likely a mistake that falls under "the compiler should warn if you do this". If there were good reason for wanting to assume this, I would expect someone to have presented it; responses I hear just take the form of a single (usually contrived) example where more performant code is generated, then insisting that all other factors (e.g. being predictable/unsurprising, acting like the underlying architecture, mitigating bugs) are irrelevant. Just as GP did.
- kalkin 4y agoAh good point re the inequality, over thought it. If there weren't good reasons for making the assumptions that modern compilers do, I'd have expected users of C and C++ to have converged on a more conservative compiler, at least in some significant number.