[fpc-pascal] how to use Default to replace this ' FillChar(aRecord, sizeof(aRecord), 0);

Sven Barth pascaldragon at googlemail.com
Thu Dec 8 08:05:20 CET 2016


Am 08.12.2016 05:14 schrieb "Lars" <noreply at z505.com>:
>
> On Mon, December 5, 2016 4:46 am, Dennis Poon wrote:
> >
>
> >
> > Lars wrote:
> >
> >> Do you know about this feature:
> >>
> >>
> >> var SomeRec: TSomeRecord = ();
> >>
> > This is good for global variable.
> > But I wonder whether it has effect in procedure's local variable since
> > it requires the compiler to clear the record on the stack (which is at
> > different location every time).
>
> I tested it and it seems to compile, and then the value is in fact 0 when
> I try to access it and do a showmessage(inttostr(rec.i))... where rec.i is
> an integer...
>
> But just because it compiles and just because it is zero this time, does
> not mean.. it is consistent. So this needs to be confirmed.

I wouldn't trust the initialization of missing fields (after all the
compiler warns about it) as it's undocumented/undefined behavior.

>
> It is weird that fpc allows a local initialized var to compile, but delphi
> 5 rejects it...  Delphi 5 is older and may have not had as advanced stack
> technology as fpc ;-)

It's a feature of FPC. It simply adds an approbiate assignment at the entry
of the function.

> Another trick is to setup a default global, and then just assign the local
> var to the global (copying the contents) which resets the local to the
> global.. i.e. if you assign one global record () default 0 contents, to a
> local... using:
>
> var
>   GlobalDefault := TSomeRec = ();
>
> procedure ...
> var
>   local: TSomeRec = ();
> begin
>   localrec := GlobalDefault

Just use Default(TSomeRec) and be done with it... -.-

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


More information about the fpc-pascal mailing list