[fpc-pascal] Re: Correct use of var in function calls?

Bo Berglund bo.berglund at gmail.com
Sun Feb 6 18:53:47 CET 2011


On Sat, 05 Feb 2011 15:51:37 +0100, Florian Klaempfl
<florian at freepascal.org> wrote:

>Am 05.02.2011 10:46, schrieb Bo Berglund:
>> But that is not what I am doing at all, so I can stick with a simple:
>>
>> FillArr(Arr: TByteArr)
>>
>> and be sure that I will not get back a different array, but instead
>> get my array filled as requested...
>>
>
>As soon as you call SetLength, this will break havoc. Then a deep copy 
>is generated and it gets ref. count of 1 and it is destroyed at callee exit.

I think I now encountered your warning live.....
What happened is that the caller has a dynamic array, which is set to
length 2 just as a precursor.
Then it calls a method and passes the name of the dynamic array as a
parameter. The function does some digging of data and then decides how
many elements to store, so it applies SetLength in its execution, then
fills the array with the new data.

But when the call returns the length of the array is still 2...

Turns out that this is a case when the declaration of the function
should have var tacked on like this:
function MyFunction(var Data: TByteArr): boolean;

When I added this the length was passed right back and it was possible
to read all of the data by the caller.

So in summary:
If the called method changes the length of teh dynamic array it must
be passed as a var, otherwise the length change will be lost when
exiting the method.


Bo Berglund




More information about the fpc-pascal mailing list