question  while vs for loop

vipul mehta (10)   Link to this post
can u give an example where a for loop cannot replace while loop?
helios (4790)   Link to this post
THERES NONE
xabnu (67)   Link to this post
when in doubt refer up to helios; the reason is

while( expression ){}

is exact equivalent of

for( ; expression ; ){},

which is perfectly legal.
int main (93)   Link to this post
Just to make sure I get this straight:

1
2
3
4
5
6
7
int bla;

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


This would be legal. I mean, after thinking about it, there is no reason why it should not work. But the thought simply never occured to me.

int main

Last edited on
jsmith (3099)   Link to this post
Syntactically it is correct in non-strict mode (this is because i is not declared where you cin it because you have a stray semicolon after the for()). The loop will never terminate (bla = 1 is an assignment expression that, when converted to bool, will always be true since false == 0 and true == not false). Also, the semicolon at the end of the for() means that what you intended to be the loop body -- the cin << i -- is not actually part of the loop.

But yes, the three expressions inside the for() need not refer to the same variables.
flyersender (3)   Link to this post
just another detail...

cin must be used like that:

cin >> i ;

to display on screen, use cout:

cout << i;
int main (93)   Link to this post
I'm sorry, I mixed up the veriables.
1
2
3
4
5
6
7
int bla;

for (int i; bla = 1;i++);
{
cin>> bla;
}


The input should change the expression that controls the for-loop.
int main
helios (4790)   Link to this post
There's still that semicolon at the end of the for, making it an empty loop.

This topic is archived - New replies not allowed.