C++26: Trivial infinite loops are no longer undefined behaviour
Thread
Unofficial Hacker News client; not affiliated with Y Combinator.
C++26: Trivial infinite loops are no longer undefined behaviour
Unofficial Hacker News client; not affiliated with Y Combinator.
JoshTriplett · · focus · HN ↗
Insert screaming here.
An infinite loop, with no library calls whatsoever, gets a system call inserted. That's a horrible surprise waiting to happen.
The entire concept of the "forward progress guarantee" is broken. An infinite loop should compile to an infinite loop. Nothing more, nothing less.
marcosdumay · · focus · HN ↗
I think you are misinterpreting that. That phrase unambiguously says the loop is preserved on the final binary.
JoshTriplett · · focus · HN ↗
marcosdumay · · focus · HN ↗
The problem is that what you want is completely against the spirit of the entire language.
If your point is that C++ should be more like C in general, I can agree with that. But if your point is that C++ should be literal on this specific case, performance be damned, and the rest of it is ok, then no, that's a bad one.
JoshTriplett · · focus · HN ↗
mitxela · · focus · HN ↗
CamperBob2 · · focus · HN ↗
Merging a buggy loop with another loop creates... a buggy loop.
teo_zero · · focus · HN ↗
Now, the compiler could try to understand if the first loop does or doesn't terminate, and apply or not the optimization accordingly, but Turing tought us that is indeed a hard task!
Or it could decide to never apply it, for fear of those rare and usually pathological cases where the first loop doesn't terminate.
Or it could decide to apply it by default and accept that in those cases the program does something different than what the source code says. The latter is better known as UB.
The third option won, and that's why infinite loops are UB in the standard.
mitxela · · focus · HN ↗
The standard example is a linked list instead of an array because the compiler can't prove it never has a cycle.
imtringued · · focus · HN ↗
Why use a for loop with a bound as an example instead of while loops with linked lists? He or she can prompt an LLM for a better example so laziness doesn't count as an excuse.
teo_zero · · focus · HN ↗
I'm the author of the example. I wanted to keep it as simple as possible, and this is the most common form of for loop. I was sure that HN readers would be clever enough to "map" it to whatever they have in their mind that satisfy the undecidability of the condition.
But since you're nitpicking, I haven't specified the types of i and n: i is uint8_t and n is uint32_t. Does it terminate? It depends on the value of n!