Zxian Posted June 6, 2005 Share Posted June 6, 2005 As I've been reading through the MSDN for code tips, I've often seen "infinite" loops in C++ written in the formfor(;;){ // 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 More sharing options...
dman Posted June 7, 2005 Share Posted June 7, 2005 (edited) 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.asphttp://msdn.microsoft.com/library/default....r_statement.asp Edited June 7, 2005 by dman Link to comment Share on other sites More sharing options...
Zxian Posted June 7, 2005 Author Share Posted June 7, 2005 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 More sharing options...
Martin Zugec Posted June 7, 2005 Share Posted June 7, 2005 Yep, dman is right, they are interchangable... Use what is your loging telling you to use I am using For (because I used it in basic, dos etc...) Link to comment Share on other sites More sharing options...
azagahl Posted June 11, 2005 Share Posted June 11, 2005 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 More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now