Next: , Previous: , Up: Miscellaneous  

Q5.1.6: What is the typical misuse of setq ?

A typical misuse is probably setqing a variable that was meant to be local. Such a variable will remain bound forever, never to be garbage-collected. For example, the code doing:

(defun my-function (whatever)
  (setq a nil)
  ... build a large list ...
  ... and exit ...)

does a bad thing, as a will keep consuming memory, never to be unbound. The correct thing is to do it like this:

(defun my-function (whatever)
  (let (a)                              ; default initialisation is to nil
    ... build a large list ...
    ... and exit, unbinding `a' in the process  ...)

Not only is this prettier syntactically, but it makes it possible for Emacs to garbage-collect the objects which a used to reference.

Note that even global variables should not be setqed without defvaring them first, because the byte-compiler issues warnings. The reason for the warning is the following:

(defvar flurgoze nil)                   ; ok, global internal variable

(setq flurghoze t)                      ; ops!  a typo, but semantically correct.
                                        ; however, the byte-compiler warns.

While compiling toplevel forms:
** assignment to free variable flurghoze