2

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'

??

0

2 Answers 2

9

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'
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

thanks, but i heed something like for example: myfunc(a,b), then call it either as myfunc(c+2-pi,d+c-3) or myfunc(byref(c),d+c-3). is it possible? (where 'byref' is the 'magic function' i need.)
@danmatei That's nothing like what you've stated in your question. You're not looking for a reference parameter, you're looking for a callback function. I suggest you ask a brand new question; and this time provide a better explanation of what you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.