2 ms·
Many things are infinite from the perspective of the program, for some classes of programs. An IoT device generally is always doing the same loop and responding
by vasco 4y ago
Many things are infinite from the perspective of the program, for some classes of programs. An IoT device generally is always doing the same loop and responding to interrupt signals for anything else. Game loops work in a similar way.
I guess you can have a limit on the loop, have it break out to make sure you're still listening to interrupts do some logging and go back to looping, but in an environment where interrupt signals are native, an infinite loop can and is fine.
Glad I got my bikeshedding allowance out for the day.
- vidarh 4y agoMost of the things that are infinite from the perspective of the program tend to be event loops of different forms, though, where that perspective is "unless the right event arrives". There are rarely many of them in the same application, and they tend to be high level. If you find yourself writing an infinite event loop at a lower level, odds are something is off (e.g. an infinite loop waiting for a reply packet over the network could do with a timeout) I agree it's usually fine to use infinite loops for high level event loops, as it's usually easy to test that you can break out of them by triggering the right event (though sometimes it might be worth thinking about pathological cases if you can do something about them, such as whether something is wrong if there's no interrupt for a long enough period; and you can also prevent writing an infinite loop even for event loops by making the break condition whether a suitable "exit"/"restart" event has been received - very few things should be without one or the other of those two even if intended to run forever in normal circumstances). The advice, I think, is more important for algorithms working on input data that may well lock up the application if the logic is wrong. E.g. a sort should eventually complete; if it takes more passes through an outer loop than the theoretical worst case for the algorithm, something is wrong (be it your implementation or your understanding of the worst case...). A habit of estimating worst cases and treating them as invariants to check and make assertions about can be useful.
- IlliOnato 4y agoWell, many document-processing tasks also require something like an infinite loop. For example, parsing of an XML document naturally resembles an event loop, with each token being an equivalent of an event. Although usually there is a natural end to this loop, so you have not "while(1)" but "while (not EOF)" or something, which helps avoid some bugs, but I believe a compiler turns it into an infinite loop anyway, and breaks it on these conditions.