Procedures, functions, parameters and variable scope
Procedures and functions let you write a piece of code once, give it a name, and use it wherever it is needed. The difference between them, and what parameters and scope mean, come up often.
Procedures and functions
A procedure is a named block of code that does a task. It is run with CALL. A function is a named block of code that returns a single value. It is used inside an expression, such as an assignment or an OUTPUT, and must have RETURNS for its type and a RETURN statement.
PROCEDURE ShowLine(Length : INTEGER)
DECLARE Count : INTEGER
DECLARE Line : STRING
Line <- ""
FOR Count <- 1 TO Length
Line <- Line & "-"
NEXT Count
OUTPUT Line
ENDPROCEDURE
FUNCTION Grade(Mark : INTEGER) RETURNS STRING
IF Mark >= 70 THEN
RETURN "Merit"
ELSE
RETURN "Pass"
ENDIF
ENDFUNCTION
CALL ShowLine(10)
OUTPUT Grade(82)Parameters
A parameter is a value passed into a procedure or function when it is called. In the definition it is listed with its data type, as in Mark : INTEGER. When it is called, a value is supplied for it: Grade(82).
Local and global variables
A local variable is declared inside a procedure or function and can only be used there. It disappears when the routine finishes. A global variable is declared in the main program and can be used anywhere. Local variables are safer: code elsewhere can’t change them by accident, and the same name can be reused in different routines.
Where marks go
- Saying a function “outputs” a value: it returns one to the code that called it.
- Writing a function with no RETURN, or a procedure that tries to return a value.
- Calling a function with CALL, or a procedure inside an expression.
- Leaving out the data type of a parameter or of the value a function returns.
- Using a local variable outside the routine where it was declared.