question with for statement(three initialization forms)

There's a for statement code and below is its output and description. I don't quite understand the description of the two declared cout. What does the author want to say? Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
for (int count = 0; count < 10; count++) //first form
      cout << count << “ “;
cout << “\n”;
 
int count;
for (count = 0; count < 10; count++) //second form
      cout << count << “ “;
cout << “\n”;
 
int index = 0;
for (; index < 10; index++) //third form
      cout << index << “ “;
cout << “\n”; 



0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9


This example also illustrates another issue. Notice how count is declared twice. This is legal here because of where the declarations are located. The second declaration is in the local scope, as you’ve already seen, so the second count’s scope lasts until the end of the function or code block (to the end of this code snippet). However, the first declaration is not local.Variables declared in initialization have a restricted scope. These variables’ scopes last until the end of the for statement, which means that once the for statement ends, the variable(s) declared in initialization no longer exist. Thus, when the second declaration is encountered, there is no conflict because the first count no longer exists.
The author wants to explain scopes. You could read more about scoping on this website: http://cplusplus.com/doc/tutorial/variables/
Basically the first for loop uses a local variable limited inside the for loop. Because it's declared and initialized inside a for loop its scope ends with the end of for loop.

The second one declares a same variable named count. This is not a problem since the first count does not exist any more. So declaration is valid. This variable is declared in the scope this for loop exists in like a function body or main etc. It will cease existing as long as it reaches the end of this scope.

The third one just declares a variable in the same scope (that's why it could not be count again - there would be double declaration). The difference with the second case is just that it's initialized outside (before) the for statement.
Topic archived. No new replies allowed.