8
votes

It was a little while since I last programmed and I have seem to forgotten if it's acceptable to use an empty "for loop" for creating an infinite loop?

for(;;)

Currently I use this method in a program to make it repeatedly ask the user to enter two numeric values one for each double variable in the program. The programs then calls a function and calculates a sum of these two pairs of numbers.

To terminate the program i have "if" statements that check if the user input value is zero, If the value is zero the program terminates using an "Return 0;" argument.

The program checks each user input value if it's zero directly after the value has been assigned to the variable.


So to the real question: Is this a correct way to make my program do what i described? Or is there a more/better/accepted way of programming this?

And secondly is there anything wrong with use the "Return 0" argument the way i did in this program?

If you thinks it's hard to understand what I'll wrote or meant please reply, and I will take more time to write everything.

9
There are arguably more elegant ways (do-while), but there is certainly nothing wrong with your way as such. - Damon
FYI, that is an infinite for loop, not an empty one. An empty for loop would look like this for (initialisation;condition;updation); or this for (initialisation;condition;updation){} - Troyseph

9 Answers

5
votes

What you're doing is perfectly fine, and an idiomatic way of writing and exiting an infinite loop.

5
votes

I always use while(true) for infinite loops

2
votes

I've seen this in a few places:

#define forever for(;;)

forever {

}

Not sure I'd recommend it though.

2
votes

for(;;) as well as while(1) both are acceptable. These are just conditional loops provided by the language and you can use them to have a infinite running loop as per your requirement.

2
votes

This is valid, you can go ahead with your code.

1
votes

Yes, it's totally acceptable. Once you have an exit condition (break or return) in a loop you can make the loop "infinite" in the loop statement - you just move the exit condition from the loop statement into the loop body. If that makes the program more readable you of course can do that.

0
votes

For an infinte loop for (;;) is fairly common practice. But if you do have a condition, such a non-zero user input, you could always have that check done in a while loop.

0
votes

You can also use while loop with condition to repeatedly request user to input.

while (condition) {
  ...
}

Instead of IF block to validation you can use the .

0
votes

What you describe will work fine, but it is worth mentioning that certain strict coding standards (i.e. MISRA) would disapprove of using a return before the end of a function.

If your code is subject to such standards then you could use do-while loop with a suitable exit condition instead:

do {
   // get userinput
   if (userinput != '0')
   {
       // do stuff 
   }
} while (userinput != '0');