返回后可以写语句吗? [英] Is it possible to write statements after return?

查看:65
本文介绍了返回后可以写语句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is the return statement the last statement inside main or is it possible to write statements after return?

#include <iostream>

using namespace std;

int main() {

    cout << "Hello" << endl;

    return 0;

    cout << "Bye" << endl;
}

该程序可以编译,但仅显示"Hello".

This program compiles but only displays "Hello".

推荐答案

返回后是否可以编写语句?

is it possible to write statements after return?

在返回之后编写更多的语句是可能且有效的.使用gcc和Clang,即使使用 -Wall 开关,我也不会收到警告.但是Visual Studio确实会为该程序生成警告C4702:无法访问的代码.

It is possible and valid to write more statements after the return. With gcc and Clang, I don't get a warning, even with the -Wall switch. But Visual Studio does produce warning C4702: unreachable code for this program.

return 语句终止当前功能,可以是 main 或其他功能.

即使编写是有效的,但如果 return 之后的代码不可访问,则编译器可能会根据

Even though it is valid to write, if the code after the return is unreachable the compiler may eliminate it from the program as per the as-if rule.

您可以有条件地执行 return 语句,并且可以有多个 return 语句.例如:

You could have the return statement executed conditionally and you could have multiple return statements. For example:

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;
}


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


Or, you could use a goto before and after the return and some labels, to execute the return statement after the second output:

int main() {

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

return_here:
    return 0;

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

打印:

Hello
Bye


链接到此答案的另一种解决方案是,使用RAII在返回后进行打印:


Another solution, linked to in this answer, would be to use RAII to print after the return:

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

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

这篇关于返回后可以写语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆