gpt4 book ai didi

c++ - 使用 if goto 循环的正确方法

转载 作者:太空宇宙 更新时间:2023-11-04 15:02:12 25 4
gpt4 key购买 nike

我想问一下这是否是 C++ 中的正确 goto 循环:

#include <iostream>

int main() {
int i=0, a=0;
this:std::cout << i << " is less than 10\n";
i++;
if( i<10) goto this;
return 0;
}

我在非常古老的 C++ 书中有这个,不知道它在当今的 C++ 中是否正确。

注意:它使用 g++ 在 Linux mint 上编译成功。

最佳答案

可以说,没有正确的方法来使用 goto。改用结构化循环:

for (int i = 0; i < 10; ++i) {    
std::cout << i << " is less than 10\n";
}

如果您坚持使用goto,那么您将不得不更改标签的名称。 this是C++中的关键字,不能作为标识符使用。

关于c++ - 使用 if goto 循环的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30197308/

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