A constant declaration has the following look:
const constant_identifier = constant_expression; ... constant_identifier = constant_expression;
A constant declaration part starts with the reserved word const
.
It declares a constant_identifier which is defined by
constant_expression. This expression has to be evaluatable during
compilation time, i.e. it can include numbers, parentheses, predefined
operators, sets and type casts (the last, however, is a Borland extension).
In ISO 7185 Pascal, constant_expression must be a constant or
a set. All Pascal Dialects but ISO-Pascal allow the use of these
intrinsic functions in constant_expression:
Abs, Round, Trunc, Chr, Ord, Length, Pred, Succ, SizeOf, Odd.
In Borland Pascal, in the constant declaration part variables can be declared as well, which are given an initial value. These variables are called “typed constants”. It is good style to avoid this use, especially since Extended Pascal and GNU Pascal allow to initialize a variable in variable declaration part or give a type a preset value on declaration.
const FiveFoo = 5; StringFoo = 'string constant'; AlphabetSize = Ord ('Z') - Ord ('A') + 1; type PInteger = ^Integer; { Define a pointer to an Integer } const { Constant which holds a pointer to an Integer at address 1234 } AddressFoo = PInteger (1234);
An example of a typed constant:
const i: Integer = 0;
If you want to use it as a constant only, that's perfectly fine. However, if you modify i, we suggest to translate the declaration to an initialized variable. The EP syntax is:
var i: Integer value 0;
GPC supports this as well as the following mixture of dialects:
var i: Integer = 0;
Furthermore, you can also assign initialization values to types:
program InitTypeDemo; type MyInteger = Integer value 42; var i: MyInteger; begin WriteLn (i) end.
Here, all variables of type MyInteger are automatically initialized to 42 when created.
program BPArrayInitDemo; const MyStringsCount = 5; type Ident = String [20]; const MyStrings: array [1 .. MyStringsCount] of Ident = ('export', 'implementation', 'import', 'interface', 'module'); begin end.
And the following way in EP:
program EPArrayInitDemo; const MyStringsCount = 5; type Ident = String (20); var MyStrings: array [1 .. MyStringsCount] of Ident value [1: 'export'; 2: 'implementation'; 3: 'import'; 4: 'interface'; 5: 'module']; begin end.
There seem to be pros and cons to each style. GPC supports both as well as just about any thinkable mixture of them.
Some folks don't like having to specify an index since it requires renumbering if you want to add a new item to the middle. However, if you index by an enumerated type, you might be able to avoid major renumbering by hand.