Jump to content

while(1) vs for(;;)


Recommended Posts

As I've been reading through the MSDN for code tips, I've often seen "infinite" loops in C++ written in the form

for(;;)
{
          // Do stuff here
}

Whereas I've always been used to writing them as

while(1)
{
         // Do stuff here
}

Either that or while(true). Of course, within the loop there's a method of breaking out of it, either a break statement or a return.

Is there a reason why the MSDN examples use the for loop instead of the while loop? Does it complile "cleaner" or faster? Or is it simply a matter of preference?

I'm just curious if someone knew the answer.

Link to comment
Share on other sites


As far as I know they are completely interchangable. I use "while" in this case because it seems to make more "human logic" sense. I.E. You are doing it while the condition is met or until told to stop. "For" seems to imply a sequential iteration, I.E. do it this number of times or until I say stop. Anyway, thats just how I think of it, like I said, in code terms they are interchangable.

http://msdn.microsoft.com/library/default....e_statement.asp

http://msdn.microsoft.com/library/default....r_statement.asp

Edited by dman
Link to comment
Share on other sites

Thanks for the reply.

I also find while a bit more intuitive in terms of "infinite" loops. The for loop is something to be done a specific number of times, like parsing through an array or the like.

Cheers!

Link to comment
Share on other sites

It's mostly a matter of style. I prefer "for(;;)".

"while(1)" may be less efficient than "for (;;)" - logically, the value of 1 must be checked against zero every iteration. In practice, a check would only occur for compilers with poor optimizers or when optimization is disabled.

Also, while(1) is kind of arbitrary - while(666) or while("hello") is just as valid.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...