Endless loop application - for (;;)

I am trying to understand the concept of an example for loop

for (;;) { //write code } 

I understand what it does and how it has the same loop structure as while (true), but my question ... is it good programming practice and for what applications will this type of loop structure be applied to?

+1
source share
5 answers

There are several situations where this is the desired behavior. For example, games on cartridge-based game consoles usually do not have exit conditions in their main cycle, since there is no operating system for the program to exit; the loop runs until the console shuts down.

Another example is when a module listens for actions from another. He will need to listen all the time, so the listener must listen to infinite time or until the program shuts down. Like sockets, threads, and UIComponents.

There is no bad practice in the concept of an infinite loop, but if it is not needed or does not harm your system function, it can be considered, for example, when you create an unintended infinite loop or lose program control for a loop.

To make an endless loop a good practice:

  • Make sure this is the desired behavior. If it has a stop condition, avoid an infinite loop!
  • Do this with for(;;) or while(true) . Avoid tautology in expression, do it easy!
  • Make it fault tolerant, save the expected exceptions and give them the right treatment!
  • And the most important thing! Make the endless loop simple !
+3
source
 while(abortRequested) { // .... } 

almost equivalent

 while(true) { // ... // ... dozens of lines of code ... if(abortRequested) break; // prepare next iteration } 

Alternatively, this can also be performed on a daemon thread, which automatically terminates when all non-daemon threads are executed. Thus, the semantics of these constructions are usually as follows:

Should continue forever by default unless an explicit completion event is received.

+1
source

In general, everything is in order, nothing to worry about. It's about the preferences of the programmer.

I prefer while(true) , from my point of view, this is a more elegant form of an infinite loop. Someone might prefer the for(;;) approach.

0
source

This is only a matter of personal preference. For example, I prefer this style:

  while (true) { // Do infinite task } 

It all comes down to readability, go with the fact that it's easy for you to read and understand after a few months.

0
source

The prospect may be: Although this is more like an event / condition based. Where you run the loop until something happens that completes the loop. On the other hand, for a loop, it looks more like a counter on which you want to indicate how many times the loop should have happened. At least there is an obvious position for this.

Of course, technically they are both the same, they both check the start condition to start the cycle loop.

0
source

Source: https://habr.com/ru/post/1445876/


All Articles