Passing Parameters

Passing Parameters By Value

By default, when you pass a parameter to a Delphi function Delphi will create a copy of the value in a new variable, and pass that new variable to the function – this means you can change the value of the parameter inside the function, and the value of the variable passed will remain untouched. This is called passing by value.

Passing Parameters By Reference

Passing by value is very useful, but as the computer needs to copy the value before passing it to the method, is slightly less efficient.

const parameters

If you do not need to change the value of a parameter in a delphi method, you can specify the const keyword before the parameter:

The const keyword tells Delphi that you do not want to change the value of the parameter inside the procedure, and passes a reference to the original variable, and as it does not need to create a new variable when calling the procedure, your program will run a little faster.

If you try to change the value of a const parameter in a function, your program will not compile, as Delphi will treat this as an error in your program.

var parameters

If you want to change the value of a variable passed as a parameter, you can use the var declaration with your parameter. This tells Delphi that the method is allowed to change the value of the passed variable:

out parameters

Out parameters are very similar to var parameters (they are still passed by reference), but out tells Delphi that passed variable does not need to have been set before calling the function.

Returning More Than One Value

If you need to return more than one value from a function, you can do this by using out parameters:

In the example above, the procedure accepts two variables as parameters, and the value of each variable is changed by the procedure, resulting in two values being returned:

The message displayed above would be ‘Joe Bloggs is 50’. This is because the values of both varables were set by the function GetName.