by jcranmer · 4y ago · 0 comments
The 'break' keyword does the exact same function as a goto, why not use a goto? The 'continue' keyword does the exact same function as a goto, why not use a goto?
... Actually, let's play the game even further. The 'else' keyword does the exact same function as a goto. So do 'while' and 'for' and 'do'/'while'. The only things you actually need are 'if' and 'goto', everything else is merely syntactic sugar on top of that.
But it turns out that syntactic sugar does have value. The break and continue keywords are nothing more than gotos that are restricted to breaking out of the innermost loop or continuing to the next loop iteration, respectively, and so you can understand what they do without having to track down the label (or indeed, come up with a name for the label!). It's more mystifying to me that some languages don't extend the syntax to refer to an arbitrary loop in the current loop nest.
In fact, it turns out that labeled break and continue are sufficient to allow you form nearly every possible control-flow graph... and the kind that it doesn't is the one I don't want you to be able to form, speaking as a writer of compiler optimizations.
A break from a named loop is one statement and a label. A goto is one statement and a label. You don’t lose structure by putting the label at the end of the loop instead of the beginning.
Unnamed break is incredibly common, so having a built-in shorthand is quite ergonomic; it also lets you avoid defining a label, which named break doesn’t do. The argument for continue is similar, but continue is less common and maybe doesn’t justify its keyword status. else, for, and do-while all take blocks, so they have the opportunity to encode structure in a way that a break from a named loop doesn’t.
Structured programming is not just a syntax sugar: the restriction encourages more readable programs https://blog.acolyer.org/2016/10/13/go-to-statement-consider...