3 ms·
int is signed and signed int overflow is UB. If you use an int as a loop counter, the compiler can optimize the loop assuming the loop counter will never overfl
by cpeterso 5y ago
int is signed and signed int overflow is UB. If you use an int as a loop counter, the compiler can optimize the loop assuming the loop counter will never overflow because, surely, a programmer would never invoke UB. :) If the loop counter does overflow, then who knows what bad things will happen. For example, a simple loop like “for (int i = 0; i >= 0; i++) { … }” might become an infinite loop, crash, execute random code, or never execute in the first place.
- sokoloff 5y agoI think it's defined to execute at least until overflow, is it not? (So, even assuming a 1-bit int, it's going to execute at least once I think.)
- witty_username 5y agoNo, if your program ever invokes UB, anything could happen (even at the beginning). In other words, UB can time travel.
- sokoloff 5y agoIf the {…} includes a break, undefined behavior could well be avoided.