June 6, 200521 yr 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.
June 7, 200521 yr 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, 200521 yr by dman
June 7, 200521 yr Author 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!
June 7, 200521 yr 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...)
June 11, 200521 yr 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.
Create an account or sign in to comment