0

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?

phuclv
  • 37,963
  • 15
  • 156
  • 475
bee.
  • 11
  • @mafso: Ahh, you're right. The standard talks about "the initial call to `main()`" implying there can be others. – Ben Voigt Dec 05 '14 at 17:03

4 Answers4

5

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

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • @Bathsheba it may be useful in some situations but not in this case because there are easier and safer solutions – phuclv Dec 05 '14 at 16:56
  • 2
    Both setjmp and longjmp are standard C as you have even referenced them. – b4hand Dec 05 '14 at 16:59
2

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;
}
Scooter
  • 6,802
  • 8
  • 41
  • 64
2

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).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • This is incorrect. The standard setjmp and longjmp provide exactly this functionality. – b4hand Dec 05 '14 at 17:06
  • 1
    I guess it's down to *easily*. I dislike having to store the buffer. I really wouldn't recommend it and stand by my recommendation of using return codes. – Bathsheba Dec 05 '14 at 17:07
2

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720