[fpc-pascal] Writeable typed constants - what's the point?

Martin Friebe fpc at mfriebe.de
Fri Jun 19 11:44:31 CEST 2009

J├╝rgen Hestermann wrote:
> > Paul Nicholls schrieb:
>> I also find writable constants hand for things like this where I can 
>> define the 'variable' + values too so I don't have to set the values 
>> at run time:
> But can't you do the same with a variable declaration? If you want to 
> change the value at runtime it's definitely not a constant anymore.
Not always
> Beeing able to change a typed constant was added by Borland as a 
> "quick hack" (because constants were put into the global data segement 
> even in function declarations) but actually its semantic is wrong. If 
> you can change it, it has to be a variable declaration and you should 
> not be able to change a constant.
there is an important difference between
const a: word = 1;
const a = word(1); // never writeable
var a: word = 1;

The1 1st and 3rd are (afaik) the same, if used top level, that is in the 
global context of interface, or implementation

But if
procedure Foo;
  const a: word = 1;
  var a: word = 1;

Then they are 2 difference things.

The "var" version, acts as if your first statement in the procedure was 
"a:= 1;". It initializes the variable each time you enter the function. 
If you enter the function recursively, then each level, has it's own a, 
not touching the value of the callers a

The const version act like a global variable. It is set to 1 once at 
some time before the 1st call to Foo. It will not be initialized again. 
If Foo chages it, it will keep the changed value, even between calls to 
Foo. If Foo enters recursively, it act like a global var, there is only 
one a, shared by all calls to Foo.
If Foo is a Method on an object, then it is shared between all instances 
of the object.
The only difference to a global var is, that no one outside Foo can see 
or access it.

And you can't do that with an initialized var. And there are plenty of 
use-cases for it.


More information about the fpc-pascal mailing list