3 ms·
I spend a lot of time dicking with embedded C code. I think using goto is reasonable some cases. The classic case is to short circuit a block of code when there
by Gibbon1 6y ago
I spend a lot of time dicking with embedded C code. I think using goto is reasonable some cases. The classic case is to short circuit a block of code when there is an error of some sort.
function(){
// early returns here.
// stuff
// more stuff
if(oops_err){
goto some_error;
}
// yet more stuff
// normal exit
return 0;
// bad exit
some_error:
// clean up
return oops_err;
}
The above is fine, you avoid a convoluted execution path. Or cleanup and a return in the middle of a function. Looking at the top of the function you see early returns. Looking at the end you see the normal and error exits.
- rtomayko 6y agoThis is specifically allowed in the Linux kernel coding style guidelines as well FWIW: https://www.kernel.org/doc/html/v4.10/process/coding-style.html#centralized-exiting-of-functions https://www.kernel.org/doc/html/v4.10/process/coding-style.h...
- someguydave 6y agoNot only is it fine, I think it's easier to reason about the control flow with this code than with languages that support exceptions like C++.