Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to execute code after return statement in C++? [closed]

Tags:

c++

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;
}
like image 760
SomeDude Avatar asked Apr 04 '13 21:04

SomeDude


4 Answers

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
like image 194
Sergey Kalinichenko Avatar answered Nov 15 '22 05:11

Sergey Kalinichenko


No. Once a return is encountered, nothing else in the function is processed.

like image 42
Nate Hekman Avatar answered Nov 15 '22 06:11

Nate Hekman


Your function must execute 1 and exactly 1 return statement.

So, either return variable1 gets executed or if(condition2), but never both.

like image 33
Sam I am says Reinstate Monica Avatar answered Nov 15 '22 06:11

Sam I am says Reinstate Monica


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.

like image 41
Kyle Strand Avatar answered Nov 15 '22 06:11

Kyle Strand