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 ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.