I was curious if there is a good way to disable returning in a C function.
This is not something I would often want to do, but there are cases where large complex functions should not return within specific blocks of code, and I want to ensure that.
Typically this is to ensure cleanup functions run or that state is not left invalid.
If you have many people working on the code, having some compiler check can be handy since this can slip through by accident.
some_function(void)
{
/* ... code ... */
#define return __noreturn__ /* any unknown identifier */
{ int return; (void)return; } /* avoids gcc's '-Wunused-macros' */
/* ... code which _can't_ return ... */
#undef return
/* ... code which _can_ return ... */
}
This works. but is fairly ugly and I wouldn't want to use this for anything besides a quick local test.
Is there some way to setup macros which disable return end enable again? (maybe using some poison _Pragma?, but it has to be able to un-poison too).
some_function(void)
{
/* ... code ... */
RETURN_DISABLE;
/* ... code which _can't_ return ... */
RETURN_ENABLE;
/* ... code which _can_ return ... */
}
Note 1) I'm aware that in most cases there are better solutions to this, which involve refactoring code, but I think there are some cases where this assurance is useful still.
Note 2) Using goto could still bypass cleanup code, but I'd consider that case out-of-scope for this question.
You are trying to solve an issue with a compiler that should be solved via code reviews and a coding standard.
It is a good rule of thumb that functions shouldn't have multiple exit points. This makes them harder to reason about and also harder to make sure that clean up code runs (your problem here). Also if the function is so large that you think you you might miss a return statement then it may well need to be split in to smaller functions.
e.g. You could have
int some_func(...)
{
init_some_func(...);
err = some_func_work(...)
clean_up_some_func(...);
return err;
}
or something similar. Now a return from the working function will always lead to the clean up being done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With