4 ms·
I'm wondering what the rationale is for the usage of `goto` in the C source? It looks like it's exclusively used to implement a pattern of exiting or failing ea
by jessedhillon 10y ago
I'm wondering what the rationale is for the usage of `goto` in the C source? It looks like it's exclusively used to implement a pattern of exiting or failing early and in a common way. Is this something that's common in modern C?
- saynsedit 10y agoYes, goto exit and cleanup resources on error is a common and not frowned upon idiom in C. See Python source.
- rossy 10y agoI'm not entirely sure how common it is in modern projects, but I use it a lot. I find functions that use this kind of centralized cleanup code a lot easier to read than functions that avoid 'goto' by duplicating the cleanup code or handling errors with deep nested if blocks. The Linux kernel coding style guide recommends it as well (see "Centralized exiting of functions" in https://www.kernel.org/doc/Documentation/CodingStyle https://www.kernel.org/doc/Documentation/CodingStyle) FWIW, it seems to be the primary use of 'goto' in these projects: https://github.com/torvalds/linux/search?q=goto https://github.com/torvalds/linux/search?q=goto https://github.com/FFmpeg/FFmpeg/search?q=goto https://github.com/FFmpeg/FFmpeg/search?q=goto https://github.com/antirez/redis/search?q=goto https://github.com/antirez/redis/search?q=goto
- mhogomchungu 10y agoI dont use "goto" in C but a specialized static function that does more or less the same thing. Example is the zuluExit "goto" function: https://github.com/mhogomchungu/zuluCrypt/blob/master/zuluCrypt-cli/lib/open_volume.c https://github.com/mhogomchungu/zuluCrypt/blob/master/zuluCr...
- ryan-c 10y agoI don't think that solution works well in general. If you want to do cleanup of local variables, I don't see how you'd do that with a static function unless you're using globals everywhere, some awful god object, or terrible varargs hacks.