Tuesday, May 1, 2018

goto considered awesome

Some people consider goto harmful.  I don't.

Most arguments I hear for why goto is bad have to do with code readability or that goto is inherently hack-ish.  My response would be that those issues are due to the programmer, not the goto.  I can write difficult to read hacks without using goto.  If there are other reasons to not use goto, please feel free to comment on this post.


First, I will start with a statement.  If you think goto's should not be used, then get rid of your continue, break, and return statements too.  Also get rid of switch, though the 1989 C standard oddly leaves that out (while also noting that "A switch statement casues control to jump...")


3.6.6 Jump statements

Syntax

          jump-statement:
                  goto  identifier ;
                  continue ;
                  break ;
                  return  expression<opt> ;


I'm not sure if there's a term for using goto for error handling in C.  Maybe "error unraveling", "error unrolling", "function unwinding"?

From the Linux kernel coding style documentation (Documentation/process/coding-style.rst):
Albeit deprecated by some people, the equivalent of the goto statement is
used frequently by compilers in form of the unconditional jump instruction.


The goto statement comes in handy when a function exits from multiple
locations and some common work such as cleanup has to be done.  If there is no
cleanup needed then just return directly.

The rationale for using gotos is:

- unconditional statements are easier to understand and follow
- nesting is reduced
- errors by not updating individual exit points when making
  modifications are prevented
- saves the compiler work to optimize redundant code away ;)


Okay, so the first three rationales are good and the last is bonus for compiler writers I guess.  (The nice thing about compiler writers, though, is that deep down inside, they know that regular programmers know more than they do).