Hamilton LaboratoriesHamilton C shell 2012User guideTutorials

Labels and gotos

Oregon Coast

Labels and gotos
Previous | Next

Topics

Caution: labels and gotos
See also

Caution:  labels and gotos

We haven’t mentioned labels and gotos yet but it probably isn’t a surprise that the C shell allows them. Indeed:

527 D% cat >trythis.csh goto next echo this does not print next: echo this prints ^Z 528 D% trythis this prints

If you want to use gotos to labels, you should be aware that forward references can be little trickier than a more conventional compiled language. The C shell allows you to redefine a label anytime you like. But if you type a goto that refers to previously defined label, the shell has no way of knowing that you intend it to redefine it up ahead. You can keep running the last example over and over this way with exactly the same result: because a new thread is started each time with no prior definition of next, the shell knows it must be a forward reference. But imagine how repeatedly sourcing this script would fail in an infinite loop:

% source trythis this prints % source trythis this prints this prints this prints this prints this prints :

(Beware of actually trying this: you may find it difficult to interrupt out of it.)

The reason sourcing the script a second time turns into an infinite loop is that the label next is already defined after the first run. The second time, when the goto is read from the script, the history list would look something like this:

source trythis goto next echo does not print next: echo this prints source trythis goto next

What particularly gets the shell into a muddle is the way this recurses indefinitely: each time through the loop, it recurses through an another level of sourcing. Ultimately, it runs out of stack space and fails. This is not a nice way to treat the shell!

In general, it’s hard to recommend gotos in any programming language nowadays; in a script you intend to run using source, they can be particularly nasty.

The shell does automatically age labels and throw them away after a while even if they haven’t been redefined. When it discards a label, it also discards any compiled statements it’s been holding onto that could have been executed only by a goto to that label. The cutoff point where the shell begins to discard labels is set by the gotowindow variable. Let’s now clean up after ourselves and move along:

529 D% rm trythis.csh

See also

Miscellaneous statements
Order of evaluation
Tutorial: Scripts
Tutorial: Condition testing
Tutorial: Iteration

Previous | Next

Getting started with Hamilton C shell

Hamilton C shell, as it first wakes up.

Getting started with Hamilton C shell

A first few commands.

You can set the screen colors to your taste.

You can set the screen colors to your taste.