Name
Const Keyword
Syntax
constName=Expression;Name:Type=Expression;Subroutine header(...; constName:Type; constName: array of const);
Description
Delphi
extends the const keyword of standard Pascal by
allowing you to specify any constant-valued expression as the value
of a constant and by allowing you to give a specific type for a
constant.
If you supply a type, you are creating a typed constant, which isn’t really a constant, but rather is an initialized variable. The lifetime of a typed constant is that of the program or library, even if the typed constant is declared locally to a subroutine.
You can also declare a subroutine parameter as
const or as an open array of
const. A subroutine cannot modify a
const parameter. This has several benefits:
A
constparameter clearly tells the reader that the subroutine does not change the parameter’s value. This improves the readability and clarity of the code.The compiler enforces the restriction. If you accidentally try to assign a new value to a
constparameter, the compiler issues an error message. Note that aconstobject reference means you cannot change the reference. The object itself is notconst.Passing
conststrings, dynamic arrays, and interfaces is slightly more efficient because Delphi can avoid incrementing the reference count when it knows the subroutine will not modify the parameter.
Tips and Tricks
One of the common uses for so-called typed constants is to declare a variable whose lexical scope is restricted to a subroutine, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access