tags:

views:

107

answers:

2

The question basically is similar to what is posted here http://stackoverflow.com/questions/1514382/example-of-a-while-loop-that-cant-be-a-for-loop except that there isn't one such example where a certain program using the while loop cannot be replaced by the for loop because of its limitations.

An example is

i=0;
while(i<10)
{
continue;
i=i+2;
}

and

for(i=0;i<10;i++)
{
continue;
i++;
}

In the for loop the continue doesn't stop the increment. I wanted to see something different.

+5  A: 

It is obvious that such does not exist, because any while() loop of the form:

while (expression) { }

can be replaced with

for (;expression;) { }

The same is not true of do { } while () loops.

caf
+1 correct, the only difference is intention and semantics I believe.
alex
+6  A: 

There's no such situation.

In particular, any

while( condition )

may be replaced by

for(; condition ;)

to achieve identical behavior.

Mark E
I know it can be achieved in normal conditions. But there has to be a certain implementation while solving a certain problem where the sequence of instructions will not have the same behavior on the for loop.
SkinD
@SkinD, I believe what's written above will compile to identical native code -- the point is that the statements are truly equivalent and don't generate different instructions.
Mark E
Look at the edit above. The answer I want here is something really stupid. I know while loops and for loops can have identical behavior. I basically want more examples like what I have shown above.
SkinD
@SkinD, your example isn't really valid. I can create a loop that acts differently in a hundred different ways but that's not what you asked ("cannot be replaced with a `for` loop"). The correct for loop for your while, based on this answer, is: `i=0; for(;i<10;) { continue; i=i+2; }`
paxdiablo
Yes, I want to see those hundred different ways. I don't know how to phrase questions. :(
SkinD
@SkinD: Then it is a completely uninteresting question - it is equivalent to the question *"what are some examples of two `while()` loops that are not the same?"* , which should be self-evidently ridiculous.
caf
@SkinD, you have mistranslated your example above. The correct translation to for is: `i=0;for(;i<10;) {i=i+2;}` which behaves identically to the while loop you gave. What mark and caf is saying is not only that for and while *can* have identical behavior but that `for(;something;)` *is* an exact implementation of `while(something)`.
slebetman