How to return to main and not the function calling it?

175 views Asked by At

I have a function() which calls anotherFunction(). Inside anotherFunction(), there is an if statement which, when satisfied returns back to main() and not to function(). How do you do this?

4

There are 4 answers

0
Scooter On

You can bypass the normal return sequence in C with the setjmp and longjmp functions.

They have an example at Wikipedia:

#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

void second(void) {
    printf("second\n");         // prints
    longjmp(buf,1);             // jumps back to where setjmp was called - making setjmp now return 1
}

void first(void) {
    second();
    printf("first\n");          // does not print
}

int main() {   
    if ( ! setjmp(buf) ) {
        first();                // when executed, setjmp returns 0
    } else {                    // when longjmp jumps back, setjmp returns 1
        printf("main\n");       // prints
    }

    return 0;
}
2
Bathsheba On

You can't easily do that in C. Your best bet is to return a status code from anotherFunction() and deal with that appropriately in function().

(In C++ you can effectively achieve what you want using exceptions).

0
Ben Voigt On

Most languages have exceptions which enable this sort of flow control. C doesn't, but it does have the setjmp/longjmp library functions which do this.

2
phuclv On

You can't do like that in "standard" C. You can achieve it with setjmp and longjmp but it's strongly discouraged.

Why don't just return a value from anotherFuntion() and return based on that value? Something like this

int anotherFunction()
{
    // ...
    if (some_condition)
        return 1; // return to main
    else
        return 0; // continue executing function()
}

void function()
{
    // ...
    int r = anotherFuntion();
    if (r)
        return;
    // ...
}

You can return _Bool or return through a pointer if the function has already been used to return something else