带初始化的while语句
C ++ 17具有带有初始化程序的选择语句
C++17 has selection statements with initializer
status_code foo() {
if (status_code c = bar(); c != SUCCESS) {
return c;
}
// ...
}
I' d想编写一个 while
循环和一个变量,该变量的循环范围受限制,并且仅初始化一次
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;
}
在C ++ 17中是否有此功能? + 2a?
Is there anything for this in C++17 or maybe coming in C++2a?
P0305R1 是引入 if
语句并进行初始化的论文,对此进行了很好的解释。在提案部分中:
P0305R1, the paper that introduced the if
statement with initialization, explains this pretty well. From the Proposal section:
在C ++中,有3个语句,无论何时,同时还是主题上的所有
变体。我们建议通过添加新形式的if语句
使图片更完整。
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!)
(简化表)
请注意, while(cond)
对应于 for(init; cond; inc)
。另外,来自讨论部分:
Note that while (cond)
corresponds to for (init; cond; inc)
. Also, from the Discussion section:
经常有人说C ++已经足够复杂了,任何
的额外复杂性都需要仔细说明。我们认为,提议的扩展
是自然且毫不奇怪的,因此会增加
的最小复杂度,甚至可能消除各种控制流语句之间现有的
差异。对于循环
语句,本地初始化没有
的任何内容,因此仅在循环中而不在选择
语句中使用它似乎是任意的。如果
语句的初始化形式从一开始就使用该语言,则
似乎不会错位。 (充其量,也许您会想知道为什么
也不会同时拼写,反之亦然)。