Reputation: 81
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.
Upvotes: 8
Views: 5011
Reputation: 10350
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');
Upvotes: 0
Reputation: 206536
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.
Upvotes: 2
Reputation: 139850
I've seen this in a few places:
#define forever for(;;)
forever {
}
Not sure I'd recommend it though.
Upvotes: 2
Reputation: 1059
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 .
Upvotes: 0
Reputation: 2341
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.
Upvotes: 0
Reputation: 91270
What you're doing is perfectly fine, and an idiomatic way of writing and exiting an infinite loop.
Upvotes: 5
Reputation: 170499
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.
Upvotes: 1