What's the difference between these two while loops? I don't understand what they do.
First:
while(condition) ;
Second:
while(condition){ };
There's no difference, both while loops enclose an empty statement.
The practical result is an infinite loop which will never end, unless there's another thread or some side effect that changes condition.
first code is optional short form for second code, which is suitable when you need to do only 1 operation in loop, like:
while (condition is true)
condition=dosomething();
you can safely re-write this like:
while (condition is true)
{
condition=dosomething();
}
this will be absolutely the same
but if you need several statements in loop, you need to "group" them somehow, so compiler will know what parts of code should be "looped", this is done via { and }
so, for several statements you cannot use short form, you can only do:
while (condition is true)
{
condition=dosomething();
dosomething2();
dosomething3();
}
for multi-threading programming we can have next situation:
Thread1: set condition to true
Thread1: create new thread2 and run it
Thread1: now need to wait until thread2 is finished, thread2 will set condition to false when it done to notify 1st one
so, for such situations sometimes you can use infinite loop like
while (condition) ; or while (condition) { }; - which are the same as we see above
this mean - do single operation, but operation is not provided, this means just wait until other thread will set this variable to false
NOTE: such infinity loops usually is bad practice and it is better to avoid them and use only when you're sure that this has sense
The loops themselves are the same, but the second one is followed by the null statement, so if this code was oart of a larger control structure they could parse differently: for example, if they were part of a nested 'if' statement the first one could be followed by 'else', but the second could not.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.
As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:
if (condition)
{
do
{
...
} while (same condition);
}
or the inverse (if inside the while), it makes me wonder if they actually wrote it that way or if they added the if statement when they realized the loop didn't handle the null case.
I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?
I always follow the rule that if it should run zero or more times, test at the beginning, if it must run once or more, test at the end. I do not see any logical reason to use the code you listed in your example. It only adds complexity.
Use while loops when you want to test a condition before the first iteration of the loop.
Use do-while loops when you want to test a condition after running the first iteration of the loop.
For example, if you find yourself doing something like either of these snippets:
func();
while (condition) {
func();
}
//or:
while (true){
func();
if (!condition) break;
}
You should rewrite it as:
do{
func();
} while(condition);
Difference is that the do loop executes "do something" once and then checks the condition to see if it should repeat the "do something" while the while loop checks the condition before doing anything
Does avoiding do/while really help make my code more readable?
No.
If it makes more sense to use a do/while loop, then do so. If you need to execute the body of a loop once before testing the condition, then a do/while loop is probably the most straightforward implementation.
First one may not execute at all if condition is false. Other one will execute at least once, then check the conidition.
For the sake of readability it seems sensible to test at the top. The fact it is a loop is important; the person reading the code should be aware of the loop conditions before trying to comprehend the body of the loop.
Here's a good real-world example I came across recently. Suppose you have a number of processing tasks (like processing elements in an array) and you wish to split the work between one thread per CPU core present. There must be at least one core to be running the current code! So you can use a do... while something like:
do {
get_tasks_for_core();
launch_thread();
} while (cores_remaining());
It's almost negligable, but it might be worth considering the performance benefit: it could equally be written as a standard while loop, but that would always make an unnecessary initial comparison that would always evaluate true - and on single-core, the do-while condition branches more predictably (always false, versus alternating true/false for a standard while).
Yaa..its true.. do while will run atleast one time.
Thats the only difference. Nothing else to debate on this
The first tests the condition before performing so it's possible your code won't ever enter the code underneath. The second will perform the code within before testing the condition.
The while loop will check "condition" first; if it's false, it will never "do something." But the do...while loop will "do something" first, then check "condition".
Yes, just like using for instead of while, or foreach instead of for improves readability. That said some circumstances need do while and I agree you would be silly to force those situations into a while loop.
It's more helpful to think in terms of common usage. The vast majority of while loops work quite naturally with while, even if they could be made to work with do...while, so basically you should use it when the difference doesn't matter. I would thus use do...while for the rare scenarios where it provides a noticeable improvement in readability.
The use cases are different for the two. This isn't a "best practices" question.
If you want a loop to execute based on the condition exclusively than use
for or while
If you want to do something once regardless of the the condition and then continue doing it based the condition evaluation.
do..while
For anyone who can't think of a reason to have a one-or-more times loop:
try {
someOperation();
} catch (Exception e) {
do {
if (e instanceof ExceptionIHandleInAWierdWay) {
HandleWierdException((ExceptionIHandleInAWierdWay)e);
}
} while ((e = e.getInnerException())!= null);
}
The same could be used for any sort of hierarchical structure.
in class Node:
public Node findSelfOrParentWithText(string text) {
Node node = this;
do {
if(node.containsText(text)) {
break;
}
} while((node = node.getParent()) != null);
return node;
}
A while() checks the condition before each execution of the loop body and a do...while() checks the condition after each execution of the loop body.
Thus, **do...while()**s will always execute the loop body at least once.
Functionally, a while() is equivalent to
startOfLoop:
if (!condition)
goto endOfLoop;
//loop body goes here
goto startOfLoop;
endOfLoop:
and a do...while() is equivalent to
startOfLoop:
//loop body
//goes here
if (condition)
goto startOfLoop;
Note that the implementation is probably more efficient than this. However, a do...while() does involve one less comparison than a while() so it is slightly faster. Use a do...while() if:
you know that the condition will always be true the first time around, or
you want the loop to execute once even if the condition is false to begin with.
Here is the translation:
do { y; } while(x);
Same as
{ y; } while(x) { y; }
Note the extra set of braces are for the case you have variable definitions in y. The scope of those must be kept local like in the do-loop case. So, a do-while loop just executes its body at least once. Apart from that, the two loops are identical. So if we apply this rule to your code
do {
// do something
} while (condition is true);
The corresponding while loop for your do-loop looks like
{
// do something
}
while (condition is true) {
// do something
}
Yes, you see the corresponding while for your do loop differs from your while :)
As noted by Piemasons, the difference is whether the loop executes once before doing the test, or if the test is done first so that the body of the loop might never execute.
The key question is which makes sense for your application.
To take two simple examples:
Say you're looping through the elements of an array. If the array has no elements, you don't want to process number one of zero. So you should use WHILE.
You want to display a message, accept a response, and if the response is invalid, ask again until you get a valid response. So you always want to ask once. You can't test if the response is valid until you get a response, so you have to go through the body of the loop once before you can test the condition. You should use DO/WHILE.
I tend to prefer do-while loops, myself. If the condition will always be true at the start of the loop, I prefer to test it at the end. To my eye, the whole point of testing conditions (other than assertions) is that one doesn't know the result of the test. If I see a while loop with the condition test at the top, my inclination is to consider the case that the loop executes zero times. If that can never happen, why not code in a way that clearly shows that?
It's actually meant for a different things. In C, you can use do - while construct to achieve both scenario (runs at least once and runs while true). But PASCAL has repeat - until and while for each scenario, and if I remember correctly, ADA has another construct that lets you quit in the middle, but of course that's not what you're asking.
My answer to your question : I like my loop with testing on top.
Both conventions are correct if you know how to write the code correctly :)
Usually the use of second convention ( do {} while() ) is meant to avoid have a duplicated statement outside the loop. Consider the following (over simplified) example:
a++;
while (a < n) {
a++;
}
can be written more concisely using
do {
a++;
} while (a < n)
Of course, this particular example can be written in an even more concise way as (assuming C syntax)
while (++a < n) {}
But I think you can see the point here.
while( someConditionMayBeFalse ){
// this will never run...
}
// then the alternative
do{
// this will run once even if the condition is false
while( someConditionMayBeFalse );
The difference is obvious and allows you to have code run and then evaluate the result to see if you have to "Do it again" and the other method of while allows you to have a block of script ignored if the conditional is not met.
I write mine pretty much exclusively testing at the top. It's less code, so for me at least, it's less potential to screw something up (e.g., copy-pasting the condition makes two places you always have to update it)
It really depends there are situations when you want to test at the top, others when you want to test at the bottom, and still others when you want to test in the middle.
However the example given seems absurd. If you are going to test at the top, don't use an if statement and test at the bottom, just use a while statement, that's what it is made for.
You should first think of the test as part of the loop code. If the test logically belongs at the start of the loop processing, then it's a top-of-the-loop test. If the test logically belongs at the end of the loop (i.e. it decides if the loop should continue to run), then it's probably a bottom-of-the-loop test.
You will have to do something fancy if the test logically belongs in them middle. :-)
I guess some people test at the bottom because you could save one or a few machine cycles by doing that 30 years ago.
To write code that is correct, one basically needs to perform a mental, perhaps informal proof of correctness.
To prove a loop correct, the standard way is to choose a loop invariant, and an induction proof. But skip the complicated words: what you do, informally, is figure out something that is true of each iteration of the loop, and that when the loop is done, what you wanted accomplished is now true. The loop invariant is false at the end, for the loop to terminate.
If the loop conditions map fairly easily to the invariant, and the invariant is at the top of the loop, and one infers that the invariant is true at the next iteration of the loop by working through the code of the loop, then it is easy to figure out that the loop is correct.
However, if the invariant is at the bottom of the loop, then unless you have an assertion just prior to the loop (a good practice) then it becomes more difficult because you have to essentially infer what that invariant should be, and that any code that ran before the loop makes the loop invariant true (since there is no loop precondition, code will execute in the loop). It just becomes that more difficult to prove correct, even if it is an informal in-your-head proof.
This isn't really an answer but a reiteration of something one of my lecturers said and it interested me at the time.
The two types of loop while..do and do..while are actually instances of a third more generic loop, which has the test somewhere in the middle.
begin loop
<Code block A>
loop condition
<Code block B>
end loop
Code block A is executed at least once and B is executed zero or more times, but isn't run on the very last (failing) iteration. a while loop is when code block a is empty and a do..while is when code block b is empty. But if you're writing a compiler, you might be interested in generalizing both cases to a loop like this.
In a typical Discrete Structures class in computer science, it's an easy proof that there is an equivalence mapping between the two.
Stylistically, I prefer while (easy-expr) { } when easy-expr is known up front and ready to go, and the loop doesn't have a lot of repeated overhead/initialization. I prefer do { } while (somewhat-less-easy-expr); when there is more repeated overhead and the condition may not be quite so simple to set up ahead of time. If I write an infinite loop, I always use while (true) { }. I can't explain why, but I just don't like writing for (;;) { }.
I would say it is bad practice to write if..do..while loops, for the simple reason that this increases the size of the code and causes code duplications. Code duplications are error prone and should be avoided, as any change to one part must be performed on the duplicate as well, which isn't always the case. Also, bigger code means a harder time on the cpu cache. Finally, it handles null cases, and solves head aches.
Only when the first loop is fundamentally different should one use do..while, say, if the code that makes you pass the loop condition (like initialization) is performed in the loop. Otherwise, if it certain that loop will never fall on the first iteration, then yes, a do..while is appropriate.
From my limited knowledge of code generation I think it may be a good idea to write bottom test loops since they enable the compiler to perform loop optimizations better. For bottom test loops it is guaranteed that the loop executes at least once. This means loop invariant code "dominates" the exit node. And thus can be safely moved just before the loop starts.
So I have some C++ code for back-tracking nodes in a BFS algorithm. It looks a little like this:
typedef std::map<int> MapType;
bool IsValuePresent(const MapType& myMap, int beginVal, int searchVal)
{
int current_val = beginVal;
while (true)
{
if (current_val == searchVal)
return true;
MapType::iterator it = myMap.find(current_val);
assert(current_val != myMap.end());
if (current_val == it->second) // end of the line
return false;
current_val = it->second;
}
}
However, the while (true) seems... suspicious to me. I know this code works, and logically I know it should work. However, I can't shake the feeling that there should be some condition in the while, but really the only possible one is to use a bool variable just to say if it's done. Should I stop worrying? Or is this really bad form.
EDIT: Thanks to all for noticing that there is a way to get around this. However, I would still like to know if there are other valid cases.
I believe that there are cases where it's fine for seemingly infinite loops to exist. However this does not appear to be one of them. It seems like you could just as easily write the code as follows
while (current_val != searchVal ) {
MapType::iterator it = myMap.find(current_val);
assert(current_val != myMap.end());
if (current_val == it->second) // end of the line
return false;
current_val = it->second
}
return true;
This seems to express the true intent of the loop better
My two cents is: code should be self-documenting. That is, when given a piece of code, I'd rather be able to look and tell the programmer's intent then have to read comments or trudge through the surrounding code. When I read:
while(true)
That tells me the programmer wanted an infinite loop; that the end condition couldn't be specified. This is the programmers intent in some circumstances; a server loop for instance, and that is when it should be used.
In the above code, the loop isn't meant to be forever, it has a clear end condition, and in order to be semantically clear, as others have pointed out:
while (currentVal != searchVal)
works, so the while(true) is clearly inferior and should be avoided in this instance.
There are times and places for infinite loops - I am not convinced this is one of them. On the other hand, it is far from being an egregious problem here.
while (currentVal != searchVal)
{
...
}
return true;
One place to use them is when the process is truly indefinite - a daemon process with a monitor loop that won't terminate.
There are situations where a construct like this makes sense:
The break condition is computed within the loop
There are more breaking conditions and they are all equally important
You really want an endless loop ;) ..
I agree with the other answers that there's no need for an infinite loop in this case.
However, another point might be that when you do have an infinite loop, for(;;) might be a better way to express it. Some compilers generate warnings for while(true) (condition always evaluates to false), and your intent is less clear because it looks like any other loop. Perhaps it used to say while (x == true), and you accidentally removed the x instead of the true. for(;;) says pretty clearly that this is intended to be an infinite loop. Or perhaps you intended to write something like while(t), but Intellisense in your IDE kicked in and decided to autocomplete to true.
for(;;) on the other hand, isn't something you'd ever type accidentally. (and it's easier to search for. while(true) could also be written as while(1))
Neither version is wrong, but for(;;) might be more intuitive because there is no loop condition.
while(true) is used in games for the main game loop - games continually read player input, process interactions between objects and paint your screen, then repeat. This loop continues infinitely until some other action breaks out of that loop (quitting the game, finishing the level).
I tried to quickly find this main loop in the Quake 1 source code for you, but there were at least 50 occurrences of 'while(1)', as well as some written as 'for(;;)', and I wasn't immediately sure which one was the main game loop.
Although I've done them before, I'd vote for always trying to go for the clearer solution by using something readable, which would generally include a valid expression in the while loop--otherwise you're scanning code to look for the break.
I'm not really terrified of them or anything, but I know some people are.
Well, a comment saying that it is not really an infinite loop would help:
while (true) // Not really an infinite loop! Guaranteed to return.
I do agree that it should have a condition, but this is okay in some situations (and it's not always possible or easy to make a condition).
Stop worrying. This is not bad form if it helps to simplify the logic of the code and improve maintainability and readability. Worthwhile though to document in comments on the expected exit conditions and on why the algorithm will not slip into an infinite loop.
Well, yes, but the two pages of code you have to write if you don't want your main loop to be something like while(true) is even worse form.
It is not uncommon to find infinite loops in embedded systems code - often surrounding finite state machines, checking peripheral chips and devices, etc.
I love infinite loops as the outside control structure of a finite state machine. It's effectively a structured goto:
for (;;) {
int c = ReadInput();
if (c == EOF)
return kEOF;
switch (state) {
case inNumber: state = HandleNumber(c); break;
case inToken: state = HandleToken(c); break;
case inWhiteSpace: state = HandleWhiteSpace(c);
default:
state = inError;
break;
}
if (state == inError) ThrowError();
}
Another poster asked about preferred syntax for infinite loops.
A follow-up question: Why do you use infinite loops in your code? I typically see a construct like this:
for (;;) {
int scoped_variable = getSomeValue();
if (scoped_variable == some_value) {
break;
}
}
Which lets you get around not being able to see the value of scoped_variable in the for or while clause. What are some other uses for "infinite" loops?
A loop like:
while (true)
{
// do something
if (something else) break;
// do more
}
lets you break out of the loop in the middle, rather than at the start (while/for) or end (do-while).
If you've got a complex condition, you might also want to use this style to make the code clearer.
I use an infinite loop for the body of my embedded control code, since it is designed to run forever once it is started.
while( 1 )
{
game->update();
game->render();
}
Edit: That is, my app is fundamentally based around an infinite loop, and I can't be bothered to refactor everything just to have the aesthetic purity of always terminating by falling off the end of main().
Finite state machines. They're not supposed to end until you reach an end state, at which point you break or return.
That's an incomplete example because it can be refactored to be an end-test loop with no loss of clarity, function or performance.
int scoped_variable;
do {
scoped_variable = getSomeValue();
} while (scoped_variable != some_value);
Infinite loops are most often used when the loop instance doesn't have the termination test at the top or the bottom, in the simplest case. This tends to happen when there is two parts to the loop: code that must execute each time, and code that must only execute between each iteration. This tends to happen in languages like C when doing things like reading from a file or processing a database resultset where a lot has to be done explicitly. Most languages with newer paradigms can structure such code actually into the test.
I would consider using an infinite loop to program the guidance system of a missile.
while ( true ) { go2Target ( ) ; }
From the perspective of the missile's guidance computer, the loop once started does repeat until the end of time.
Perhaps a purists would favor
while ( ! blown2Bits ( ) ) { go2Target ( ) ; }
but then how do you implement the blow2Bits method? what would it mean if blow2Bits returned true?
Nearly all apps use an infinite Main loop. ;)
One example is in a message pump type scenario, where you want to loop forever processing any messages that come in until told to stop. Another is if you want to take a periodic action then you might write an infinite loop with a sleep in it (though it may be better to use some form of timer for this).
There may be some other places where the loop has to perform a certain amount of work to determine whether it should exit, and it may be cleaner just to use break when this condition is true rather than set some external flag to indicate the loop should exit.
Generally though I think it's better practice to put your exit condition in the loop statement if possible, rather than to make it infinite and exit the loop using a break statement, because the exit condition of the loop is more obvious.
There are other questions relating to if/when it's ok to use break in a loop. Let's assume that we agree that it's sometimes ok. In those circumstances (hopefully rare) I would use an infinite loop if there are a number of terminating conditions and no identifiable "primary" terminating condition.
It avoids a long series of disjunctions (or's) and also draws the reader's attention to the fact that there may (almost certainly will) be breaks in the loop.
Ultimately it's a matter of taste.
I use them to write Linux daemons / services that loop until kill / other termination signals are received.
Infinite loops are useful mostly in daemon/service processes or the main loop in a game. You can even get cute with them, eg:
const bool heatDeathOfTheUniverse = false;
do
{
// stuff
} while(!heatDeathOfTheUniverse);
They should not be used to "wait" for things like threads as was suggested by Fry. You can use the Join method of a thread object for that.
However, if you're in a situation where your tech lead says, "infinite loops are verboten & so are multiple method/function returns & breaks" you can also do stuff like this:
bool done = false;
while(!done)
{
if(done = AreWeDone()) continue; // continue jumps back to start of the loop
}
Of course if you tech lead is forcing you to do such things you should start looking for a new job.
For more details on the continue keyword see this MSDN article.
Webservers use an infinite while loop:
while(true)
{
//Do something like respond to requests
}
They don't have to end unless you close your webserver application.
I used to use them when waiting for multiple threads to complete in c#, but now I use the ThreadPool class.
Other than embedded systems situations infinite loops always really are:
Repeat
Something
Until Exit_Condition;
But sometimes Exit_Condition isn't something that can actually be evaluated at the end of the loop. You could always set a flag, use that flag to skip the rest of the loop and then test it at the end but that means you are testing it at least twice (the code is slightly slower) and personally I find it less clear.
There are times when trading clarity for speed makes sense but something that gives neither clarity nor speed just to be technically correct? Sounds like a bad idea to me. Any competent programmer knows that while (true) means the termination condition is somewhere inside the loop.