Name

Const Keyword

Syntax

const
  Name = Expression;
  Name: Type = Expression;

Subroutine header(...; const Name: Type; const Name: 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 const parameter 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 const parameter, the compiler issues an error message. Note that a const object reference means you cannot change the reference. The object itself is not const.

  • Passing const strings, 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, ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.