| Constants
Constants are very similar with
variables but with only difference that you cannot change the data
that is stored in the constant and that data is assigned from the
design time of the program.
Constants are either true constants or typed constants. These two
kinds of constant are superficially similar, but they are governed
by different rules and used for different purposes. Before you use
a constant, you need to declare it (assign memory to
it).
Declaring
Constants
True Constants:
A true constant is a declared identifier whose value cannot
change. For example,
const MaxValue = 237;
declares a constant called MaxValue
that returns the integer 237. The syntax for declaring a true
constant is
const identifier =
constantExpression;
where identifier is any valid
identifier and constantExpression is an expression that the
compiler can evaluate without executing your program.(See Constant
expressions for more information.)
If constantExpression returns an ordinal value, you can specify
the type of the declared constant using a value typecast. For
example
const MyNumber =
Int64(17);
declares a constant called MyNumber,
of type Int64, that returns the integer 17. Otherwise, the type of
the declared constant is the type of the
constantExpression.
If constantExpression is a character
string, the declared constant is compatible with any string type.
If the character string is of length 1, it is also compatible with
any character type.
If constantExpression is a real, its type is Extended. If it is an
integer, its type is given by the table below.
Examples of constants
declarations:
const
Min =
0;
Max = 100;
Center = (Max - Min) div 2;
Beta = Chr(225);
NumChars = Ord('Z') - Ord('A') + 1;
Message = 'Out of memory';
ErrStr = ' Error: ' + Message + '. ';
ErrPos = 80 - Length(ErrStr) div 2;
Ln10 = 2.302585092994045684;
Ln10R = 1 / Ln10;
Numeric = ['0'..'9'];
Alpha = ['A'..'Z', 'a'..'z'];
AlphaNum = Alpha + Numeric; |
Typed Constants
Typed constants, unlike true
constants, can hold values of array, record, procedural, and
pointer types. Typed constants cannot occur in constant
expressions.
Constants are declared with the word const. You can declare them
like this:
Declare a typed constant like this:
const identifier: type =
value
where identifier is any valid
identifier, type is any type except files and variants, and value
is an expression of type type. For example,
const Max: Integer = 100;
In most cases, value must be a
constant expression; but if type is an array, record, procedural,
or pointer type, special rules apply.
|