6.4. Statement ScopeSome statements permit variable definitions within their control structure: while (int i = get_num()) cout << i << endl; i = 0; // error: i is not accessible outside the loop
Variables defined as part of the control structure of a statement are visible only until the end of the statement in which they are defined. The scope of such variables is limited to the statement body. Often the statement body itself is a block, which in turn may contain other blocks. A name introduced in a control structure is local to the statement and the scopes nested inside the statement: // index is visible only within the for statement for (vector<int>::size_type index = 0; index != vec.size(); ++index) { // new scope, nested within the scope of this for statement int square = 0; if (index % 2) // ok: index is in scope square = index * index; vec[index] = square; } if (index != vec.size()) // error: index is not visible here If the program needs to access the value of a variable used in the control statement, then that variable must be defined outside the control structure: vector<int>::size_type index = 0; for ( /* empty */ ; index != vec.size(); ++index) // as before if (index != vec.size()) // ok: now index is in scope // as before
One advantage of limiting the scope of variables defined within a control statement to that statement is that the names of such variables can be reused without worrying about whether their current value is correct at each use. If the name is not in scope, then it is impossible to use that name with an incorrect, leftover value. |