by kbenson · 11y ago · 0 comments
It does not use macros or goto and I find that it makes the code easy to reason locally about.
In summary:
struct RefreshDevices {
// fields that require clean up
}
static void deinit_refresh_devices(struct RefreshDevices *rd) {
// clean up rd regardless of what state it's in
}
static int refresh_devices(struct SoundIoPrivate *si) {
struct RefreshDevices rd = {0};
if (error_occurred) {
deinit_refresh_devices(&rd);
return ErrorCode;
}
// ...
deinit_refresh_devices(&rd);
return 0;
}
Whenever the ownership of a resource changes to something other than the stack of refresh_devices, you just null it out and it won't get cleaned up.If calling deinit on every exit path of the function is too much typing you can wrap that function in another function that calls deinit, and the function doing the actual work can just return an error code without worrying about cleanup.
What's the benefit of this way over a more explicit coding style? The only benefit is saving a few lines of typing. Code is typed once and read 1000's of times. It's better to optimize code for reading, not for writing.
Feel free to read the Joint Strike Fighter (JSF) coding standards which says "Goto shall not be used", and "Macros shall not be used, inline functions are preferred". Also, see NASA's Joint Propulsion Labs (JPL) coding standards where they recommend against using goto, and only allow simple macros (hint: a goto inside a macro is not simple).
Some really smart people put a lot of effort into creating coding standards for critical systems. Even if you don't believe me, when Bjarne Stroustrup is hosting the coding standard on his personal website you might want to pay attention.
On the other hand no other engineering will be asked to change the requirement and spec hundreds of time during its lifetime either since that would be impossible to achieve.
From earlier this year, NASA's 10 rules for safety critical systems [1]:
Rule 1: Restrict all code to very simple control flow constructs.
Do not use GOTO statements, setjmp or longjmp constructs, or
direct or indirect recursion.
I don't think gotos are inherently bad, but I choose to heed the advice of people with more experience than me. (I do think that hiding gotos in macros is inherently bad, though.)[1] http://sdtimes.com/nasas-10-rules-developing-safety-critical...
Also note that systemd employs gcc's __attribute__((cleanup(...))) logic to improve code clarity.