Some History on Assignable Typed Constants in Delphi

@Brian_Long - posting for the UkDevGroup (talk to @jasonukDev) after Paul Woodhams had presented some encounters he had had with Mutable Typed Constants in some Delphi Code.
[Posted with permissions]

Assignable typed constants.

"I was going to pipe up in the meeting, but had to dash out…Re defending it and the observation that what are essentially static var.s are ridiculously implemented with the const keyword, the following occurred to me.The thing about typed constants is they were designed as the syntax for defining constants with non-simple types. E.g. in the case of an integer you can write:

const CMagic = 42;

But for something less trivial, like an array type, you can’t directly express it like that. Typed constants allow this, e.g.:

type
  TSmallArray = array[1..2] of Char;
const
  CSmallArray: TSmallArray = ('a', 'z');

In the case of the trivial constant the compiler can simply use the value anywhere the constant token is referenced.In the case of the typed constant this cannot be done - indeed storage is required for the whole value so parts of it can be referenced as and when. How to achieve this? They elected to use the same internal implementation as a global variable, which also allows in-declaration initialisation, e.g.

type
  TBigArray = array[1..4] of Char;
var
  CBigArray: TBigArray = ('I', 'J', 'K', 'L'); 

By using the same internal mechanism the typed constant gets global storage, initialisation at startup, but local scope - only accessible within the defining routine, if defined as a local typed constant.The wrinkle was that they let these typed constants be assignable, just like the global variable feature their implementation was based on, perhaps working on the basis that it was more effort to restrict the compiler from supporting them than not, and it may be useful to offer an equivalent to a C local static variable.

This feature was present from long, long ago in the days of Turbo Pascal and is fully documented in the old Turbo Pascal Language Guide. In the early days of Delphi this was seen more and more as a ‘bad thing’, hence the compiler option to disable typed constants being writeable. And as Paul said, the option’s default value changed in Delphi 2 to what we currently see.The 2 images below are a couple of pages from The Delphi Clinic in The Delphi Magazine from 24.5 years ago, which include a Q/A on the topic, in case of passing interest.

1 Like