# Rewriting a for loop as a while/do-while loop

• 04-27-2007
Ashfury
Rewriting a for loop as a while/do-while loop
Okay, I know this isn't exactly rocket science but I can't seem to rewrite this for loop to another type of loop:

Code:

for (; z != n; n = n->l)
{
do_something(n);
}

The problem is the first condition (at the start) of the for loop is blank, instead of something like for (i = 0; i < 25; i++)... so I'm a little confused as to how the loop works...
• 04-27-2007
indigo0086

Code:

for(int i = 1; i < 2; ++i)
{
}

is the same as
Code:

int i = 1;
for(; i < 2; ++i)
{
}

which is the same as
Code:

int i = 1;
while(i < 2)
{

//do something
++i;
}

• 04-27-2007
robatino
In general,
Code:

for (init; cond; inc) {
// loop body
}

is equivalent to
Code:

init;
while (cond) {
// loop body
inc;
}

Edit: If init is blank, there's no init. If inc is blank, there's no inc. If cond is blank, then cond is assumed true (so for example for (;;) is an infinite loop).

Edit: Except for the behavior of continue, as K&R2 reminded me. If there's a continue statement in the for loop's body, then inc is executed before the next iteration. In the while loop, that doesn't happen - the next iteration starts immediately.
• 04-27-2007
Ashfury
Thank you very much :) The replies were very useful.
• 04-27-2007
Salem
for ( a ; b ; c ) d;

Is almost equivalent to

a;
while ( b ) d ; c ;
• 04-27-2007
brewbuck
Quote:

Originally Posted by Salem
for ( a ; b ; c ) d;

Is almost equivalent to

a;
while ( b ) d ; c ;

Well, not quite.

Code:

a;
while(b) { d; c; }

But I understand what you meant.
• 04-27-2007
anon
To be more pedantic: :)
Code:

{ //the loop itself is in a separate scope (life-time of the loop counter)
a;
while (b)
{ // so is the loop body
d; c;
}
}

• 04-27-2007
CornedBee
And to incorporate the continue case:
Code:

{
a;
while(b)
{
transformed_d;
incrementer: c;
}
}

where transformed_d is the sequence of statements in d with each "continue;" replaced by "goto incrementer;"