COBOL Subprograms: Procedures and Functions

May 7, 2024

Subprograms, such as procedures and functions, allow for modular programming in COBOL. This lesson explores how to define and use subprograms to enhance code reusability and maintainability.

Defining Procedures in COBOL

In COBOL, procedures are defined using the PROCEDURE DIVISION header. Procedures are used to encapsulate a specific set of actions or logic that can be called from other parts of the program. Here’s an example of a simple procedure in COBOL:

PROCEDURE DIVISION.
    DISPLAY 'Hello, World!'.
    EXIT.

Calling Procedures

To call a procedure in COBOL, you use the PERFORM statement followed by the name of the procedure. For example:

PERFORM MY-PROCEDURE.

Defining Functions in COBOL

Functions in COBOL are similar to procedures but can return a value. You define functions using the FUNCTION keyword. Here’s an example of a function that calculates the square of a number:

MY-FUNCTION FUNCTION.
    MULTIPLY NUM BY NUM GIVING RESULT.
    EXIT FUNCTION RESULT.

Calling Functions

When calling a function in COBOL, you use the COMPUTE statement to assign the result to a variable. For example:

COMPUTE SQUARE-RESULT = MY-FUNCTION(5).

Subprograms play a crucial role in structuring COBOL programs and promoting code reuse. By encapsulating logic into procedures and functions, you can create more maintainable and modular code.