Introduction to Functions
|
|
Like a procedure, a function is an assignment that must be performed to complete a program. Unlike a procedure, a function must return a value. Based on this, the most fundamental syntax of a function is: |
function FunctionName : ReturnType;
begin
end;
The function keyword is required to let the compiler know that you are creating a Pascal function. The function keyword must be followed by a name for the function. The name follows the same conventions applied to other Object Pascal objects and we will apply the suggestions reviewed above for a procedure.
You must let the compiler know what type of data the function would return. This is done by typing a colon followed by a valid data type. An example would be: |
Function CalculatePerimeter : Double;
begin
end;
The begin and end keywords are required because they would enclose the assignment performed by the function. Between the begin and end keywords, do whatever the function is supposed to do. After performing the assignment for function, you must specify what value the function is returning. There are two ways you can do this. You can assign the desired result to the name of the function. Here is an example: |
Function AddTwoNumbers : Integer;
begin
AddTwoNumbers := 1250 + 48;
end;
You can also assign the intended result to the Result keyword. Here is an example:
Function AddTwoNumbers : Integer;
begin
Result := 1250 + 48;
end;
As you are in charge of what a function is supposed to do, you have the responsibility of making sure that a function returns the right kind of value as stated by its data type. A function can return: |
function ShowSomeCharacter : char;
begin
Result := 'Z';
end;
|
function Natural : Integer;
begin
Result := 228;
end;
|
function DecimalNumber : Double;
begin
Result := 12.55;
end;
|
function IsMarried : Boolean;
begin
Result := true;
end;
|
function CompleteName : string;
begin
Result := 'I showed you mine. Now show me yours';
end;
|
|
|