Working Example
Assuming a button on a form, here's the supporting code for a quick demo:
unit ParametersUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function Add(a, b : integer) : integer;
begin
Result := a + b;
end;
function AddByRef(var a, b : integer) : integer;
begin
Result := a + b;
end;
function AddByConst(const a, b : integer) : integer;
begin
Result := a + b;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
x, y: Integer;
begin
x := 4;
y := 3;
ShowMessage('by val pass literals 2+2=' + IntToStr(Add(2,2)));
ShowMessage('by val pass vars 4+3=' + IntToStr(Add(x,y)));
//With by reference, you cannot pass literals!
//Does not work...ShowMessage('by ref 4+3=' + IntToStr(AddByRef(2,2));
ShowMessage('by ref pass vars 4+3=' + IntToStr(AddByRef(x,y)));
//With by constant, the compiler optimizes parameters.
ShowMessage('by const pass literals 2+2=' + IntToStr(AddByConst(2,2)));
ShowMessage('by const pass vars 4+3=' + IntToStr(AddByConst(x,y)));
end;
end.
Default Paremeters
Delphi introduced default parameters with Delphi 4. Default parameters is a form of overloading that allows you to specify a default for a parameter which is used when the routine is called without that particular parameter.
For example, the following function demonstrates default parameter overloading. It allows you to add up to four numbers:
function Add(a, b: integer; c:integer=0; d:integer=0): Integer;
begin
Result := a+b+c+d;
end;
To test our new function, add the following code to a button click event:
ShowMessage('2+2=' + IntToStr(Add(2,2)));
ShowMessage('2+2+3=' + IntToStr(Add(2,2,3)));
ShowMessage('2+2+3+4=' + IntToStr(Add(2,2,3,4)));