Software Development

Goto

Once upon a time there was a keyword that showed up in most programming languages - goto. It’s job was to send the Program counter to a different point in a program to be executed.

The first program I learnt to write made use of the goto statement:

10 Print "Shane is cool"
20 goto 10

Back then lines in BASIC were numbered, computer would execute each line in order, until it met a gotostatement that sent it to another line number.

Pascal had labels instead, and goto sent the program counter to wherever the label it was being sent to was:

program exGoto;
label 1; 
var
   a : integer;

begin
   a := 10;
   (* repeat until loop execution *)
   1: repeat
      if( a = 15) then
      
      begin
         (* skip the iteration *)
         a := a + 1;
         goto 1;
      end;
      
      writeln('value of a: ', a);
      a:= a +1;
   until a = 20;
end.

Edgar Djikstra wrote his famous Goto statement considered harmful, which is often cited by programmers as the seminal document on whygoto isn’t used anymore.

The problem, though, is that it is. That is, goto is still in every programming language I know of, just it’s hidden behind some other syntax. Worse, developers today don’t understand this.

Djikstra’s paper is very clear that goto is still useful, his argument was that it shouldn’t be used by developers nearly as much as they were using it.

So, where did he think it was still useful, and where are we using it today?

There are two places that goto remain, and they’re both mentioned in the paper.

Loops, and Conditionals; and that’s it.

My BASIC program was a loop, but in (say) Go it now looks like:

for {
    fmt.Println("Shane is cool")
}

The goto is hidden in the for syntax, it’s the closing brace.

A conditional looks like this in Go:

if 1 == 3 {
    fmt.Println("One equals three?")
} else {
    fmt.Println("One does not equal three!")
}

Again, the goto is hidden in the closing brace of the if syntax.

The only other time that a program counter jumps to another line that’s not necessarily the next is when a function is called. This is still a goto but it’s differentiated by the fact that a new function stack may be created and isn’t necessarily thought of as a goto (but I do!)

Note: Go, like Pascal has a goto statement that points at labels; it’s a reemergence of the goto keyword, but I don’t see it in the wild very often, and it’s still used largely for loops and conditionals (people use it to express the idea of “re-execute code from below this label when a condition is met” or “if condition is met jump to the end label”). There are some syntactical rules associated with it, but, that’s the subject of another post perhaps.

repeat:
fmt.Println("Shane is cool")
goto repeat

Summary

Goto, once upon a time made code messy and difficult to read, so it’s existence has largely been banished from modern programming, but it’s still there, hidden from view.

Published:
comments powered by Disqus