我是一名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)