Basic Pascal Tutorial/Chapter 4/Functions

From Lazarus wiki
Revision as of 17:41, 5 January 2010 by Kees (talk | contribs)
Jump to navigationJump to search

4C - Functions (author: Tao Yue, state: unchanged)

Functions work the same way as procedures, but they always return a single value to the main program through its own name: <delphi> function Name (parameter_list) : return_type; </delphi>

Functions are called in the main program by using them in expressions: <delphi> a := Name (5) + 3; </delphi>

If your function has no argument, be careful not to use the name of the function on the right side of any equation inside the function. That is: <delphi> function Name : integer; begin

 Name := 2;
 Name := Name + 1

end. </delphi> is a no-no. Instead of returning the value 3, as might be expected, this sets up an infinite recursive loop. Name will call Name, which will call Name, which will call Name, etc.

The return value is set by assigning a value to the function identifier. <delphi> Name := 5; </delphi>

It is generally bad programming form to make use of VAR parameters in functions -- functions should return only one value. You certainly don't want the sin function to change your pi radians to 0 radians because they're equivalent -- you just want the answer 0.

previous contents next