Constants

A constant is an identifier that marks a value that can’t change. A constant declaration declares a constant within the block containing the declaration. A constant identifier can’t be included in its own declaration.

Constants - 图1constant declaration

Object Pascal allows the use of constant expressions. A constant expression is an expression that can be evaluated by the compiler without actually executing the program. Wherever Standard Pascal allows only a simple constant, Object Pascal allows a constant expression.

Examples of constant expressions follow:

100 'A'x 256 - 1

(2.5 + 1) / (2.5 - 1)

'Borland' + ' ' + 'Pascal' Chr(32)

Ord('Z') - Ord('A') + 1

The simplest case of a constant expression is a simple constant, such as 100 or ‘A’.

constant

Because the compiler has to be able to completely evaluate a constant expression at compile time, the following constructs are not allowed in constant expressions:

  • References to variables and typed constants (except in constant

    address expressions as described on page 35)

  • Function calls (except those noted in the following text)

  • The address operator (@) (except in constant address expressions

    as described on page 35)

Except for these restrictions, constant expressions follow the syntactical rules as ordinary expressions. For expression syntax, see Chapter 5, “Expressions.”

The following standard functions are allowed in constant expressions:

Ab Length Ord SizeOf Chr Lo Pred Succ

Hi Low Ptr Swap High Odd Round Trunc

Here are some examples of the use of constant expressions in constant 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;

C h a p t e r