Declaring variables in conditions

suggest change

A for statement can declare a variable in its initializer, and that variable lasts for the whole loop. A range-based for initializes its loop variable on each iteration. A while condition can also declare a variable. That variable is created each time the condition is evaluated and destroyed at the end of that iteration:

for (int i = 0; i < 5; ++i) {
    do_something(i);
}
// i is no longer in scope.

for (auto& a : some_container) {
    a.do_something();
}
// a is no longer in scope.

while(std::shared_ptr<Object> p = get_object()) {
   p->do_something();
}
// p is no longer in scope.

However, it is not permitted to do the same with a do...while loop; instead, declare the variable before the loop, and (optionally) enclose both the variable and the loop within a local scope if you want the variable to go out of scope after the loop ends:

//This doesn't compile
do {
    s = do_something();
} while (short s > 0);

// Good
short s;
do {
    s = do_something();
} while (s > 0);

This is because the statement portion of a do...while loop (the loop’s body) is evaluated before the expression portion (the while) is reached, and thus, any declaration in the expression will not be visible during the first iteration of the loop.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents