问题
What are the actual disadvantages of for loop? No, I mean seriously. There must be something right. There are while and do while loops, both effective, yet we have a for loop. There must be some disadvantage in for loop due to which while and do while were developed, right?
回答1:
No, while loops are the basic structure for making loops, based on conditional gotos or assembly jumps if you will. However, because the following code was being written all the time to go through arrays:
int i = 0;
while (i < N)
{
//do something, probably access an array
i++;
}
They created a cleaner, more readable, way to do this:
for(int i = 0; i < N; i++)
{
//do something
}
This is an example of what is called Syntactic sugar.
Because there is no inherent reason for these kind of things to exist a famous quote of Alan Perlis goes "syntactic sugar causes cancer of the semicolon".
That being said, you always have to strive for more readable codes, so go for it.
回答2:
No disvantages at all. I think that Go language did away with while(), it just has for().
回答3:
Even though while(cond){...} and for(; cond; ){...} are equivalent. However, writing a for loop in this way without a counter and incremental expression is weird. To make your code easier and readable, you should use the for-loop in its original and natural format. i.e., for (counter; cond; expr). If you can iterate your loop's body according to the evaluation of a particular expression, then you should stick with a while loop.
回答4:
The disadvantage may be that with the only for loop the "while(cond) { /* do something*/ }" were been invalid code... :-)
来源:https://stackoverflow.com/questions/21869399/disadvantage-of-for-loop