Product Site

7.2. Functions and Subroutines

Functions and subroutines are called in the same way. The only difference between functions and subroutines is that functions must return data, whereas subroutines need not.

The following types of routines can be called as functions:
Internal

If the routine name exists as a label in the program, the current processing status is saved for a later return to the point of invocation to resume execution. Control is then passed to the first label in the program that matches the name. As with a routine called by the CALL instruction, status information, such as TRACE and NUMERIC settings, is saved too. See the CALL instruction for details.

If you call an internal routine as a function, you must specify an expression in any RETURN instruction so that the routine can return. This is not necessary if it is called as a subroutine.
Example 7.1. Recursive internal function execution
arg x
say x"! =" factorial(x)
exit
factorial: procedure   /* Calculate factorial by    */
  arg n                /*   recursive invocation.   */
  if n=0 then return 1
  return  factorial(n-1) * n

FACTORIAL is unusual in that it calls itself (this is recursive invocation). The PROCEDURE instruction ensures that a new variable n is created for each invocation.
Built-in

These functions are always available and are defined in Section 7.4, “Built-in Functions”.
External

You can write or use functions that are external to your program and to the language processor. An external routine can be written in any language, including Rexx, that supports the system-dependent interfaces the language processor uses to call it. You can call a Rexx program as a function and, in this case, pass more than one argument string. The ARG, PARSE ARG, or USE ARG instruction or the ARG built-in function can retrieve these argument strings. When called as a function, a program must return data to the caller.

Notes:
  1. Calling an external Rexx program as a function is similar to calling an internal routine. For an external routine, however, the caller's variables are hidden. To leave the called Rexx program, you can use either EXIT or RETURN. In either case, you must specify an expression.
  2. You can use the INTERPRET instruction to process a function with a variable function name. However, avoid this if possible because it reduces the clarity of the program.