Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything wrong with using an empty for loop?

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.

like image 787
Anonymous Avatar asked May 03 '11 09:05

Anonymous


People also ask

What happens if for loop is empty?

Empty Statement in a for Loop Here, the initialization block of the for loop contains nothing, hence an empty statement. For creating a loop that runs infinitely, we can use empty statements. However, if we use break statements inside the body of the loop, then the loop can terminate.

Can we leave for loop empty?

However, in a for loop, any of the three fields can be left blank. If you leave init blank, then there is no initialization phase. You just start with the cond. If you leave update blank, then there is no update phase.

Is an empty for loop infinite?

An empty loop is a loop that doesn't contain any executable statement, whereas, an infinite loop is a loop that runs an infinite number of times. An empty loop contain only one empty statement. They are mostly used to produce time breaks. for(int a=0;a<10;a++); An infinite loop on the other hand continues forever.


2 Answers

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

like image 88
Erik Avatar answered Oct 30 '22 07:10

Erik


I always use while(true) for infinite loops

like image 37
Matthias Avatar answered Oct 30 '22 08:10

Matthias