Function Call
|
Once a function exists or is known, such as the above simple
AddTwoNumbers function, you can call it the same way we did with the
above StopHere procedure, by simply typing its name where the function
is needed.
We mentioned that the main difference between a function and a procedure is that a function returns a value. This value can be any of the types of data we reviewed previously but the value must be the type stated by the ReturnType word. Because a function returns a value, it can be “passed’ to a Write or a Writeln procedure to display its return value. For example, the above AddTwoNumbers function can be supplied to a Writeln procedure as follows: |
program Project1; {$APPTYPE CONSOLE} Procedure StopHere; begin write('Press any key to continue...'); readln; end; Function AddTwoNumbers : Integer; begin Result := 1250 + 48; end; begin Writeln(AddTwoNumbers); StopHere end.
This would produce:
|
1298 Press any key to continue...
Because a function returns a value, it can also be assigned to a
variable of the same type. A function can be used only as the right
value in an assignment operation, never to the left of the operator.
Here is an example: |
program Project1; {$APPTYPE CONSOLE} Procedure StopHere; begin write('Press any key to continue...'); readln; end; Function AddTwoNumbers : Integer; begin Result := 1250 + 48; end; var Addition: Integer; begin Addition := AddTwoNumbers; StopHere end.
This means that, once a function has performed its assignment and
returns a value, the function call can be used anywhere its type of
value is needed.
Procedures and functions are sometimes commonly referred to as routines. Therefore, from now on, in this book, the word “routine” will mean “procedure or function”.
Procedures and functions are sometimes commonly referred to as routines. Therefore, from now on, in this book, the word “routine” will mean “procedure or function”.
No comments:
Post a Comment