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.
Remark 2 exceptions to this rule exist:
Note that the behavior of zeroing out certain variables can result in invalid content for variables:
The above will result, when run, in an error:
Therefore is is Highly recommended to always initialize variables before using them.
This can be easily done in the declaration of the variables. Given the declaration:
The value of the variable following will be initialized with the provided value. The following is an even better way of doing this:
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:
For constant records, each element of the record that you wish to initialize must be specified in the form Field: Value, separated by semicolons, and surrounded by round brackets.. You can omit fields that you don’t wish to initialize, in fact you can skip all fields. If you skip fields, the compiler will emit a warning.
As an example:
The above declarations will result in the following warnings:
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 a character in the string will therefore not work. Assigning S itself will of course work. The first routine will give an error, the second not: