3 ms·
The only acceptable use-case for goto I came across was for error handling and cleanup. If there are multiple points of code failure that all require same clea
by me_me_me 5y ago
The only acceptable use-case for goto I came across was for error handling and cleanup.
If there are multiple points of code failure that all require same cleanup procedure then one section at the bottom is acceptable and can actually keep the code cleaner.
Anything else looks like bad design that ends up producing hard to follow code.
- mikevm 5y agoYes, this is pretty much how it is being used in C code. The other acceptable use-case is breaking out of nested loops. There's also `setjmp()`/`longjmp()` but that's even more rarely used.
- einpoklum 5y agolongjmp() is the C-language version of going-to labels in other functions. Its basic "use" is not having to unwind the stack; but moreover, it lets you avoid cleanup and resource de-allocation. Usually it doesn't make sense to do that (you get memory leaks), but if, say, your memory allocations happen in some kind of arena - you can just leave it in any junk state and then proceed to clear it altogether after your setjmp() instruction.
- SAI_Peregrinus 5y agoThe most common use of setjmp/longjmp I've seen (in embedded development) is to have coroutines in C. The original use AFAIK was usually to implement exceptions of some variety. Neither use is that common these days.
- zelos 5y agoI remember working with two C teams where one did: rc = do_something(); if (!rc) { rc = do_something_else(); } ... do_cleanup(); and the other did: rc = do_something(); if (rc) goto xout; rc = do_something_else(); ... xout: do_cleanup(); I think the goto was clearer and harder to get wrong?