while (true) and for (; ; ) [modified]
-
What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.
"Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson
modified on Thursday, March 10, 2011 12:10 PM
I sometimes do this in C:
void method(void)
{
//initialization, e.g. mallocs
do //think try
{
//some stuffif(early exit condition)
{
break; //continue is also fine
}
//other stuff (but skipped in event of early exit condition)} while(false); //think finally
//finalization, e.g. frees
}This effectivly gives me a try...finally in C. Which helps reduce ifs nesting.
-
Not always. In
C
applications, for instance, you may know in the middle of the loop that you've to exit and while you may skip the following statements with anif
and then use the condition, I prefer an immediatebreak
.If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles] -
Ah, I'm going to modify my original post. I wasn't referring to the preference between the 2, but the use of infinite loops, especially if there is no breaks to exit the loop. I guess we have a crash-only design for some applications.
"Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson
It depends on what the application calls for. There are numerous situations where while(true) is appropriate. Three years ago I did an application where the spec explicitly said to not handle shutting down the application. It was a long-running application, and my guess was they would simply shut down the computer when done. What about a heart pacemaker? If it exited the loop, someone might die.
-
While(!done) won't prevent you from exiting in the middle of the loop. You can break anywhere you like. The point is that I prefer to use a loop in a controlled manner.
Best, Jun
Jun Du wrote:
While(!done) won't prevent you from exiting in the middle of the loop. You can break anywhere you like.
Well that would look (to me) redundant. It's just matter of personal taste, but I think
if .. break
in the middle of the loop is a 'controlled manner' too. :)If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles] -
Okay, I can't think of why anyone'd have a while-true (or otherwise infinite) loop that does not have any normal exit conditions. Although you could break out via an exception it just does not seem very clean to me.
Regards, Nish
New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com
while(true) { lock(syncObject) { if (checkSomeCriticalCondition()) break; } doSomeOtherStuff(); }
-
while(true) { lock(syncObject) { if (checkSomeCriticalCondition()) break; } doSomeOtherStuff(); }
Uhm, what's your point? :-) You do have a break there (which is an exit point)! So yours is not an exit-less infinite loop!
Regards, Nish
New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com
-
Uhm, what's your point? :-) You do have a break there (which is an exit point)! So yours is not an exit-less infinite loop!
Regards, Nish
New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com
I know, just giving a solid example so there's no doubt. ;P
-
I know, just giving a solid example so there's no doubt. ;P
Andrew Glow wrote:
I know, just giving a solid example so there's no doubt.
Thanks for the 1 vote.
Regards, Nish
New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com
-
Jun Du wrote:
While(!done) won't prevent you from exiting in the middle of the loop. You can break anywhere you like.
Well that would look (to me) redundant. It's just matter of personal taste, but I think
if .. break
in the middle of the loop is a 'controlled manner' too. :)If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles] -
What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.
"Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson
modified on Thursday, March 10, 2011 12:10 PM
I have used this only once in production. It's a windows service application that listen to connection requests on a background thread. Something like this:
while(true)
{
m_Socket = m_Listener.AcceptSocket(); // This is a blocking line which waits until a connection request arrives from the clinet.//Do stuff from the connection request, then start over to keep listening for new requests
}
Of course this code is part of a method that is enclosed on a try catch block that expects a ThreadAbortedException. Which is the way out of the loop. And that only happens when the user explicitly asks to do so or the service is stopped. I think the while(true) can be used, but with lot of care. And I think that there are very few scenarios where the danger of it's use is smaller than the need. So, if you can avoid it, avoid it. If not, make sure you know what you're doing and try to cover as many possibilities of things going wrong as possible.
-
Not always. In
C
applications, for instance, you may know in the middle of the loop that you've to exit and while you may skip the following statements with anif
and then use the condition, I prefer an immediatebreak
.If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles]CPallini wrote:
you may know in the middle of the loop that you've to exit and while you may skip the following statements with an
if
and then use the condition, I prefer an immediatebreak
.What you have described is known as an n-and-a-half times loop. The Pascal P-Code compiler uses the following ungainly way of doing it (excuse the non-PASCAL syntax ... my Pascal is extremely rusty, but the principle is clear)
DO
(* bits before the test *)
test = exit condition;
IF (NOT test)
(* bits after the test condition *)
UNTIL (test)It always struck me as bad - the compiler writers having to use an idiom to do something that their language did not support cleanly - surely, they should be able to adjust the language when they saw its inherent deficiencies. Languages that I was involved with in the late 1970s always 'magically' got extensions that supported n-and-a-half times loops. For example, my Rationalised FORTRAN (which included block structured constructs long before FORTRAN 77 became available) had:
LOOP
bits before the test
EXITIF condition // You could have multiple EXITIF sections
bits after the test
ENDLOOP(minor later variant was an
EXITIFNOT
statement as an alternative toEXITIF
) A WHILE loop then simply becomesLOOP
EXITIFNOT condition
body of the loop
ENDLOOPAn UNTIL loop then simply becomes
LOOP
body of the loop
EXITIF condition
ENDLOOPA normal FOR/NEXT or DO/CONTINUE loop becomes
controlvar = startvalue
LOOP
EXITIF controlvar > endvalue
body of the loop
controlvar = controlvar + step
ENDLOOPA 'must do at least once' FOR/NEXT or DO/CONTINUE loop becomes
controlvar = startvalue
LOOP
body of the loop
controlvar = controlvar + step
EXITIF controlvar > endvalue
ENDLOOPExample: To see if an item is in an array
i = 1 // Lower bound of subscript
LOOP
EXITIF i > noofelementsinthearray
EXITIF array(i) = valuetofind // Previous EXITIF ensure that array subscript overflow will not occur
i = i + 1
ENDLOOPor
i = 1 // Lower bound of subscript
LOOP
EXITIF i > noofelementsinthearray
IF (array(i) = valuetofind)
do whatever you want with the found value
EXITIF true // I never got around to creating a simple unconditional EXIT statement!
END IF
i = i + 1
ENDLOOP -
while(true) { lock(syncObject) { if (checkSomeCriticalCondition()) break; } doSomeOtherStuff(); }
Andrew Glow wrote:
while(true)
{
lock(syncObject)
{
if (checkSomeCriticalCondition())
break;
}doSomeOtherStuff();
}If possible, I'd move the lock{ someCriticalCondition } out to a function returning boolean. Then toss the result of that as the while condition. while(CheckCondition()){ doSomeOtherStuff(); } The semantics are identical, unless there is code before the lock... In my opinion, this displays the intent of code/loop better than having an internal break.
-
Andrew Glow wrote:
while(true)
{
lock(syncObject)
{
if (checkSomeCriticalCondition())
break;
}doSomeOtherStuff();
}If possible, I'd move the lock{ someCriticalCondition } out to a function returning boolean. Then toss the result of that as the while condition. while(CheckCondition()){ doSomeOtherStuff(); } The semantics are identical, unless there is code before the lock... In my opinion, this displays the intent of code/loop better than having an internal break.
True. I guess having it just like this would be useless unless maybe doSomeOtherStuff actually used the same data in the critical section that other threads were using as well. In this case I would do something like this:
while (true)
{
lock(syncObject)
{
if (checkSomeCriticalCondition())
break;
doSomeOtherStuff();
}
Sleep(someAmountOfTime);
}... I can see a lot more holes in this design now but I still think that having a critical section check could be used somehow.
-
True. I guess having it just like this would be useless unless maybe doSomeOtherStuff actually used the same data in the critical section that other threads were using as well. In this case I would do something like this:
while (true)
{
lock(syncObject)
{
if (checkSomeCriticalCondition())
break;
doSomeOtherStuff();
}
Sleep(someAmountOfTime);
}... I can see a lot more holes in this design now but I still think that having a critical section check could be used somehow.
Depending on the language and framework's your using, there is probably a timer you could use to avoid the loop all together? If the bulk of the code in the loop is critical enough to require a lock, I wonder if it is something that would actually benefit from running in a multithreaded environment? I work mostly with C# and have seen very few scenarios where while(true) or for(;;) is the best choice. Just make sure its commented well!
-
Depending on the language and framework's your using, there is probably a timer you could use to avoid the loop all together? If the bulk of the code in the loop is critical enough to require a lock, I wonder if it is something that would actually benefit from running in a multithreaded environment? I work mostly with C# and have seen very few scenarios where while(true) or for(;;) is the best choice. Just make sure its commented well!
Very good point, for some reason I always assume people are using .NET. I did mean C# anyway. However, nothing comes to mind for a concrete example of where this would be useful at the moment.
-
Ah, I'm going to modify my original post. I wasn't referring to the preference between the 2, but the use of infinite loops, especially if there is no breaks to exit the loop. I guess we have a crash-only design for some applications.
"Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson
-
What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.
"Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson
modified on Thursday, March 10, 2011 12:10 PM
-
What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.
"Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson
modified on Thursday, March 10, 2011 12:10 PM
I hate to sound like a politician, but it depends. However, when there is a clear way to use "either," I personally prefer "for" looping. If working with object arrays, data rows, etc, I prefer to either check the count in an "if" block (or the UBOUND in the case of an array >-1) prior to the for loop. This approach allows you to predetermine iterations (if any are needed) at runtime- with your max value value being a variable. I usually reserve the use of "while" loops for conditions that are not numeric in nature... i.e. Fuzzier routines. In these cases, I usually place a boolean variable AND a counter out of the scope of the procedure and wrap a MAX If on loop iterations. I usually only go down this road if I am having to enumerate using self-calling recursion or something complex like that.
I float like a butterfinger & stank like a bee.
-
Christopher Duncan wrote:
Hang the app with an endless loop?
Only on a single core machine :-D
Regards, Nish
New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com
That's incorrect. This code will only hang a single core machine if there are no interrupts to force context switching (which is the case on the vast majority of machines that run an OS, anyway). Also, this code is useful to spawn a thread that continuously polls hardware. If you have a piece of hardware that can change its output at any given time, but you're not sure when, you can spawn the equivalent to a listener thread to capture (sample) changes at the output. In fact, this code is useful in many "thread listener" type scenarios, such as when a server is idling and listening for clients...
-
What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.
"Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson
modified on Thursday, March 10, 2011 12:10 PM
DirectX programming relies on while(true) for the primary loop. As long as a graceful exit exists (catching exceptions is not graceful), this is a valid programming code piece.