What are Subroutines and Functions?

Subroutines and functions are routines made up of a sequence of instructions that can receive data, process it, and return a value. The routines can be:

Internal
The routine is within the current program, marked by a label, and only that program uses the routine.
External
A REXX subroutine that exists as a separate file.

In many aspects, subroutines and functions are the same. However, they are different in a few major aspects, such as how to call them and the way they return values.

When to Write Subroutines Rather Than Functions

The actual instructions that make up a subroutine or a function can be identical. It is the way you want to use them in a program that turns them into either a subroutine or a function. For example, you can call the built-in function SUBSTR as either a function or a subroutine. This is how to call SUBSTR as a function to shorten a word to its first eight characters:

a = SUBSTR('verylongword',1,8)        /* a is set to 'verylong' */

You get the same results if you call SUBSTR as a subroutine.

CALL SUBSTR 'verylongword', 1, 8
a = RESULT                            /* a is set to 'verylong' */

When deciding whether to write a subroutine or a function, ask yourself the following questions:

The rest of this chapter describes how to write subroutines and functions and finally summarizes the differences and similarities between the two.