For loops and the death of whiles

NSBCoding :: Coding :: C++

Go down

For loops and the death of whiles

Post  Admin on Wed Jun 08, 2011 12:50 pm

Syntactically, a for loop has the following anatomy:

Code:
for([i]variable declaration[/i]; [i]condition[/i]; [i]some actions[/i])

Typically, it's something like this:
Code:
for(int i = 0; i < n; i++) {
    // stuff
}// which is the same as...

int i = 0;
while(i < n) {
    // stuff
    i++;
}

Please don't do crazy for loops like these:
Code:
for(int a, b, c = 0; a < 5 && b != 0; scanf("%d\n"), a++) {
}

Admin
Admin

Posts : 21
Join date : 2011-06-04

View user profile http://nsbcoder.board-directory.net

Back to top Go down

Re: For loops and the death of whiles

Post  Elusive on Wed Jun 08, 2011 1:10 pm

An interesting feature of for loops, other than looking cleaner (yes, please don't do that), is that variables declared in the loop statement will only last until the loop ends, they have a very small scope.

Code:

for (int i = 0; i <= 9001; i++);
{
    printf("%d", i); // Will work
}

printf("%d", i); // Will not work, i is undeclared here.

You can always do this if you need that variable later, for whatever reason.
Code:

int i = 0;
for (; i <= 9001; i++)

Elusive
Newbie

Posts : 10
Join date : 2011-06-04

View user profile

Back to top Go down

Back to top

- Similar topics

NSBCoding :: Coding :: C++

 
Permissions in this forum:
You cannot reply to topics in this forum