When will a constant be created in Delphi XE2?

129 Views Asked by At

I am using Delphi XE2 and I have to write a function which needs some constant arrays. If I declare these inside the function, when will they be created? Each time when the function runs or only once?

Example:

function Something;
const
  Arr: array[0..100] of string = ('string1', 'string2'...);
begin
end;
2

There are 2 best solutions below

5
Andreas Rejbrand On BEST ANSWER

The array will occupy a fixed, constant, region in your process's memory for the duration of the process's life.

In fact, you can easily see that yourself:

Screenshot of IDE with the memory pane displayed.

Each time the timer fires, you'll find that Pointer(@Arr) has the same value, and at that point in memory, you'll find your constant array.

And if you change it using the Memory panel (like string1 to orange1), the change will persist.

0
E.Einsfeldt On

Just to elaborate a little more on Andreas Rejbrand's answer...

If you declare a local constant, it'll remain in compilation even if you declare the same values more than once. These constants will be independent. In other words, if you write:

function Something;
const
  Arr: array[0..100] of string = ('string1', 'string2'...);
begin
end;

function Otherhing;
const
  Values: array[0..100] of string = ('string1', 'string2'...);
begin
end;

You'll get two sets of "string1" and "string2" in your compiled code. If you change (in file or memory) one "string1" to "orange1" in one function, the other "string1" will remain the same. There's no compiler optimization to "unify" those constants.

Aside from being a waste of code, if you have the same constant declared twice, it can become a mess if you change your code in one place and forget to check everywhere else.

In summary, if you have more than one place in your program where you'll use a constant, always consider declaring them global (or in the unit's scope) not locally.