What are Subroutines and Functions?

Subroutines and functions are routines made up of a sequence of instructions that can receive data, process that data, and return a value. The routines can be:
The routine is within the current exec, marked by a label and used only by that exec.
A program or exec in a member of a partitioned data set that can be called by one or more execs. In order for an exec to call the routine, the exec and the routine must be allocated to a system file, for example SYSEXEC or SYSPROC, or be in the same PDS. For more information about allocating to a system file, see Allocating Data Sets.
In many aspects, subroutines and functions are the same; yet they are different in a few major aspects, such as the way they are called and the way they return values.
  • Calling a subroutine
    To call a subroutine, use the CALL instruction followed by the subroutine name (label or exec member name) and optionally followed by up to 20 arguments separated by commas. The subroutine call is an entire instruction.
    CALL  subroutine_name  argument1, argument2,...

    Issuing a CALL to internal label names for REXX subroutines and functions that are greater than eight characters, may have unintended results. Label names will be truncated to eight characters.

  • Calling a function
    To call a function, use the function name (label or exec member name) immediately followed by parentheses that can contain arguments. There can be no space between the function name and the parentheses. The function call is part of an instruction, for example, an assignment instruction.
    x = function(argument1, argument2,...)
  • Returning a value from a subroutine
    A subroutine does not have to return a value, but when it does, it sends back the value with the RETURN instruction.
    RETURN value
    The calling exec receives the value in the REXX special variable named RESULT.
    SAY 'The answer is' RESULT
  • Returning a value from a function
    A function must return a value. When the function is a REXX exec, the value is returned with either the RETURN or EXIT instruction.
    RETURN value
    The calling exec receives the value at the function call. The value replaces the function call, so that in the following example, x = value.
    x = function(argument1, argument2,...)