common-lisp Functions RETURN-FROM, exit from a block or a function


Functions always establish a block around the body. This block has the same name as the function name. This means you can use RETURN-FROM with this block name to return from the function and return values.

You should avoid returning early whenever possible.

(defun foobar (x y)
  (when (oddp x)
    (format t "X (~d) is odd. Returning immediately.~%" x)
    (return-from foobar "return value"))
  (format t "X: ~s~@
             Y: ~s~%"
          x y))

(foobar 10 20)
; X: 10
; Y: 20
;=> NIL
(foobar 9 20)
; X (9) is odd. Returning immediately.
;=> "return value"