Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason to replace while(condition) with for(;condition;) in C++?

Looks like

while( condition ) {
    //do stuff
}

is completely equivalent to

for( ; condition; ) {
    //do stuff
}

Is there any reason to use the latter instead of the former?

like image 609
sharptooth Avatar asked Sep 04 '09 13:09

sharptooth


People also ask

Can every while loop be replaced with for loop Why or why not?

You can always convert a while loop to a for loop. The while loop and the do loop are equivalent in their expressive power; in other words, you can rewrite a while loop using a do loop, and vice versa.

Should I use while or for loop in C?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

Is for loop or while loop better?

In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.

Can we replace while loop with for loop?

for() loop can always be replaced with while() loop, but sometimes, you cannot use for() loop and while() loop must be used.


1 Answers

There's no good reason as far as I know. You're intentionally misleading people by using a for-loop that doesn't increment anything.

Update:

Based on the OP's comment to the question, I can speculate on how you might see such a construct in real code. I've seen (and used) this before:

lots::of::namespaces::container::iterator iter = foo.begin();
for (; iter != foo.end(); ++iter)
{
    // do stuff
}

But that's as far as I'll go with leaving things out of a for-loop. Perhaps your project had a loop that looked like that at one time. If you add code that removes elements of a container in the middle of the loop, you likely have to control carefully how iter is incremented. That could lead to code that looks like this:

for (; iter != foo.end(); )
{
    // do stuff

    if (condition)
    {
        iter = foo.erase(iter);
    }
    else
    {
        ++iter;
    }
}

However, that's no excuse for not taking the five seconds needed to change it into a while-loop.

like image 95
Michael Kristofik Avatar answered Sep 28 '22 11:09

Michael Kristofik