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?
How to return to main and not the function calling it?
190 Views Asked by bee. At
4
There are 4 best solutions below
2
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
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
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
You can bypass the normal return sequence in C with the setjmp and longjmp functions.
They have an example at Wikipedia: