biolightning
biolightning

Reputation: 39

How to avoid 'while(true)' with 'break' and rather use a 'for' loop?

I have an application with a config file from which various settings are read. One of the settings is the cycles that the application is running. If this variable nLoops is -1 then it's supposed to run an infinite number of times. Otherwise it shall run x times. At the moment this is how I implemented it. However I was wondering if there's a more straight forward way without the while(true) expression (I get a warning here):

//get nLoops from config file

int i = 0;
while (true)
{
    if (nLoops > -1 && i >= nLoops)
        break;
    i++;

   // do stuff
}

Upvotes: 0

Views: 979

Answers (3)

ad absurdum
ad absurdum

Reputation: 21317

You can replace while(true) with for(;;) to avoid warnings. The for loop with a missing controlling expression is explicitly defined in the standard, e.g., ISO/IEC 9899:1999 6.8.5.3/2.

Upvotes: 2

Andre
Andre

Reputation: 186

This requires one more (boolean) variable, but avoid using break statement in your loop.

    // Here reads from configuration file

    bool isInfiniteLoop = false;
    i = 0;

    if(nLoops == -1)
    {
       isInfiniteLoop = true;
       nLoops = 1;
    }

    while(i < nLoops)
    {
         // here goes your code

         if(!isInfiniteLoop)
         {
            // If NOT infinite loop: increment counter, otherwise while condition will always be 0 < 1
            i++;
         }
    }

Upvotes: 0

dbush
dbush

Reputation: 223709

Just put the if condition (inverted, since you're testing to stay in instead of break out) in the while condition:

while (nLoops == -1 || i < nLoops)

Or as a for:

for (i=0; (nLoops == -1) || (i < nLoops); i++)

Upvotes: 3

Related Questions