These forms constitute the basic way for declaring and initializing data:
identifier-list : type; identifier-list : type = expression;A comma-separated sequence of identifiers is followed by a colon and then the name of a type. Each identifier is declared as having that type and denotes a particular object for the rest of its scope (see Scope). If the declaration contains
=
and an expression, all the objects are initialized from the value of the expression. In a declaration at the top level (outside a function), the expression must be constant or an array initialized with constant expressions; the bound of any array must be a constant expression. Lists and ref
adt
types can not be initialized at the top level.
If an object is not explicitly initialized, then it is always set to nil
if it has a reference type; if it has arithmetic type, then it is set to 0 at the top level and is undefined if it occurs within a function. For example,
i, j : int = 1; r, s : real = 1.0;declares
i
and j
as integers, r
and s
as real. It sets i
and j
to 1
, and r
and s
to 1.0.
Another kind of declaration is a shorthand. In either of:
identifier := expression; (identifier-list) := expression;identifiers on the left are declared using the type of the expression, and are initialized with the value of the expression. In the second case, the expression must be a tuple or an
adt
, and the types and values attributed to the identifiers in the list are taken from the members of the tuple, or the data members of the adt
, respectively. If the identifier is replaced by nil
, nothing new is declared. For example:
x : int = 1;and
x := 1;are the same.
(p, q) := (1, 2);declares the identifiers on the left as
int
and initializes them to 1 and 2 respectively. Declarations with :=
can be expressions, and are discussed again in Declare expressions.