Description |
The Const keyword is used to start a section of constant definitions.
The section is terminated by the next keyword in a program.
Within the section, one or more constants may be defined. These can be a mixture of normal or typed constants:
1.Normal constants
These give a name Name1 to a fixed expression, Expression1. The expression must resolve into one of the following types:
Integer number
Floating point number
Character
String
Set
Enumerated value
2.Typed constants
These are very odd. They are constant only in the sense that their value persists all parts of a program. Yet it can be changed (as long as the compiler directive {WriteableConst} is set On).
They are used, for example, when a routine needs to hold values that are preserved across calls.
It is better to use Object Oriented principles to allow data to be preserved across accesses.
3.Constant routine parameters
When passing data to a routine (function or procedure), you can prefix the parameter definition with Const if the value is never updated. This marginally improves performance, clarifies routine operation, and prevents accidental updates of the value.
|
|
Related commands |
Function |
|
Defines a subroutine that returns a value |
Out |
|
Identifies a routine parameter for output only |
Procedure |
|
Defines a subroutine that does not return a value |
Type |
|
Defines a new category of variable or process |
Var |
|
Starts the definition of a section of data variables |
|
|
|
Example code : Illustrating the different constant types |
Const
MAX_LINES = 3;
CRUDE_PI = 22/7;
HELLO = 'Hello World';
LETTERS = ['A'..'Z', 'a'..'z'];
DECISION = True;
var
i : Integer;
begin // Display our crude value of Pi
WriteLn('Crude Pi = '+FloatToStr(CRUDE_PI));
// Say hello to the WOrld
ShowMessage(HELLO);
// Display MAX_LINES of data
for i := 1 to MAX_LINES do
begin // Do some checking - note that Char(i+64) = 'A'
if DECISION and (Char(i+63) in LETTERS)
then ShowMessage(Char(i+63)+' is a letter')
else ShowMessage(Char(i+63)+' is not a letter');
end;
end;
|
Show full unit code |
Crude Pi = 3.14285714285714
Hello World
@ is not a letter
A is a letter
B is a letter
|
|
Example code : Preserving a number value across calls to a routine |
var
i : Integer;
begin
for i := 1 to 8 do
WriteLn('Number = '+IntToStr(GetNextNumber));
end;
// Get the next number from a given sequence
function TForm1.GetNextNumber: Integer;
type // Define a range of numbers returnable by this routine
TNumbers = 0..5;
Const // A typed constant is really a persistent variable : // It's value is preserved across calls to this routine.
{$WriteableConst On} nextNumber : TNumbers = 0; // Start at the beginning
begin // Return the current value
result := nextNumber;
// Increment to the next value
nextNumber := (nextNumber + 1) MOD 6;
end;
|
Show full unit code |
Number = 0
Number = 1
Number = 2
Number = 3
Number = 4
Number = 5
Number = 0
Number = 1
|
|