Xpe*_*tor 9 c++ scope initialization c++17
C++17 有带初始化器的选择语句
status_code foo() {
if (status_code c = bar(); c != SUCCESS) {
return c;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我想写一个while-loop 和一个范围仅限于循环的变量,并且在第一次迭代之前只初始化一次。
// fake example, doesn't compile, is doable in many ways
while (bool keep_trying = foo(); keep_trying) {
// do stuff
if (something)
keep_trying = false;
}
Run Code Online (Sandbox Code Playgroud)
在 C++17 或 C++2a 中有什么可以解决的吗?
L. *_* F. 13
介绍if带初始化语句的论文P0305R1很好地解释了这一点。从提案部分:
C++ 中有三个语句,if、for 和 while,它们都是一个主题的变体。我们建议通过添加一种新形式的 if 语句来使图片更加完整。
Run Code Online (Sandbox Code Playgroud)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). 此外,从讨论部分:
人们常说 C++ 已经足够复杂,任何额外的复杂性都需要仔细论证。我们相信提议的扩展是自然的和不足为奇的,因此增加了最小的复杂性,甚至可能消除了各种控制流语句之间的一些现有差异。局部初始化没有任何特定于循环语句的内容,因此只在循环中而不是在选择语句中使用它似乎是任意的。如果 if 语句的初始化形式从一开始就在语言中,它似乎不会不合适。(充其量,人们可能想知道为什么 for 不也拼写为 while,反之亦然。)
"While statement with initializer" = "For statement without update"
for无论语言版本如何,您总是有一个循环。