while statement with initializer

允我心安 提交于 2020-08-24 10:26:04

问题


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 maybe coming in C++2a?


回答1:


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.)




回答2:


"While statement with initializer" = "For statement without updation"

And you have always had a for loop regardless of the version of the language.



来源:https://stackoverflow.com/questions/59985550/while-statement-with-initializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!