5 ms·
The use of goto in C for error and exception handling is good practice. It keeps the code easy to read, and also provides common code for error and/or exit han
by palebluedot 10y ago
The use of goto in C for error and exception handling is good practice. It keeps the code easy to read, and also provides common code for error and/or exit handling. You'll see this paradigm used a lot in large open source C projects, such as the Linux kernel and QEMU.
In my experience, a lot of closed source C projects ban goto outright, in (IMO) an overly dogmatic adherence to the idea that all goto use is spaghetti code and therefore bad.
- mianos 10y agoI have used them myself for error handling many times many years ago. When you don't have exceptions and longjmp scares the shit out of you, gotos for error handling are fine by me too. I agree, dogmatic banning of them precludes the useful case of error handling but it is a slippery slope that they seem to be already sliding with got_key:.
- aninhumer 10y agoI'm aware of only two reasonable use cases for goto, both of which could be avoided with extra language features. Namely, breaking out of nested loops (which could be solved with optionally named loops) and error handling (which can be solved by some form of exception flow control). Not that I think C should add these features, goto does these jobs okay, and there's enough stigma that it's unlikely to be used foolishly. But I think it's worth keeping in mind as we think about future languages.