user1937012
user1937012

Reputation: 385

Delphi Procedure Array Parameter confusion

I have here a problem which I do not understand :

procedure TMain.THREAD_SYNC(
              AProgressBar: TProgressBar; 
              ARemoteData: array of RemoteDATA; 
              ALocalData : array of LocalDATA; 
              Number : integer; 
              AInfo : TEdit);

The following procedure works perfectly if I assign to it "smaller arrays" like this

THREAD_SYNC(Remote,Local,0,Edit1)

When I try to assign a larger array to it with over 30.000 records then I get a Stack Overflow error, so I tried and googled ... and I found something about using const so I changed my procedure to:

procedure TMain.THREAD_SYNC(
              AProgressBar: TProgressBar; 
              ARemoteData: array of RemoteDATA; 
              const ALocalData : array of LocalDATA; 
              Number : integer; 
              AInfo : TEdit);

And now it works, my problem is I don't understand why?
What is the difference without const?

Upvotes: 4

Views: 187

Answers (1)

David Heffernan
David Heffernan

Reputation: 613013

These arrays are passed by value which means that they are copied onto the stack and passed that way. Hence the stack overflow errors.

The problem is resolved by making the array parameters const. In that scenario the array is passed by reference rather than value. In other words a single pointer is passed.

In general when passing (potentially) large structures like arrays or records you should always pass them by reference; using const if the method receiving them does not alter the data and using var if the receiver does. This has the added benefit that your code becomes faster because no data needs to be copied.

You should probably alter your method like so:

procedure TMain.THREAD_SYNC(
              AProgressBar: TProgressBar; 
              const ARemoteData: array of RemoteDATA; 
              const ALocalData : array of LocalDATA; 
              Number : integer; 
              AInfo : TEdit);

There is no need to use const for TProgressBar or TEdit, these are classes and classes are stored on the heap with only a reference on the stack.

Upvotes: 6

Related Questions