5.2. Statement Scope
We can define variables inside the control structure of the if, switch, while, and for statements. Variables defined in the control structure are visible only within that statement and are out of scope after the statement ends:
c++
while (int i = get_num()) // i is created and initialized on each iteration
cout << i << endl;
i = 0; // error: i is not accessible outside the loopIf we need access to the control variable, then that variable must be defined outside the statement:
c++
// find the first negative element
auto beg = v.begin();
while (beg != v.end() && *beg >= 0)
++beg;
if (beg == v.end())
// we know that all elements in v are greater than or equal to zeroThe value of an object defined in a control structure is used by that structure. Therefore, such variables must be initialized.
INFO
Exercises Section 5.2
Exercise 5.4: Explain each of the following examples, and correct any problems you detect.
(a)while (string::iterator iter != s.end()) { /* . . . */ }
(b)while (bool status = find(word)) { /* . . . */ }
if (!status) { /* . . . */ }