Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling the same function by value and by reference in Delphi

Tags:

delphi

Is it possible to call the same function definition with parameters by value and later in the run time, by reference? something like:

function myfunc(a:string);
begin
a:='abc';
end;
...
later:
b:='cde';
myfunc(b);
caption:=b; //prints 'cde'
...
later:
myfunc(@b);
caption:=b; //prints 'abc'

??

like image 984
dan matei Avatar asked Jul 28 '26 01:07

dan matei


2 Answers

Not the same function, no. You need to use overloaded functions instead, eg:

function myfunc(a: string); overload;
begin
  // use a as needed, caller is not updated...
  a := 'abc';
end;

function myfunc(a: PString); overload;
begin
  // modify a^ as needed, caller is updated...
  a^ := 'abc';
end;

b := 'cde';
myfunc(b);
Caption := b; //prints 'cde'

b := 'cde';
myfunc(@b);
Caption := b; //prints 'abc'
like image 62
Remy Lebeau Avatar answered Jul 29 '26 22:07

Remy Lebeau


First note that your function cannot be called by reference because of the way it's declared.

function myfunc(a: string); overload;

You would have to change this to:

function myfunc(var a: string); overload;

But if you want to call the same function, you need to call the function with a discard variable that is a copy of the input.

b := 'cde';
discard := b;
myfunc(discard);
caption := b; //uses 'cde'

However you can create a second function that trivially wraps the first for you and discards the by ref change:

function myfunc2(s: string);
begin
  Result := myfunc(s);
end;

//Now the earlier code becomes:
b := 'cde';
myfunc2(b);
caption := b; //uses 'cde'

Note, that unlike Remy's answer this uses a different function name and not an overload, because the compiler would be unable to detect which of the 2 functions to call. However, I would strongly argue that this is a good thing. One of the worst things you can do for the maintainability of your program is write identically named functions that are fundamentally different. It makes it very confusing to figure out what is happening on a particular line of code.

like image 45
Disillusioned Avatar answered Jul 29 '26 23:07

Disillusioned