Suppose we have a recursive function, f, that might fail if the input is incorrect. The error in the input can only be detected while f is running.
What is the idiomatic way in C to break out of f(), straight to the original calling function, in case of an error?
Is setjmp/longjmp the usual solution here?
Toy example:
void g() {
int arr[] = {1, 2, -3, 4};
int result = f(0, sizeof(arr)/sizeof(int) - 1, arr);
/* if f() was successful: */
printf("%d\n", );
/* if error occurred in f: do something else */
}
int f(int n, int i, int *arr) {
if (i < 0)
return n;
/*
if (arr[i] < 0) <-- "erroneous input"
break to g()
*/
return f(arr[i] + n, i-1, arr);
}
Options are:
Return a status flag from
f()indicating success or failure. This causes the error to bubble up one level at a time from the depth at which the error occurs, so may not be what you want. Note that this is the only safe option if you need to unwind any allocations or release resources whichf()may have claimed at each level.Use
setjmp()andlongjmp()exactly as you suggest to simulate the effect of throwing an exception and jump directly to the error-handling code.