Declaring variables in conditions

suggest change

In the condition of the for and while loops, it’s also permitted to declare an object. This object will be considered to be in scope until the end of the loop, and will persist through each iteration of the loop:

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

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

while(std::shared_ptr<Object> p = get_object()) {
// 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:

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

Table Of Contents