[fpc-pascal] Untyped var params
Dmitry Boyarintsev
skalogryz.lists at gmail.com
Sun Jan 8 00:46:18 CET 2017
On Sat, Jan 7, 2017 at 5:42 PM, Bart <bartjunk64 at gmail.com> wrote:
>
> procedure X(var Y);
> begin
> PInteger(Y)^ := 3; //syntax may be wrong, too lazy to test
> end;
>
> To me this completely defies the purpose of an untyped var parameter,
> since in this exmaple you do know, @design time, the type of Y, so why
> not write then
>
> procedure X(var Y: Integer);
> begin
> Y := 3;
> end;
>
Think about something like a var-type variable, where the actual type of Y
might vary.
procedure XX(var Y; YType: integer);
begin
case YType of
T_INT: PInteger(@Y)^:= 3;
T_SINGLE: PSingle(@Y)^:=3;
T_DOUBLE: PDouble(@Y)^:=3;
end;
end;
Again, earlier in the thread I gave a link to anySort() example, that could
sort any array-like structure (as long as elements of the structure are
placed in sequential order in memory).
As I said mentioned earlier. Untyped parameter, is an implicit pointer
(since the value is always passed by reference).
But there's a compile-time difference.
If you'd declare a parameter as a pointer
procedure X( Y:Pointer);
Then it would be possible to use the function as following:
X(nil)
which requires you, at least add additional sanity check into X procedure.
But if you'd declare it as X(var Y), then the compiler would not allow to
pass nil, always requiring a user to provide a valid variable to be passed
and writing something like X(nil) is no longer possible.
Here's an example:
http://www.freepascal.org/docs-html/rtl/system/iunknown.queryinterface.html
QueryInterface must return an interface variable. BUT:
* the actual returned interface type is unknown at compile time.
* "obj" parameter must not be nil, since the reference must be written
somewhere.
It's also more convenient from syntax point of view, since a developer
doesn't have to write "@" symbol when passing a parameter. The reference
would be resolved by the compiler itself.
thanks,
Dmitry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20170107/3889e783/attachment.html>
More information about the fpc-pascal
mailing list