[fpc-pascal] Declaring an array as var or not in function calls?

Bo Berglund bo.berglund at gmail.com
Thu Apr 13 07:49:15 CEST 2023


On Thu, 13 Apr 2023 00:06:16 +0200, Sven Barth via fpc-pascal
<fpc-pascal at lists.freepascal.org> wrote:

>Bo Berglund via fpc-pascal <fpc-pascal at lists.freepascal.org> schrieb am
>Mi., 12. Apr. 2023, 21:17:
>
>> Now my question:
>> ----------------
>> Since I am modifying the WArgs variable inside the BuildArgumentsArray
>> function and using its new content afterwards in the WriteItem function
>> I assumed that I had to use var as shown above, but I am not certain this
>> is the case...
>>
>
>If you modify the length or the contents of a dynamic array parameter then
>you need to use "var" or "out" modifiers (the later only if you don't need
>the data passed in).

In this case I am assuming that there is no existing data because I change the
length of the array depending on the calculation of the number of needed calls
to complete the write operation.
So it is definitely only an "out" argument (I have never used out before...).

>
>> It seems like it works also if I do not use the vars specification...
>>
>
>It should not. If it does it will likely be an implementation detail and
>you shall not rely on it. Do you have an explicit example for this
>behavior?

Well, I think I have done this earlier but now I have made a quick test using
TBytes and it seems like var *is* needed...

Since I have not used out before I also tested that and it worked like var does.

What is the use case for "out" compared to "var" when it seemingly is doing the
same thing?
Or is it exactly this:
With "out" you get a pristine empty variable which you have to initialize if
needed (setting its length in this case)?
And you are ensured no stale data will be part of it?

>
>And if so, what is the rule for *when* to use var in function call argument
>> lists for items that will be changed inside the called function and used
>> afterwards
>>
>
>The rule is simple: if you need to modify the parameter value itself (e.g.
>changing a primitive type, changing a field in a record, changing an
>array's length or data, changing the value of a class instance - but not
>its fields!) you need to pass it as "var".
>If it's a write only parameter you can even use "out".

So "out" it is unless I need to use the existing data or append new data to it,
in which case I need "var", right?

Thanks!


-- 
Bo Berglund
Developer in Sweden



More information about the fpc-pascal mailing list