Is there something wrong with using an empty loop?

It has been a while since the last time I was programmed, and I seem to have forgotten whether it is permissible to use an empty "for" loop to create an infinite loop?

for(;;) 

I am currently using this method in a program so that it repeatedly asks the user to enter two numeric values, one for each double variable in the program. Then the programs call the function and calculate the sum of these two pairs of numbers.

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

The program checks each input value of the user if it is equal to zero after the value has been assigned to the variable.


So, to the real question: Is this the right way to get my program to do what I described? Or is there a more / better / acceptable way to program this?

And secondly, is there something wrong with the "Return 0" argument, as I did in this program?

If you think it’s hard to understand what I wrote or had in mind, answer and I will take more time to write everything.

+7
source share
9 answers

What you do is beautiful, and an idiomatic way to record and exit an infinite loop.

+4
source

I always use while(true) for infinite loops

+4
source

This is valid, you can continue your code.

+2
source

for(;;) as well as while(1) both acceptable. These are just conditional loops provided by the language, and you can use them for an infinite loop of work as per your requirement.

+2
source

Yes, that’s perfectly acceptable. When you get a termination 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 to the loop body. If this makes the program more readable, you can of course do it.

+1
source

I saw this in several places:

 #define forever for(;;) forever { } 

Not sure if I would recommend it.

+1
source

For the infinte for (;;) loop, a fairly common practice. But if you have a condition, such non-zero user input, you can always perform this check in a while .

0
source

You can also use a while loop with the condition of re-asking the user for input.

 while (condition) { ... } 

Instead of an IF block for verification, you can use.

0
source

What you described will work fine, but it is worth mentioning that some strict coding standards (i.e. MISRA ) would not approve of using return until the end of the function.

If your code is subject to such standards, you can use a do-while with a suitable exit condition:

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

All Articles