What is function result in Pascal functions?

In Pascal, a function is a subroutine that returns a value. The value that is returned by the function is called the function result.

There are three ways to set the result of a function, depending upon the compiler and the version of Pascal:

  • Using the Result variable
  • Using the name of the function
  • Using the Exit call

Note that different versions and compilers of Pascal might not support some of the above-stated methods.

Using the Result variable

Result is a special variable that is automatically declared and accessible inside a function. To return a value from any function, we can assign that value to this variable.

The value of the Result variable at the end of the function is returned from the function.

For example:

Program FunctionResult(output);
function returnNumber : integer;
begin
Result := 5;
end;
var
x : integer;
begin
x := returnNumber();
writeln(x);
end.

In the above snippet of code, a function named returnNumber returns the value 5 by assigning it to the special variable Result in line 5.

In the main block of code, the function is being called, and the value returned by it is being assigned to another variable, x. Then, the value of x is being printed.

Using the name of the function

We can return a value from a function by assigning that value to the name of the function. The name of the function can be accessed as a variable inside the function body.

For example:

Program FunctionResult(output);
function returnNumber : integer;
begin
returnNumber := 5;
end;
var
x : integer;
begin
x := returnNumber();
writeln(x);
end.

In the above snippet of code, a function named returnNumber is returning the value 5 by assigning it to the name of the function in line 5.

The returned value is stored and printed in another variable, x, in the main code block.

Using the Exit call

We can also return a value from the function by using the Exit function call inside the function body. The Exit function call behaves like a return function. It stops the execution of the function and returns the value passed to it.

For example:

Program FunctionResult(output);
function returnNumber : integer;
begin
Exit(5);
end;
var
x : integer;
begin
x := returnNumber();
writeln(x);
end.

In the above snippet of code, the function returnNumber returns the value 5 by calling the Exit. The value to be returned is passed as an argument to the Exit function.

Copyright ©2024 Educative, Inc. All rights reserved