Yung Hee
Yung Hee

Reputation: 33

defvar without initial value does not define the symbol

Shown in following IELM session, defining a variable using defvar without initial value does not define the symbol for the variable. Then why use defvar without initial value? Is it just for documentation and/or compiler help?

ELISP> foo 
*** Eval error ***  Symbol's value as variable is void: foo
ELISP> (boundp 'foo)
nil
ELISP> (defvar foo)
foo
ELISP> (boundp 'foo)
nil
ELISP> (defvar foo t)
foo
ELISP> (boundp 'foo)
t
ELISP> 

Upvotes: 1

Views: 249

Answers (1)

phils
phils

Reputation: 73256

This syntax is used to tell the byte compiler that a variable exists, when it does not otherwise know that to be true, thus avoiding compilation warnings.

This is described in the manual at C-hig (elisp) Compiler Errors :

• You can tell the compiler that a function is defined using
  ‘declare-function’.  *Note Declaring Functions::.

• Likewise, you can tell the compiler that a variable is defined
  using ‘defvar’ with no initial value.  (Note that this marks the
  variable as special.)  *Note Defining Variables::.

It also tells Emacs that the variable uses dynamic binding (i.e. is "special", as mentioned in the quote). In Emacs Lisp this is the default, of course; but in libraries for which lexical binding has been enabled, even if you have no particular need to give the variable an initial value, it is necessary to do this if the variable is to be bound dynamically.

The defvar docstring also indicates this latter point: C-hf defvar :

The `defvar' form also declares the variable as "special",
so that it is always dynamically bound even if `lexical-binding' is t.

Upvotes: 2

Related Questions