4.4 Initialized variables

By default, simple 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.

Managed types are an exception to this rule: Managed types are always initialized: in general this means setting the reference count to zero, or setting the pointer value of the type to Nil. See section 3.9, page 215

Given the declaration:

Var  
  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:

Const  
  SDefault = ’This is an initialized string’;  
 
Var  
  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:

Var  
  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:

Type  
  Point = record  
    X,Y : Real  
    end;  
Var  
  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 variables 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.

Remark: Care should be taken when using initialized pointer types such as PChars. In the following examples, S is a pointer, pointing to a block of constant (read-only) program data. Assigning S

0

will therefor not work. Assigning S itself will of course work.

procedure foo1;  
var  
  s: PChar = ’PChar’;  
begin  
  s[0] := ’a’;  
end;  
 
procedure foo2;  
var  
  s: PChar;  
begin  
  s := ’PChar’;  
  s[0] := ’a’;  
end;