4.4 Initialized variables

By default, variables in Pascal are not initialized after their declaration. Any assumption that they contain 0 or any other default value is erroneous: They can contain rubbish. To remedy this, the concept of initialized variables exists. The difference with normal variables is that their declaration includes an initial value, as can be seen in the diagram in the previous section.

Given the declaration:

  S : String = ’This is an initialized string’;

The value of the variable following will be initialized with the provided value. The following is an even better way of doing this:

  SDefault = ’This is an initialized string’;  
  S : String = SDefault;

Initialization is often used to initialize arrays and records. For arrays, the initialized elements must be specified, surrounded by round brackets, and separated by commas. The number of initialized elements must be exactly the same as the number of elements in the declaration of the type. As an example:

  tt : array [1..3] of string[20] = (’ikke’, ’gij’, ’hij’);  
  ti : array [1..3] of Longint = (1,2,3);

For constant records, each element of the record should be specified, in the form Field: Value, separated by semicolons, and surrounded by round brackets. As an example:

  Point = record  
    X,Y : Real  
  Origin : Point = (X:0.0; Y:0.0);

The order of the fields in a constant record needs to be the same as in the type declaration, otherwise a compile-time error will occur.

Remark: It should be stressed that initialized variables are initialized when they come into scope, in difference with typed constants, which are initialized at program start. This is also true for local initialized variables. Local initialized are initialized whenever the routine is called. Any changes that occurred in the previous invocation of the routine will be undone, because they are again initialized.