common-lisp Tagbody


For lots of control in a group forms, the tagbody special operator can be very helpful. The forms inside a tagbody form are either go tags (which are just symbols or integers) or forms to execute. Within a tagbody, the go special operator is used to transfer execution to a new location. This type of programming can be considered fairly low-level, as it allows arbitrary execution paths. The following is a verbose example of what a for-loop might look like when implemented as a tagbody:

(let (x)               ; for (x = 0; x < 5; x++) { print(hello); }
     (setq x 0)
     (unless (< x 5)
       (go end))
     (print (list 'hello x))
     (incf x)
     (go prologue)

While tagbody and go are not commonly used, perhaps due to "GOTO considered harmful", but can be helpful when implementing complex control structures like state machines. Many iteration constructs also expand into an implicit tagbody. For instance, the body of a dotimes is specified as a series of tags and forms.