Pointers in COBOL
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:
- Initialize
WS-I
with the value 1 and display it. - Call
ZEROVAL
withWS-I
. This doesn’t change the value ofWS-I
in the main procedure. - Set
WS-PTR
to the address ofWS-I
usingSET WS-PTR TO ADDRESS OF WS-I
. - Call
ZEROPTR
withWS-PTR
. This changes the value ofWS-I
to 0. - 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:
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.