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

c++, for-loop, loops, while-loop

Solution

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.

Problem

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?

Original source

Related problems