c++scopeinitializationc++17

while statement with initializer


C++17 has selection statements with initializer

status_code foo() {
    if (status_code c = bar(); c != SUCCESS) {
      return c;
    }
    // ...
}

I'd like to write a while-loop and a variable with a scope limited to the loop and initialized only once before the first iteration.

// fake example, doesn't compile, is doable in many ways
while (bool keep_trying = foo(); keep_trying) {
    // do stuff
    if (something)
        keep_trying = false;
}

Is there anything for this in C++17 or a later version of C++?


Solution

  • P0305R1, the paper that introduced the if statement with initialization, explains this pretty well. From the Proposal section:

    There are three statements in C++, if, for and while, which are all variations on a theme. We propose to make the picture more complete by adding a new form of if statement.

    while (cond) E;
    for (init; cond; inc) E;
    if (cond) E;
    if (cond) E; else F;
    if (init; cond) E;         (new!)
    if (init; cond) E; else F; (new!)
    

    (table simplified)

    Note that while (cond) corresponds to for (init; cond; inc). Also, from the Discussion section:

    It is often said that C++ is already complex enough, and any additional complexity needs to be carefully justified. We believe that the proposed extension is natural and unsurprising, and thus adds minimal complexity, and perhaps even removes some of the existing differences among the various control flow statements. There is nothing about the local initialization that is specific to loop statements, so having it only on the loop and not on the selection statement seems arbitrary. Had the initializer form of the if statement been in the language from the start, it would not have seemed out of place. (At best one might have wondered why for is not also spelled while, or vice versa.)