cplusplus.com
C++ : Forum : General C++ Programming : while vs for loop
 
cplusplus.com
Information
Documentation
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs


question while vs for loop

vipul mehta (12)
can u give an example where a for loop cannot replace while loop?
helios (9402)
THERES NONE
xabnu (72)
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)
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 (5804)
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)
just another detail...

cin must be used like that:

cin >> i ;

to display on screen, use cout:

cout << i;
int main (93)
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 (9402)
There's still that semicolon at the end of the for, making it an empty loop.
Topic archived. No new replies allowed.