Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal

What are forward declared functions in Pascal?

Amaaz Ahmad

A forward declared function is a function whose declaration is not immediately followed by its implementation. It can be declared using the forward keyword, and then we can provide its implementation later on in the same module.

A forward declared function can be called as if it has been implemented completely.

Syntax

function functionName(parameterList): returnType; forward;

In the above snippet of code, functionName is replaced by the function’s name. parameterList is replaced by the parameters and their types. returnType is replaced by the data type which the function will return (if any). Then the forward keyword is written.

Examples

Let’s consider two examples to understand forward declared functions better:

Program Maximum_Minimum_Number(output);

var 
    res: integer;

function max(num1, num2: integer): integer; forward;

function min(num1, num2: integer): integer;
var
   result: integer;

begin
   if (num1 > num2) then
      result := num2
   else
      result := num1;
   min := result;
end;


function max(num1, num2: integer): integer;
var
   result: integer;

begin
   if (num1 > num2) then
      result := num1
   else
      result := num2;
   max := result;
end;

begin
  res := max(5,10);
  writeln('The maximum number is: ', res);
end.

In the above snippet of code, the max function is declared first, using the forward keyword. Then the min function is declared and implemented. Afterwards, the implementation of the max function is provided. In this case, the declaration of the max function is not immediately followed by its implementation.

In the main program block, the max function is called, and the value returned by it is printed on the screen.

Consider another example with the following snippet of code:

Program OutputLines(output);

procedure fun1() ; forward;

procedure fun2();
begin
    writeln('Inside fun2. Calling fun1()');
    fun1();
end;

procedure fun1();
begin
   writeln('Inside fun1');
end;

begin
    fun2();
end.

In the above snippet of code, there are two procedures, named fun1 and fun2.

In Pascal, a function is a sub-program that returns a value after execution, whereas a procedure is a subprogram that does not return a value.

The procedure fun1 is forward declared and then used in the procedure fun2. The implementation of fun1 is provided after it has been used in fun2. Hence, we can conclude that a forward declared function can be used as if it has been implemented completely.

RELATED TAGS

pascal

CONTRIBUTOR

Amaaz Ahmad
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring