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:

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 loop

If we need access to the control variable, then that variable must be defined outside the statement:

// 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 zero

The value of an object defined in a control structure is used by that structure. Therefore, such variables must be initialized.


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) { /* . . . */ }


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.59