Version 0 of Why Tcl has no GOTO command

Updated 2000-11-08 18:16:22

Q. Why doesn't TCL have a 'goto' command?

A. (Donal Fellows) Because "goto"s are the bane of structured programming. Let's examine what you might use them for:

1) Implementing a standard control structure.

This simply doesn't fit with the Tcl way of doing things. Remember, [if], [for] and [while] are all ordinary commands with no special privileges. If you want, you can even create your own control structures which are just as much a part of the language as they are.

    proc repeat {script untilKeyword expression} {
        if {![string equal $untilKeyword "until"]} {
            return -code error "malformed repeat: should be \"repeat\
                    script until expression\""
        uplevel 1 $script
        set test [list expr $expression]
        while {![uplevel 1 $test]} {
            uplevel 1 $script

2) Resource cleanup on error exit.

Most Tcl resources are cleaned up automatically on exit from scope. The rest can be handled with the use of [catch] or something built on top of it; it is a better way to do it too, as it is writing code that is saying what you actually mean. (Alas, the code for try/finally is a bit too long for me to reproduce here.)

KBK (8 November 2000) -- Here's one possible implementation of try ... finally ...

3) Creating a state-machine.

It is equally possible to use a mechanism based on Tcl arrays and [eval] to do this, like this:

    array set transition {
       initialState state1
       state1 {
           set state state2
           set x 1
       state2 {
           set state state3
           incr x $x
       state3 {
           set state [expr {($x < 10) ? "state2" : "state4"}]
       state4 {
    set state $transition(initialState)
    while {1} {eval $transition($state)}
    puts $x ;# Can you guess what this does without running the code?

This can even be extended fairly easily into working over events. I leave that as an exercise though.

4) Err. I can't think of a 4) at the moment. :^)

As you can see, you can do a lot with Tcl even without a goto. It often even ends up clearer to the person maintaining the code like that. Everyone's a winner!

David Cuthbert comments on 4):

If you're a code generator, you'll often use a goto for a combination of the above reasons. Of course, if you're a code generator, you're not human, and your code is not intended to be read by humans.

You're also probably spitting out C or assembly instead of Tcl. :-)

Also, see Goto in Tcl.