Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Subprograms

User-Defined Functions and Recursion

Learn COBOL user-defined functions with FUNCTION-ID and REPOSITORY, recursive programs with LOCAL-STORAGE, intrinsic function calls, and how to write a factorial and tree walk safely.

You already know that CALL runs another program and that parameters travel by reference, content or value (CALL and the Linkage Section). COBOL has two more ways to structure code that most beginners never see: user-defined functions, which you use inside expressions exactly like the built-in FUNCTION LENGTH, and recursive programs, which call themselves. Both are part of COBOL 2002 and later and are supported by current compilers, including GnuCOBOL and IBM Enterprise COBOL for z/OS 6.x.

Built-in functions: a reminder

An intrinsic function returns a value and is used wherever an expression or a data item of that type is allowed:

COBOL
           COMPUTE WS-ROOT = FUNCTION SQRT (WS-AREA)
           MOVE FUNCTION UPPER-CASE (WS-NAME) TO WS-NAME-UC
           DISPLAY FUNCTION CURRENT-DATE (1:8)

User-defined functions work in the same places, which makes calling code read naturally and keeps CALL ... USING for procedures with side effects.

Writing a user-defined function

A function is a separate compilation unit that starts with FUNCTION-ID instead of PROGRAM-ID and ends with END FUNCTION. It receives parameters with USING and returns a value with RETURNING:

COBOL
       IDENTIFICATION DIVISION.
       FUNCTION-ID. CELSIUS-TO-F.
       DATA DIVISION.
       LINKAGE SECTION.
       01  LK-C    PIC S9(3)V9.
       01  LK-F    PIC S9(3)V9.
       PROCEDURE DIVISION USING LK-C RETURNING LK-F.
           COMPUTE LK-F ROUNDED = LK-C * 9 / 5 + 32
           GOBACK.
       END FUNCTION CELSIUS-TO-F.

To use it, a program must tell the compiler the function exists in the REPOSITORY paragraph of the Environment Division:

COBOL
       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       REPOSITORY.
           FUNCTION CELSIUS-TO-F.
       ...
           COMPUTE WS-TEMP-F = FUNCTION CELSIUS-TO-F (WS-TEMP-C)

With the repository entry, calls look like built-ins. The compiler checks that the argument and result types fit. Practical points:

  • Parameters in functions are by value in effect: the function cannot change the caller's data.
  • A function may have only one returned item. For several results use a CALL with BY REFERENCE parameters.
  • The function can be in its own source file compiled separately; the repository line names it.
  • Functions are not available in very old compilers (COBOL-74/85 only). If you must support those, use a subprogram.

Recursive programs

A recursive program calls itself, directly or through other programs. The classic example is the factorial: n! = n x (n - 1)!, with 0! = 1. Standard COBOL requires two things:

  1. The program says IS RECURSIVE in PROGRAM-ID.
  2. Data that must be fresh for each invocation lives in LOCAL-STORAGE, not WORKING-STORAGE.
COBOL
       IDENTIFICATION DIVISION.
       PROGRAM-ID. FACT IS RECURSIVE.
       DATA DIVISION.
       LOCAL-STORAGE SECTION.
       01  LS-N-1      PIC 9(3).
       01  LS-SUB      PIC 9(18).
       LINKAGE SECTION.
       01  LK-N        PIC 9(3).
       01  LK-RESULT   PIC 9(18).
       PROCEDURE DIVISION USING LK-N LK-RESULT.
       MAIN.
           IF LK-N <= 1
               MOVE 1 TO LK-RESULT
           ELSE
               COMPUTE LS-N-1 = LK-N - 1
               CALL "FACT" USING BY CONTENT LS-N-1
                                 BY REFERENCE LS-SUB
               COMPUTE LK-RESULT = LK-N * LS-SUB
           END-IF
           GOBACK.
       END PROGRAM FACT.

Each call to FACT gets its own copies of LS-N-1 and LS-SUB; they are allocated at entry and freed at exit. WORKING-STORAGE exists once per program, so a recursive call would overwrite it and the caller would lose its values when the call returned.

flowchart TD
    A["FACT n=4"] --> B["FACT n=3"]
    B --> C["FACT n=2"]
    C --> D["FACT n=1: returns 1"]
    D -->|"2 x 1 = 2"| C
    C -->|"3 x 2 = 6"| B
    B -->|"4 x 6 = 24"| A

Each level has its own LOCAL-STORAGE; results flow back up as the calls return.

Choosing storage sections

Section Created Value kept between calls Use
WORKING-STORAGE Once, on the first call Yes (unless INITIAL) Constants, counters, loaded tables
LOCAL-STORAGE At every entry No, freed at GOBACK Recursive programs, re-entrant code
LINKAGE Not allocated, maps the caller's data Belongs to the caller Parameters

LOCAL-STORAGE items may have VALUE clauses, which are applied on each entry. Large local tables cost time on every call, so keep recursive frames small.

Limits of recursion

COBOL compilers allocate local storage on a stack or heap, and deep recursion can run out of it. Typical business uses of recursion are modest: bill-of-materials explosions, directory-like hierarchies (a parent code in each record), and parsers. For plain counting problems, loops are simpler and faster:

COBOL
           MOVE 1 TO WS-RESULT
           PERFORM VARYING I FROM 2 BY 1 UNTIL I > N
               COMPUTE WS-RESULT = WS-RESULT * I
           END-PERFORM

Note too that PERFORM of a paragraph is not recursive in the same way: a paragraph that performs itself (even indirectly) gives undefined results, because there is no stack of return addresses for it in the standard. If you need recursion, make it a recursive program.

You also have to watch the size of results. A PIC 9(18) holds up to 18 digits, so FACT works up to 19!, which is 121,645,100,408,832,000 (18 digits); 20! has 19 digits and overflows. Add ON SIZE ERROR to the COMPUTE to catch overflow.

Modelling recursion

These Python stand-ins show what the two storage sections mean. The first keeps a shared counter (like WORKING-STORAGE, one per program) and a per-call variable (like LOCAL-STORAGE). The second shows the same recursive hierarchy walk that a bill-of-materials program performs.

Python Stand-in: recursive FACT with per-call frames and a shared counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: bill-of-materials explosion (recursive walk of a hierarchy)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first block prints the enter/leave trace and 24, then calls made: 4. The second block prints the tree with cumulative quantities: for example SPOKE x72 under two wheels.

Common mistakes

  1. Recursion without IS RECURSIVE: the second entry is a run-time error or corrupts storage.
  2. Using WORKING-STORAGE for variables that must be per-call.
  3. No base case, giving endless recursion until the stack overflows.
  4. Missing the REPOSITORY entry for a user-defined function, so the compiler treats the name as an unknown data item.
  5. Expecting a function to modify its arguments.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which header marks a user-defined function?

    A user-defined function starts with FUNCTION-ID and ends with END FUNCTION name.
  2. 2. Where should per-invocation variables of a recursive program live?

    LOCAL-STORAGE is allocated again at each entry, so every level has its own copy.
  3. 3. What must a program declare to allow itself to be called recursively?

    IS RECURSIVE in PROGRAM-ID permits a program to be active more than once at a time.
  4. 4. How does the compiler learn that a user-defined function exists?

    The REPOSITORY paragraph in the Configuration Section names functions (and classes) that the program uses.

Summary

  • A user-defined function (FUNCTION-ID, USING, RETURNING) is used in expressions like an intrinsic one after a REPOSITORY entry.
  • A recursive program needs IS RECURSIVE and uses LOCAL-STORAGE for per-call data.
  • Do not make paragraphs perform themselves; use a recursive program instead.
  • Prefer loops for simple counting; save recursion for hierarchies and parsers, and always code a base case.

Next: The mainframe environment