Pointers in COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. POINTERS-EXAMPLE.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-I PIC 9(5) VALUE 1.
       01 WS-PTR POINTER.
       
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           DISPLAY "initial: " WS-I
           
           CALL 'ZEROVAL' USING WS-I
           DISPLAY "zeroval: " WS-I
           
           SET WS-PTR TO ADDRESS OF WS-I
           CALL 'ZEROPTR' USING WS-PTR
           DISPLAY "zeroptr: " WS-I
           
           DISPLAY "pointer: " WS-PTR
           
           STOP RUN.

       ZEROVAL.
       LINKAGE SECTION.
       01 LS-VAL PIC 9(5).
       PROCEDURE DIVISION USING LS-VAL.
           MOVE 0 TO LS-VAL.
       
       ZEROPTR.
       LINKAGE SECTION.
       01 LS-PTR POINTER.
       01 LS-VAL PIC 9(5) BASED.
       PROCEDURE DIVISION USING LS-PTR.
           SET ADDRESS OF LS-VAL TO LS-PTR
           MOVE 0 TO LS-VAL.

COBOL supports a concept similar to pointers through the use of the POINTER data type and the SET ADDRESS OF statement. This example demonstrates how to work with pointers in COBOL, contrasting it with value-based operations.

We’ll show how pointers work in contrast to values with two subprograms: ZEROVAL and ZEROPTR. ZEROVAL has a PIC 9(5) parameter, so arguments will be passed to it by value. ZEROVAL will get a copy of LS-VAL distinct from the one in the calling procedure.

ZEROPTR, in contrast, has a POINTER parameter, meaning that it takes a memory address. The SET ADDRESS OF LS-VAL TO LS-PTR statement in the procedure then allows us to manipulate the value at that address. Assigning a value to LS-VAL changes the value at the referenced address.

In the main procedure, we:

  1. Initialize WS-I with the value 1 and display it.
  2. Call ZEROVAL with WS-I. This doesn’t change the value of WS-I in the main procedure.
  3. Set WS-PTR to the address of WS-I using SET WS-PTR TO ADDRESS OF WS-I.
  4. Call ZEROPTR with WS-PTR. This changes the value of WS-I to 0.
  5. Display the final value of WS-I and the pointer value.

The ZEROVAL subprogram doesn’t change the WS-I in the main procedure, but ZEROPTR does because it has a reference to the memory address for that variable.

When you run this program, you should see output similar to:

initial: 00001
zeroval: 00001
zeroptr: 00000
pointer: 0000000000000000

Note that the exact format of the pointer value may vary depending on your COBOL implementation and system architecture.

COBOL’s approach to pointers is different from many modern languages, reflecting its origins in business computing. While not as flexible as pointers in languages like C, COBOL’s pointer mechanism still allows for some degree of indirect memory access and manipulation.