Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


I 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.)


No, if your program ever invokes UB, anything could happen (even at the beginning). In other words, UB can time travel.


If the {…} includes a break, undefined behavior could well be avoided.




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: