BudiBadu Logo
Samplebadu

COBOL by Example: Parameters

COBOL 2002

Receiving parameters in subprograms using LINKAGE SECTION for shared memory, matching PROCEDURE DIVISION USING signature with caller, preventing memory corruption with correct type matching, and using EXIT PROGRAM to return control.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. ADD-PROG.
       
       DATA DIVISION.
       LINKAGE SECTION.
       01  L-NUM1  PIC 99.
       01  L-NUM2  PIC 99.
       01  L-SUM   PIC 999.
       
       PROCEDURE DIVISION USING L-NUM1, L-NUM2, L-SUM.
           COMPUTE L-SUM = L-NUM1 + L-NUM2.
           EXIT PROGRAM.

Explanation

When writing a subprogram that receives data, you must use the LINKAGE SECTION in the Data Division. This section defines the memory layout of the data passed from the calling program. The variables here do not allocate new memory; they point to the memory of the caller.

The PROCEDURE DIVISION USING... header lists the variables from the Linkage Section that correspond to the arguments passed in the CALL statement. The order must match exactly. If the types or lengths do not match, you may get runtime errors or memory corruption.

It is good practice to define the Linkage Section variables in a copybook shared by both the calling program and the subprogram. This ensures that both sides agree on the data structure, reducing the risk of interface mismatches.

Code Breakdown

5
LINKAGE SECTION. Special section for parameters. Variables here are "linked" to the caller's memory.
9
PROCEDURE DIVISION USING... This signature defines the interface of the subprogram.
11
EXIT PROGRAM. Returns control to the caller. STOP RUN would terminate the entire application!
10
COMPUTE L-SUM = L-NUM1 + L-NUM2. The calculation uses the linked memory directly.