Possible Duplicates:
Iterate with for loop or while loop? Loops in C - for() or while() - which is BEST?
When should one use a for
loop instead of a while
loop?
I think the following loops are开发者_运维问答 identical, except for their syntax. If so, then why choose one over the other?
int i;
for (i = 0; i < arr.length; i++) {
// do work
}
int i = 0;
while (i < arr.length) {
// do work
i++;
}
In your case, you don't gain much besides one less line of code in the for
loop.
However, if you declare the loop like so:
for(int i = 0; i < x; i++)
You manage to keep i
within the scope of the loop, instead of letting it escape to the rest of the code.
Also, in a while loop, you have the variable declaration, the condition, and the increment in 3 different places. With the for loop, it is all in one convenient, easy-to-read place.
Last thought:
One more important note. There is a semantic difference between the two. While loops, in general, are meant to have an indefinite number of iterations. (ie. until the file has been read..no matter how many lines are in it), and for loops should have a more definite number of iterations. (loop through all of the elements in a collection, which we can count based on the size of the collection.)
There is one reason to choose for
over while
: Readability.
By using a for
loop, you're expressly saying your intent is to perform some type of operating that requires an initialization, a "step" operation, and a completion condition.
With while
, on the other hand, you're only saying you need the completion condition.
I use 'while' when I don't necessarily need a counter, for example when you are reading from a file and you are waiting to reach EOF. In this case 'for' may not be the best alternative. When you are going through items on an array I'd rather use 'for' because it conveys intent better.
The one notable difference between a for() and while() loop is that a "continue" statement in a while() loop will branch to the top of the loop, while one in a for() loop will branch to the third part of the for() clause [the one after the condition, usually used to bump variables].
As a teacher I have been pondering this in various shapes and forms; my suggestion always boils down to
for
-loops are for counting. counting up, counting down.while
/do-while
constructs are for all other conditions.c!=EOF
,diff<0.02
, etc. Iterators/Enumerators are counters very suitable for for-loops.
i.e. your int=0; while( ... )
is hideous to my eyes.
Why choose Coke over Pepsi?
Between a WHILE and FOR loop, you can use them interchangeably. To be a purist, you could make your decision base on the nature of the conditions. If you're performing a count-based loop, then a FOR loop would make the most sense.
for( cur = 0; cur < myList.Length; cur++ ){
doSomething( myList[cur] );
}
If you're performing a logic-based loop, then a WHILE would make for the cleanest implementation
Iterator i = myObject.getIterator();
while( i.hasNext() ){
doSomething( i.next() );
}
As you say, the reasons are semantical and aesthetical, rather than performance (their compiled code tends to be very similar).
That said, for
is usual in cycles which have a known number of iterations, whereas while
implies that the condition isn't necessarily correlated to what you're doing inside the cycle, or that you don't know at the beginning how many iterations there will be.
Generally, I always prefer for loops, even for cases where the loop has nothing to do with counting, because it localizes maintenance of the loop in a single location. When someone else comes along and decides to add/modify the loop, if they are using a FOR loop, the person doing the modification can generally be confident that, so long as they don't mess with items inside the FOR expression(s), they aren't going to break iteration in the loop.
However, something like a while loop requires the programmer to parse the loop body completely, and understand how it iterates, to make sure they keep loop maintenance code unmodified and in the correct order when they make changes.
Therefore, I only use WHILE in cases where I only effectively need the middle part of the FOR.
They are functionally identical, however, it can be argued that the for loop is less error prone, because all of the loop functionality is right there together. if you have several lines separating the declaration of i, the while declaration, and the index iterator, you could forget, or be confused by how it is used. This is all subjective of course.
In the early times of programming a prevalent data structure was the linear array (aka vector) and a repeating pattern was to traverse and use each element of the array. So usual was this scenario that the languages included a specific syntax for this pattern: the for loop. Aside from this historical heritage you could use the while loop all right (well nowadays with functional languages like F# you'd rather use List.map or List.fold ;-)
It's mostly an issue of readability. Generally, use for loops when you have a defined range of values to iterate over. Use while loops when you aren't iterating, or don't know when your exit condition will be true.
From a java perspective, I find for loops very handy for collections:
for (Object o : objects){
o.process();
}
is a lot easier to read than:
int i=0;
while(i < objects.size()){
objects.get(i).process();
i++;
}
They'll usually compile to the same end result. I prefer for's or for-each most of the time. Writing
for (;x<5;x++){
//do work
}
isn't so sinister, but writing
while(x<5){
x++
//do work
}
instead of
while(x<5){
//do work
x++
}
could confuse some people and cause off-by-one errors.
In a language like Pascal, for and while constructs had different applications. You would write a for loop in Pascal as follows:
for i := 1 to 5 do
begin
{ some code here }
end
So you explicitly state that i is incremented by 1. There is no termination condition explicitly specified over here. Thus you could use a for loop only in places where you know the loop will run for certain pre-determined number of times before the actual loop execution starts. On the other hand, you can specify an explicit termination condition in the case of a while loop.
i:=0;
while (i<>5) do
begin
{ some code here }
i:=i+1;
end
Thus a while loop is much more flexible. Later on when C was developed, although for and while were supported, the meaning of the for construct changed and you could add in explicit termination conditions using boolean operators. Thus, the power of while and for in C and C-like languages is same and thus it becomes more of a readability issue than a usability issue.
Glancing over the other (very good) answers, there's a point I didn't see getting made. (If it did get made I missed it and apologize.)
I'm going to give you two snippets of seemingly semantically identical code.
Snippet #1:
for (int a = 0; a < arr.length; a++) {
/* do some work here */
}
Snippet #2:
int b = 0;
while (b < arr.length) {
// do work
b++;
}
They look like they do the same thing, right? Now let me add one single line to each snippet and let's see what happens:
Snippet #3:
for (int c = 0; c < arr.length; c++) {
/* do some work here */
}
printf("%d\n", c);
Snippet #4:
int d = 0;
while (d < arr.length) {
// do work
d++;
}
printf("%d\n", d);
So when I compile a junk file with those four snippets embedded (plus some glue to have arr.length mean something) I get the following error:
$ clang junk.c
junk.c:20:17: error: use of undeclared identifier 'c'
printf("%d\n", c);
^
1 diagnostic generated.
Using the for
loop, it turns out, allows you to provide more locality to your dummy counter variables, etc. This gives you greater leeway in reusing variable names without chance of collision (albeit at the expense of increasing potential shadowing).
Generally, the difference between a while loop and for loop is syntax and not performance related. That said, it looks like this question was already addressed for Java: Java for loop vs. while loop. Performance difference?
Readability. And from the old VB 6 days of wend whenever I see a while I want to cry.
There are some cases while loops are good to use. Calling a function on an object that returns true/false but iterates a value inside that object.
Example being a DataReader in C#:
List<string> strings = new List<string>();
while(DataReader.Read())
{
strings.Add(DataReader["foo"].ToString());
}
A for loop allows you to encapsulate your work within a function, which gives better memory management. Also, if there is an error in your while loop, it could spiral into an out of control loop that threatens all life:
bool keepGoing = true;
while(keepgoing)
{
try
{
//something here that causes exception, fails to set keepGoing = false;
keepGoing = false;
}
catch(Exception)
{
//Do something, but forget to set keepGoing.
//maybe there is always an exception...
}
}
I also think it's just general practice. Much like in construction. You use nails for putting roofing flats onto the studs. You "could" use screws, they would do the same job, but it's just not common practice.
No one is saying it's wrong, we're just saying "please fold under the pressure of your peers to keep the coding world functioning".
There is a semantic difference between for
and while
loops. With for
loops, the number of iterations is pre-defined, whereas with while
loops it is not necessary.
Some languages (such as Ada) enforce this, by making the for
loop counter a constant within the loop body. Hence it would be illegal to say, for example:
for i in values'range loop
...
i := i + 1; -- this is illegal, as i is a constant within the loop body
end if;
This semantic difference, however, is not so clear with most languages, which do not treat the for
loop counter as a constant.
Just decide on one and then copy and paste / adjust it throughout your projects. Less decisions, less typing, faster coding. Negligible performance difference.
Also I am not with Justin keeping i
in the scope of the loop, AND I use
var aL = array.length
outside the loop too. Then use i
and aL
within the for
loop constructor so you are not recalculating the length of the array on each hit (along with a var creation over and over ;)). Again neg. performance really (see first bit of my answer), unless you have very big arrays flying around. If you happen to know the array length upfront initiate it with its fixed length first (slight help with memory allocation on crappy browsers ;) if this is client side and you have a lot of data).
js example
<script>
var i=0;
var myArray = ["D","R","Y"];//literal style will do for now;)
var aL=myArray.length; //or use 3 if known upfront
for(i;i<aL;i++){/*always do DRY things here*/}
</script>
also ensure when a condition is met, ask yourself "do I still need to complete the whole loop?" If not don't forget to break out of the loop as early as you can.
Related trivia:
In Google's new Go language, they have decided not to include the while statement. Instead they allow you to write a for statement that only has the condition clause. So the equivalent of
while (a < b) { ... }
is simply
for a < b { ... }
Simply put:
A 'for' loop tends to be used for iterational use. You need to iterate through an array, you need the numbers 1 through 100 (or other ranges) for various reasons.
A 'while' loop tends to be a conditional loop. You want to keep doing something until a contition is false. Assuming you have a class called 'Toast' and you wanted to cook the toast until it is toasted, you would have something like the following:
while (!toast.isToasted) cook(toast);
You can most always (I can't think of an example where you can't) write a for loop as a while loop and a while loop as a for loop, but picking the one which best first the situation usually comes down to my above points.
Readability is a very important point, but it works both ways. I'll convert a for-loop to a while-loop—even when I'm using a counter variable or it would otherwise be "natural" to use for—when it's more readable that way. This is common when you have a long or complex expression in any of for's three parts or multiple counters (which is related to being complex).
Knuth's loop-and-a-half also works better, in several languages, as an infinite loop with a break, rather than a for-loop.
However, there is a very important semantic difference:
for (int i = 0; i < arr.length; i++) {
if (filter(arr[i])) continue;
use(arr[i]);
}
int i = 0;
while (i < arr.length) {
if (filter(arr[i])) continue;
use(arr[i]);
i++;
}
Use for-loop when it's appropriate. The while solution has syntactic drawbacks (it's longer) and you have to check that you increment i before any continue call within the loop.
Preference. For me all the looping logic is built into the for statement so you do not have to declare the counter variable or do the increment/decrement stuff in the actual loop. Also, the you can declare the counter/index local to the for statement.
For loops are often easier to parallelize. Since the program can tell in advance the number of iterations that will be performed and the value of the iterator at any point, parallelization using an API such as OpenMP is trivial. Of course if you get into breaks, continues, and changing the iterator manually this advantage disappears.
because latter can be one liner: while (++i < arr.length) { // do work }
One reason is that a while's condition can be a string.
Also, if we add 'Do' to the mix, we can use a do while loop when we want the operation to run at least once regardless of its current state.
Its just my logic that we generally use for loop when we know the exact count of our itterations and we use a while loop when we generally want to check a condition.Then we use them according to ur requirments. Otherwise they both show same behaviour.
A while loop, defined as
while(condition)
represents this programming pattern:
1:
if(!condition) goto 2;
...
goto 1;
2:
Whereas a for loop, defined as
for(var i = seed; condition; operation)
represents this pattern:
var i = seed
1:
if(!condition) goto 2;
...
operation;
goto 1;
2:
Both patterns are so commonly used that they have been named and built into languages.
If you need to define a counter to control your loop, use a for loop. If not, use a while loop.
精彩评论