gpt4 book ai didi

c++ - return后可以写statements吗?

转载 作者:太空狗 更新时间:2023-10-29 23:43:28 24 4
gpt4 key购买 nike

return 语句是 main 中的最后一条语句还是可以在 return 之后写语句?

#include <iostream>

using namespace std;

int main() {

cout << "Hello" << endl;

return 0;

cout << "Bye" << endl;
}

此程序编译但仅显示“Hello”。

最佳答案

is it possible to write statements after return?

在return之后写更多的statements是可能的也是有效的。使用 gcc 和 Clang,即使使用 -Wall 开关,我也不会收到警告。但是 Visual Studio 确实会为此程序生成 warning C4702: unreachable code


return statement终止当前函数,无论是 main 还是其他函数。

即使编写是有效的,如果 return 之后的代码不可访问,编译器可能会根据 as-if rule 将其从程序中删除.


您可以有条件地执行 return 语句,也可以有多个 return 语句。例如:

int main() {
bool all_printed{false};
cout << "Hello" << endl;
if (all_printed)
return 0;
cout << "Bye" << endl;
all_printed = true;
if (all_printed)
return 0;
}

或者,您可以在返回前后使用 goto 和一些标签,在第二个输出之后执行 return 语句:

int main() {

cout << "Hello" << endl;
goto print;

return_here:
return 0;

print:
cout << "Bye" << endl;
goto return_here;
}

打印:

Hello
Bye

另一个解决方案,链接到 this answer , 就是返回后用RAII打印:

struct Bye {
~Bye(){ cout << "Bye" << endl; } // destructor will print
};

int main() {
Bye bye;
cout << "Hello" << endl;
return 0; // ~Bye() is called
}

关于c++ - return后可以写statements吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50027068/

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