1 2
|
for (int i = 0; i < 10; i++)
cout << i << ' ';
| |
Can be re-written as:
1 2 3 4 5 6 7 8
|
{
int i = 0;
while (i < 10);
{
cout << i << ' ';
i++;
}
}
| |
The idea here is that we are declaring
i
and an integer. Hence
int i
. When we reach the end of the for statement,
i
goes out of scope and is discarded.
I'm guessing you're more used to the world of C. In C,
i
needs to be defined at the start of a function, but can be used as often as you like in as many
for
statements as you like. It only goes out of scope when you reach the end of your current function. In C++, you can declare variables at almost any point in a function, it does not need to be close to the beginning. It will go out of scope at the next
}
which could be in an
if
statement or inside a loop.
There are individual preferences as to which is nicer:
1 2 3 4 5 6 7 8
|
// in C
void someFunc()
{
int i;
for (i = 0; i < 10; i++)
printf("%d ", i);
}
|
// in C++
void someFunc()
{
for (int i = 0; i < 10; i++)
cout << i << ' ';
} | |
Really, the only functional difference is that
i
goes out of scope at the end of the
for
loop in the example on the right. I (and most C++) people agree that the right-hand method is the way to go. A general rule is to reduce the scope of your variables as much as possible.
When working in C, I often see this:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void someFunc()
{
for i; // reserved as an index for any for loop
for (i = 0; i < 10; i++)
do_something( i );
for (i = 0; i < 10; i++)
do_something_else( i );
for (i = 0; i < 10; i++)
do_another_thing( i );
}
| |
I don't like this sharing because if someone meant for i to be saved and used later, then someone else has just over-written it. By declaring your own variable in a very small scope, you guarantee that you are not screwing around with any other logic, all of your variables are contained. If you just assume that you can use i, then you might be messing up another later piece of logic.