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 elementauto 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access