I am a java programmer, new to C++. In the code below, I know if( condition1 ) is true variable1 is returned. But is there any mechanism by which the second if is also processed after the first if condition evaluates to true? I am asking this because I have seen code like this and I found it while debugging.
if( condition1 )
{
return variable1;
}
//do some processing here
if( condition2 )
{
return variable2;
}
Although there is a way to run code after the return statement, there is no way to return again after a return statement has been executed.
Here is how you can make some code to run after a return statement:
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;
}
The above program prints
returning...
after return
5
No. Once a return
is encountered, nothing else in the function is processed.
Your function must execute 1 and exactly 1 return
statement.
So, either return variable1
gets executed or if(condition2)
, but never both.
No, code is never executed after a return
statement is reached. If, however, condition1
is false, then the return
statement isn't reached, so execution proceeds normally. This is exactly the way Java behaves, too.
There is an argument against early return
statements, but personally I find them helpful; trying to avoid them can lead to extraneous cruft, such as temporary variables that don't really do you any good or large if
-blocks that are mostly just confusing to read due to their scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With