I have 3 functions: my_fun1(), my_fun2(), and my_fun3().
main() calls my_fun1() which calls my_fun2(), which in turn calls my_fun3().
Upon some pre-defined condition in my_fun3(), I would like my program to go directly back to the main() function at the line my_fun1() was called.
Is it possible to go directly from my_fun3() to main(), or do I have to add some conditions to my_fun2() and my_fun1() to achieve this?
Well, there is a way to jump directly to another point in the code using
longjmp/setjmp, but I’m not going to tell you how because it is a terrible idea. Just about as bad as it gets. So let’s talk about good solutions :-).The most obvious way is to use exceptions. Like this:
If you don’t want to use exceptions, (which may be the case, some may argue that this would be an abuse of exceptions if the reason for going back to main is not “exceptional”) the next most straightforward way is to make
my_fun1,my_fun2, andmy_fun3return values meaning “done”, let’s say anintwhere a value less than0means “go back to main”. Your call structure would look like this: