manpagez: man pages & more
info asymptote
Home | html | info | man
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.7 Variable initializers

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:

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.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]
© manpagez.com 2000-2024
Individual documents may contain additional copyright information.