是否可以在C++中的return语句后执行代码?

Som*_*ude 2 c++

我是一名java程序员,是C++的新手.在下面的代码中,我知道if(condition1)是否为true,返回variable1.但是有没有任何机制可以在第一个if条件求值为true之后处理第二个if?我问这个是因为我看过这样的代码,我在调试时发现了它.

if( condition1 )
{
    return variable1;
}

//do some processing here

if( condition2 )
{
    return variable2;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 17

虽然有一种方法可以在return语句之后运行代码,但是在执行return语句之后无法再次返回.

以下是如何在return语句之后运行一些代码:

struct AfterReturn {
    ~AfterReturn() {
        // This code will run when an AfterReturn object goes out of scope
        cout << "after return" << endl;
    }
};

int foo() {
    AfterReturn guard; // This variable goes out of scope on return
    cout << "returning..." << endl;
    return 5;
    // This is when the destructor of "guard" will be executed
}

int main() {
    cout << foo() << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的程序打印

returning...
after return
5
Run Code Online (Sandbox Code Playgroud)


Nat*_*man 5

否。一旦return遇到 a,函数中的其他任何内容都不会被处理。


Sam*_*ica 4

您的函数必须执行 1 条且恰好 1 条return语句。

因此,要么return variable1被执行,要么被执行if(condition2),但绝不会两者都被执行。