Public Group

Infinite Loops in c++

This topic is 3923 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

This is probably a very simple question but I am unsure if there is a reason or just personal preference. In a lot of libraries I tend to see infinite loops written as for(;;) rather then while(true). Is there any difference once a compiler has it's way with the code? Thanks

Share on other sites
Nope, no difference. However, VC 2003 and VC 2005 give a warning about while(true) on the highest warning level (Warning: Conditional expression is constant).

Share on other sites
The binary result is the same in both cases on every professional compiler available. One might argue that for(;;) avoids warnings related to constant conditions, while another might argue that while(true) is closer to the intent. Ultimately, the number of infinite loops in any program is small enough that this is an utterly pointless issue. I stick to whatever the team habits are, and use for(;;) in my own code for no reason but my own artistic preference.

Share on other sites
I had a professor who did the following:
#define ever (;;)for ever{   // ...}

I like it but, wouldn't use it in my own code.

Share on other sites
Original post by Simian Man
#define ever (;;)for ever{   // ...}

Hehehe, wouldn't have thought of that XD.

Share on other sites
Quote:
 Original post by Simian ManI had a professor who did the following:#define ever (;;)for ever{ // ...}I like it but, wouldn't use it in my own code.

Because, one day you'll do:
int ever = 20;

and spend an hour or two banging your head against the wall trying to figure out why it doesn't compile. Ah, the wonders of the preprocessor.

Skizz

Share on other sites
Quote:
 Original post by Simian ManI had a professor who did the following:#define ever (;;)for ever{ // ...}I like it but, wouldn't use it in my own code.

I never use infinite loops, but now you showed me this I think I will!

R O F L

Share on other sites
Generally, I fail to see the use of infinite loops.

You still need a way to stop it eventually, if you're hoping for a clean exit.

And since infinite loops stop program execution after it, they'll likely operate in a thread.

So the general approach I use is:
bool running = true;...while (running) {}

One could argue that exiting from a loop may be done using break, but that involves a condition test as well.

For algorithms, I'm strongly opposed to infinite loops. You either know when you're done, or you don't. The later obviously being non-deterministic, there-by undesirable choice.

Another approach I might use would be:
bool doTheStuff() {  // foo  return are_we_out_of_stuff;}...while ( doTheStuff() ) ;

Both of these to me make it much clearer when, how and why we are exiting.

1. 1
2. 2
3. 3
4. 4
5. 5
Rutin
17

• 10
• 12
• 9
• 12
• 37
• Forum Statistics

• Total Topics
631420
• Total Posts
2999987
×