gpt4 book ai didi

c++ - 带初始化的while语句

转载 作者:行者123 更新时间:2023-12-01 14:03:59 30 4
gpt4 key购买 nike

C++ 17具有selection statements with initializer

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

我想编写一个 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;
}

在C++ 17中有什么需要解决的问题,或者也许在C++ 2a中有?

最佳答案

P0305R1是介绍if语句并进行初始化的论文,对此进行了很好的解释。在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!)


(表格简化)

请注意, 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.)

关于c++ - 带初始化的while语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59985550/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com