A variable can be assigned a value when it is declared, as in
int x=3;
where the variable x
is assigned the value 3
.
As well as literal constants such as 3
, arbitary expressions can be used
as initializers, as in real x=2*sin(pi/2);
.
A variable is not added to the namespace until after the initializer is evaluated, so for example, in
int x=2; int x=5*x;
the x
in the initializer on the second line refers to the variable
x
declared on the first line. The second line, then, declares a variable
x
shadowing the original x
and initializes it to the value
10
.
Variables of most types can be declared without an explicit initializer and they will be initialized by the default initializer of that type:
int
, real
, and pair
are all initialized to zero; variables of type triple
are
initialized to O=(0,0,0)
.
boolean
variables are initialized to false
.
string
variables are initialized to the empty string.
transform
variables are initialized to the identity transformation.
path
and guide
variables are initialized to
nullpath
.
pen
variables are initialized to the default pen.
frame
and picture
variables are initialized to empty
frames and pictures, respectively.
file
variables are initialized to null
.
The default initializers for user-defined array, structure, and function types
are explained in their respective sections. Some types, such as
code
, do not have default initializers. When a variable of such
a type is introduced, the user must initialize it by explicitly giving
it a value.
The default initializer for any type T
can be redeclared by defining the
function T operator init()
. For instance, int
variables are
usually initialized to zero, but in
int operator init() { return 3; } int y;
the variable y
is initialized to 3
. This example was given for
illustrative purposes; redeclaring the initializers of built-in types is not
recommended. Typically, operator init
is used to define sensible
defaults for user-defined types.
The special type var
may be used to infer the type of a variable from
its initializer. If the initializer is an expression of a unique type, then
the variable will be defined with that type. For instance,
var x=5; var y=4.3; var reddash=red+dashed;
is equivalent to
int x=5; real y=4.3; pen reddash=red+dashed;
var
may also be used with the extended for
loop syntax.
int[] a = {1,2,3}; for (var x : a) write(x);