Structs in COBOL

Our program will demonstrate how to use structs to group data together. Here’s the full source code in Cobol.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. StructExample.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       * Declare the person structure
       01 PERSON.
           05 NAME PIC X(50).
           05 AGE  PIC 99.

       * Declare another person to use as a pointer
       01 NEW-PERSON.
           05 NAME PIC X(50).
           05 AGE  PIC 99.

       PROCEDURE DIVISION.
       BEGIN.
           * Create a new person record
           MOVE "Bob" TO NAME OF PERSON
           MOVE 20 TO AGE OF PERSON
           DISPLAY "{" NAME OF PERSON " " AGE OF PERSON "}"

           * Initialize struct fields by name
           MOVE "Alice" TO NAME OF PERSON
           MOVE 30 TO AGE OF PERSON
           DISPLAY "{" NAME OF PERSON " " AGE OF PERSON "}"

           * Omitted fields will be zero-valued
           MOVE "Fred" TO NAME OF PERSON
           MOVE 0 TO AGE OF PERSON
           DISPLAY "{" NAME OF PERSON " " AGE OF PERSON "}"

           * Using pointers to structs
           MOVE "Ann" TO NAME OF NEW-PERSON
           MOVE 40 TO AGE OF NEW-PERSON
           DISPLAY "{" NAME OF NEW-PERSON " " AGE OF NEW-PERSON "}"

           * Using a constructor function
           PERFORM NEW-PERSON-FUNCTION

           * Access struct fields with a dot
           MOVE "Sean" TO NAME OF PERSON
           MOVE 50 TO AGE OF PERSON
           DISPLAY NAME OF PERSON

           * Automatically dereferencing pointers
           MOVE "Sean" TO NAME OF NEW-PERSON
           MOVE 50 TO AGE OF NEW-PERSON
           DISPLAY AGE OF NEW-PERSON

           * Structs are mutable
           MOVE 51 TO AGE OF NEW-PERSON
           DISPLAY AGE OF NEW-PERSON

           * Anonymous struct type example
           MOVE "Rex" TO NAME
           MOVE 1 TO AGE
           DISPLAY "{" NAME " " (AGE = 1 "true" ELSE "false") "}"

           STOP RUN.

       NEW-PERSON-FUNCTION.
           MOVE "Jon" TO NAME OF PERSON
           MOVE 42 TO AGE OF PERSON
           DISPLAY "{" NAME OF PERSON " " AGE OF PERSON "}"
           EXIT.

To run the program, compile the code using a Cobol compiler and then execute the generated binary.

$ cobc -x StructExample.cob
$ ./StructExample
{Bob 20}
{Alice 30}
{Fred 0}
{Ann 40}
{Jon 42}
Sean
50
51
{Rex true}

In Cobol, we can use struct-like data grouping to logically organize and manipulate related data. Let’s learn more about handling data structures in Cobol.