CALL Using by Reference Example


Scenario - Dynamic Call passing parameters using call by reference from MAINPROG to SUBPROG.

MAINPROG -

----+----1----+----2----+----3----+----4----+----5----+
       IDENTIFICATION DIVISION.
       PROGRAM-ID. MAINPRCR.
       AUTHOR. MTH.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-VAR.
          05 WS-A        PIC 9(02) VALUE 10.
          05 WS-B        PIC 9(02) VALUE 20.
          05 WS-RESULT   PIC 9(03) VALUE ZEROES.
          05 WS-PROG     PIC X(08) VALUE "SUBPRCR".

       PROCEDURE DIVISION.
           DISPLAY "INPUTS  : " WS-A " " WS-B.
           CALL WS-PROG  USING BY REFERENCE
                         WS-A, WS-B RETURNING WS-RESULT.
           DISPLAY "INPUTS AFTER CALL: " WS-A " " WS-B.
           DISPLAY "RESULT IS:  " WS-RESULT.
           STOP RUN.

SUBPROG -

----+----1----+----2----+----3----+----4----+----5----+
       IDENTIFICATION DIVISION.
       PROGRAM-ID. SUBPRCR.
       AUTHOR. MTH.

       DATA DIVISION.
       LINKAGE SECTION.
       01 LS-INP1       PIC 9(02).
       01 LS-INP2       PIC 9(02).
       01 LS-RESULT     PIC 9(03) VALUE ZEROES.
 
       PROCEDURE DIVISION USING LS-INP1, LS-INP2
                                RETURNING LS-RESULT.
           COMPUTE LS-RESULT = LS-INP1 + LS-INP2
           COMPUTE LS-INP1 = LS-INP1 + 20.
           GOBACK.

JCL -

//MATEPKRJ JOB MSGLEVEL=(1,1),NOTIFY=&SYSUID     
//***********************************************
//*  RUN A COBOL PROGRAM 
//***********************************************
//STEP01  EXEC PGM=MAINPRCR                      
//STEPLIB  DD  DSN=MATEPK.COBOL.LOADLIB,DISP=SHR
//SYSOUT   DD  SYSOUT=*

Output -

INPUTS  : 10 20
INPUTS AFTER CALL: 30 20
RESULT IS:  030

Explaining Example -

In the above example:

  • MAINPRCR is the main program, and SUBPRCR is the subprogram.
  • CALL WS-PROG makes the call as dynamic call.
  • WS-INP1 and WS-INP2 are the inputs passed from MAINPRCR to the SUBPRCR using BY REFERENCE.
  • SUBPRCR receives the data into LS-INP1 and LS-INP2 from MAINPRCR, adds those values, places the result into WS-RESULT.
  • SUBPRCR adds 20 to the LS-INP1 and returns the control to the main program.
  • WS-INP1 value is affected according to the changes made by SUBPRCR, and the reflected value is 30.
Note! CALL..BY REFERENCE, passes the address of the variable to a sub-program, and any value changes made by the sub-program are reflected in the main program.