while 带有初始值设定项的语句

while statement with initializer

C++17 有 selection statements with initializer

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

我想编写一个 while 循环和一个 范围受限 的变量到循环并且 只初始化一次 在第一次迭代之前。

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

在 C++17 中或 C++2a 中是否有相关内容?

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

而且无论语言版本如何,你总是有一个 for 循环。

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

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 简化)

注意while (cond)对应for (init; cond; inc)。此外,来自 Discussion 部分:

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