1

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 Answers2

0

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.

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • So this means that I can declare it inside the function. Thank you very much! – Wolf Poncho Oct 14 '22 at 17:22
  • @WolfPoncho The exact same thing would happen if you were to declare it outside of the function, too. Declaring something inside vs outside of a function affects its scope (ie, which code can access it), not its memory usage. – Remy Lebeau Oct 14 '22 at 18:01
  • @RemyLebeau for a constant that is so, but not for a variable – David Heffernan Oct 14 '22 at 20:25
  • @DavidHeffernan yes, for a non-constant variable, too. If it is declared inside the function, only the function can access it. Declared outside of the function and other code can access it. That doesn't change how the variable is stored in memory, or how it is assigned data. – Remy Lebeau Oct 14 '22 at 21:02
  • @remy I mean a local variable has a completely different lifetime from a global variable. – David Heffernan Oct 14 '22 at 23:24
-1

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.