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:
Result
variableExit
callNote that different versions and compilers of Pascal might not support some of the above-stated methods.
Result
variableResult
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;beginResult := 5;end;varx : integer;beginx := 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.
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;beginreturnNumber := 5;end;varx : integer;beginx := 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.
Exit
callWe 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;beginExit(5);end;varx : integer;beginx := 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.