BudiBadu Logo
Samplebadu

COBOL by Example: Subprograms

COBOL 2002

Structuring applications with external subprograms using CALL statement, passing data by reference with USING clause, implementing modular development with separate compilation, and managing program control flow with EXIT PROGRAM.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. MAIN-PROG.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  NUM-A   PIC 99 VALUE 10.
       01  NUM-B   PIC 99 VALUE 20.
       01  RESULT  PIC 999.
       
       PROCEDURE DIVISION.
           DISPLAY "Calling Subprogram...".
           CALL 'ADD-PROG' USING NUM-A, NUM-B, RESULT.
           DISPLAY "Back in Main. Sum is: " RESULT.
           STOP RUN.

Explanation

For true modularity, COBOL allows programs to CALL other compiled programs. This is different from a Copybook; a subprogram is compiled separately and linked at runtime. This allows for separate development and testing of individual components.

The CALL statement transfers control to the subprogram. You can pass data to it via the USING clause. The subprogram runs, does its work, and returns control to the main program using EXIT PROGRAM or GOBACK.

Data is typically passed by reference, meaning the subprogram operates directly on the memory of the calling program. If the subprogram modifies a parameter, the change is visible to the caller immediately upon return. This is efficient but requires care to avoid unintended side effects.

Code Breakdown

11
CALL 'ADD-PROG'. 'ADD-PROG' is the PROGRAM-ID of the external subprogram.
11
USING NUM-A, NUM-B, RESULT. These variables are passed by reference. If the subprogram modifies them, the changes are reflected here.
12
DISPLAY "Back in Main...". This line runs only after ADD-PROG has finished and returned control.