Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is there to return out of a nested function that will end the parent function?

I want something like this to happen:

void a(){
    b()
    // if condition met in b(), exit out of this function also
}
void b(){
    if(condition){
        super return
        // also returns out of function a
    }
}

I can't seem to think of a way to do this. Any help would be appreciated. Thanks!

like image 561
Ricky Su Avatar asked Apr 07 '16 06:04

Ricky Su


2 Answers

Does b has to be void? You could do it normally by:

void a()
{
    // if condition met in b(), exit out of this function also
    if( !b() )
    {
        return;
    }
    //continue...
}
bool b(){
    if(condition)
    {
        return false;
        // also returns out of function a
    }
    return true;
}
like image 126
Dieter Meemken Avatar answered Nov 15 '22 03:11

Dieter Meemken


There is no way in C++ to do exactly what you ask. There are 4 mechanisms provided by which you can achieve something similar.

  1. Return a logical value: Return a value from b, test it in a and exit immediately.
  2. Set a global variable: Set a globally-accessible flag in b, test it in a and exit immediately.
  3. Exceptions: Create a try/catch block in the caller of a, throw an exception in b and catch it outside a.
  4. Setjmp/longmp: Create a setjmp in the caller of a, call longjmp in b.

Those are your choices. You can write helpers or macros or templates to make them easier to use, but that's what you have to choose from.


Edit: deal with global and return value separately.

Please note that this is a complex topic and there are numerous traps for the unwary, including undefined behaviour using longjmp across a non-trivial destructor. Caveat programmer!

like image 43
david.pfx Avatar answered Nov 15 '22 03:11

david.pfx