C++ variable scope and the for loop

C++ allows you to re-use variables in nested scopes.

A confusion arises sometimes, especially with those new to C++ rules, as to the variables at the top of a for loop.

In a for loop, such as for (int i = 0; i < 2; i++) { ... }, does the int i belong to the outer scope or the scope within the for loop.

The answer is that it belongs to the inner loop, and hides any outer variables, if they exist.
Of course, this is best shown with an example.

Three variables: i, j, k
Variable i is defined both in the outer scope and as a loop index variable defined in the top of the for statement.
Variable j is defined both in the outer scope and within the curly brackets of the for loop.
Variable k is only defined in the outer scope.

The treatment of i is the same as j. It’s as if all of the statements at the top of the for loop are inside the curly brackets of the for loop.

Sample Code:
[code lang="cpp"]
#include
using namespace std;

void report(string label, int i, int j, int k)
{
cout << label << " i:" << i << " j: " << j << " k: " << k << endl;
}

int main ()
{
int i = 123;
int j = 456;
int k = 789;

report("before loop", i, j, k);
cout << endl;

// inner scope i hides outer scope i
for (int i = 0; i < 2; i++)
{
// inner scope j hides outer scope j
// outer scope k not hidden
int j = i;
report("in for loop", i, j, k);
}
cout << endl;
report("after loop ", i, j, k);
return 0;
}
[/code]

output:

[bash] > g++ -Wall -o scope for_loop_scope.cpp
> ./scope
before loop i:123 j: 456 k: 789

in for loop i:0 j: 0 k: 789
in for loop i:1 j: 1 k: 789

after loop i:123 j: 456 k: 789
[/bash]

Please leave a comment if you feel I’ve gotten something wrong here.
If your compiler does something different, I want to hear about it.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">