[fpc-pascal] Pass open array to static array?

Sven Barth pascaldragon at googlemail.com
Sat Apr 4 10:08:20 CEST 2020


Ryan Joseph via fpc-pascal <fpc-pascal at lists.freepascal.org> schrieb am
Fr., 3. Apr. 2020, 21:03:

>
>
> > On Apr 3, 2020, at 10:09 PM, Sven Barth <pascaldragon at googlemail.com>
> wrote:
> >
> > If your DoThis would be declared with a dynamic array parameter (e.G.
> "specialize TArray<Integer>") then you'd in fact have a temporary dynamic
> array constructed on the heap.
> >
> > Also I didn't say that dynamic arrays can't be constant, but that they
> only are so if declared in a const section.
> >
>
> can you post an example of a const dynamic array? I tried and it thinks
> it's a set so I can't assign to an open array.
>

It needs to be a typed constant:

const
  MyArray: array of LongInt = (1, 2, 3);

If the writable constants switch is off then this dynamic array won't be
writable either.


> Also that made me think, is it possible for an open array parameter to be
> written to if its source was a static array? You said it's a pointer so I
> wonder if it's possible to use them instead of passing a static array
> pointer with an additional parameter for the length.
>

Yes that is indeed the case though you'll have to declare the parameter as
var as otherwise the compiler will create a copy on the stack which will be
lost afterwards.

Also open array *always* start at index 0. So if you pass a static array
that's declared as 4..6 then your function will get an open array stsrting
at 0 with length 3 with the element at 0 being the element at 4 of the
static array.

And as a special functionality open arrays allow slicing. That is if you
have an open array parameter you can pass along parts of it to another open
array:

SomeFunc(MyArrayArg[3..High(MyArrayArg) - 3]);

This will also work correctly with var/out open array parameters.

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20200404/b8e9ab75/attachment.html>


More information about the fpc-pascal mailing list