r_d*_*uck 3 c++ program-entry-point function
是return声明的最后一条语句里面main还是有可能写的语句返回后?
#include <iostream>
using namespace std;
int main() {
cout << "Hello" << endl;
return 0;
cout << "Bye" << endl;
}
Run Code Online (Sandbox Code Playgroud)
该程序编译但只显示“Hello”。
返回后可以写语句吗?
在返回后编写更多语句是可能且有效的。使用 gcc 和 Clang,即使使用-Wall开关,我也不会收到警告。但 Visual Studio 确实warning C4702: unreachable code为这个程序生成。
该return语句终止当前函数,无论是它main还是另一个函数。
即使编写是有效的,如果 之后的代码return不可访问,编译器可能会根据as-if 规则将其从程序中删除。
您可以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;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以goto在返回之前和之后使用 a和一些标签,return在第二个输出之后执行语句:
int main() {
cout << "Hello" << endl;
goto print;
return_here:
return 0;
print:
cout << "Bye" << endl;
goto return_here;
}
Run Code Online (Sandbox Code Playgroud)
印刷:
Hello
Bye
Run Code Online (Sandbox Code Playgroud)
在此答案中链接到的另一个解决方案是在返回后使用 RAII 进行打印:
struct Bye {
~Bye(){ cout << "Bye" << endl; } // destructor will print
};
int main() {
Bye bye;
cout << "Hello" << endl;
return 0; // ~Bye() is called
}
Run Code Online (Sandbox Code Playgroud)