Arguments |
Top Previous Next |
It is often necessary to send information to a procedure. Values to be sent are separated by commas and placed between parentheses immediately after the procedure call. These values are the arguments of the procedure. When the procedure is called, these arguments are copied into the first local variables of the procedure. Here is an example:
integer A, B, C, Result;
procedure AddTen; \Subroutine integer X, Y, Z; \Arguments begin X:= X + 10; Y:= Y + 10; Z:= Z + 10; Result:= X + Y + Z; end;
begin \Start of the program A:= 1; B:= 2; C:= 3; AddTen(A, B, C); \Procedure call with arguments end;
In this example the second block calls the first. In the process it sends the values of the variables A, B, and C, which are 1, 2, and 3 respectively. When AddTen is called, the values in A, B, and C are copied into X, Y, and Z. The procedure adds 10 to these values, sums them into Result (= 36), and returns. The original A, B, and C are not changed by the procedure call.
XPL0 allows a special comment to be placed after the name of a procedure and before the semicolon in the declaration. This helps the programmer keep track of which variables are arguments and which are normal locals. Use the comment to list the arguments in the order they are sent when the procedure is called.
Here is an example of an argument list as a comment:
procedure Check(Area, Perimeter); integer Area, Perimeter; \Arguments integer Side; \Normal local variable begin Side:= Perimeter / 4; if Side*Side = Area then Text(0, "square") else Text(0, "rectangle"); end;
Writing Area and Perimeter in parenthesis on the first line shows that this procedure has these two values passed to it as arguments, while Side is simply a normal local variable.
Real values can also be passed as arguments. Be sure to declare the local variables in the same order as they are passed. "Real" and "integer" declarations can be mixed in any order to accomplish this.
The ability to pass values to procedures, with the ability to declare in each procedure just those variables it needs, enables each procedure to be a complete and independent piece of code. This enables it to be debugged separately and copied from program to program. |