79547411

Date: 2025-03-31 23:15:28
Score: 1
Natty:
Report link

As is printed in your 2nd link

An iteration statement whose controlling expression is not a constant expression,156) that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression-3, may be assumed by the implementation to terminate.157)

The program exhibits undefined behavior as your loop happens to meet all of those conditions. Returning 0 instead of having is one form of undefined behavior.

It sounds like your real question is: "how can I protect myself against this footgun?" Unfortunately you already know the answer (static analysis, unit tests, etc). Unfortunately (for most of us), the C++ standard committee decided that the potential optimizations opened up by this assumption are worth the footgun. Short of C++ adopting a profile that would prohibit you writing such a loop (note, I didn't see a proposal for this particular issue in several profile lists I looked at), I don't see a good solution other than the ones you propose.

Reasons:
  • Blacklisted phrase (0.5): how can I
  • Long answer (-1):
  • No code block (0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: Jeremy Richards