Node:Top Level, Next:, Up:Binding Constructs



25.1 Top Level Variable Definitions

On the top level of a program (i.e. when not inside the body of a procedure definition or a let, let* or letrec expression), a definition of the form

(define a value)

defines a variable called a and sets it to the value value.

If the variable already exists, because it has already been created by a previous define expression with the same name, its value is simply changed to the new value. In this case, then, the above form is completely equivalent to

(set! a value)

This equivalence means that define can be used interchangeably with set! to change the value of variables at the top level of the REPL or a Scheme source file. It is useful during interactive development when reloading a Scheme file that you have modified, because it allows the define expressions in that file to work as expected both the first time that the file is loaded and on subsequent occasions.

Note, though, that define and set! are not always equivalent. For example, a set! is not allowed if the named variable does not already exist, and the two expressions can behave differently in the case where there are imported variables visible from another module.

define name value Scheme Syntax
Create a top level variable named name with value value. If the named variable already exists, just change its value. The return value of a define expression is unspecified.

The C API equivalents of define are scm_define and scm_c_define, which differ from each other in whether the variable name is specified as a SCM symbol or as a null-terminated C string.

scm_define (sym, value) C Function
scm_c_define (const char *name, value) C Function
C equivalents of define, with variable name specified either by sym, a symbol, or by name, a null-terminated C string. Both variants return the new or preexisting variable object.

define (when it occurs at top level), scm_define and scm_c_define all create or set the value of a variable in the top level environment of the current module. If there was not already a variable with the specified name belonging to the current module, but a similarly named variable from another module was visible through having been imported, the newly created variable in the current module will shadow the imported variable, such that the imported variable is no longer visible.

Attention: Scheme definitions inside local binding constructs (see Local Bindings) act differently (see Internal Definitions).