I am trying to understand the concept behind the for loop example
for (;;)
{
//write code
}
I understand what it does and how it\'s the sa
One perspective could be : While is more like event/condition based .. Where you run the loop until something happens which terminates the loop. On the other hand for loop is more like counter based where you want to specify for how many times should the loop happened. Al least it has an explicit provision for that.
Ofcourse technically both are same they both check for run condition to start a loop cycle.
There are a few situations when this is desired behavior. For example, the games on cartridge-based game consoles typically have no exit condition in their main loop, as there is no operating system for the program to exit to; the loop runs until the console is powered off.
Another example is when a module listen actions from another. It will need to listen all the time, so the listener have to listen for infinite time or until the program turn off. Like Sockets, Threads and UIComponents.
There isn't bad practice on the concept of infinite loop, but if it isn't wanted or prejudice your system's feature it can be considered, like when you create an unintentional infinite loop or lose program control for the loop.
To make the infinite loop a good practice:
for(;;)
or while(true)
. Avoid tautologies in expression, do it simple!This is just a matter of personal preference. For instance I much prefer this style:
while (true) {
// Do infinite task
}
It all comes down to readability, go with whatever is easy for you to read and understand months later.
while(abortRequested)
{
// ....
}
is almost equivalent to
while(true)
{
// ...
// ... dozens of lines of code ...
if(abortRequested)
break;
// prepare next iteration
}
Alternatively this might also run in a daemon thread which automatically gets terminated when all non-daemon threads are done. So the semantic of these constructs generally is:
Should keep running forever by default, unless some explicit termination event is received.
In general it is ok, there's nothing to worry about. It is about of programmer's preferences.
I prefer while(true)
, from my point of view it is more elegant form of infinite loop. Someone else may prefer for(;;)
approach.