Switch in COBOL

Our first program will demonstrate the use of Switch statements that express conditionals across many branches.

Here’s a basic switch.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. SwitchExample.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  I      PIC 9 VALUE 2.
       01  NOW    PIC X(20).
       01  T      PIC 9(2).

       PROCEDURE DIVISION.
       MAIN-LOGIC.
           DISPLAY "Write " I " as ".
           EVALUATE I
               WHEN 1
                   DISPLAY "one"
               WHEN 2
                   DISPLAY "two"
               WHEN 3
                   DISPLAY "three"
           END-EVALUATE

           CALL 'CURRENT-DATE' USING CURRENT-DATE-TEXT.
           MOVE FUNCTION CURRENT-DATE(1:8) TO NOW.
           COMPUTE T = FUNCTION INTEGER-OF-DAY
              (FUNCTION CURRENT-DATE (1:8) - FUNCTION DATE-DAYS (1601-01-01)).
           IF T MOD 7 = 6 OR T MOD 7 = 7 THEN
               DISPLAY "It's the weekend"
           ELSE
               DISPLAY "It's a weekday"
           END-IF

           MOVE FUNCTION CURRENT-TIME(1:2) TO T.
           IF T < 12 THEN
               DISPLAY "It's before noon"
           ELSE
               DISPLAY "It's after noon"
           END-IF

           CALL 'type-switch' USING BY VALUE "TRUE", BY VALUE 1, BY VALUE "HEY"
           .
           STOP RUN.

       CURRENT-DATE-TEXT.
       LINKAGE SECTION.
       COPY 'IGZDT3'.
       PROCEDURE DIVISION USING CURRENT-DATE.

       type-switch.
           LINKAGE SECTION.
           01 i              PIC 9.
           01 x              PIC X.

           PROCEDURE DIVISION USING BY VALUE x.
               EVALUATE TRUE
                   WHEN FUNCTION IS-NUMERIC (x)
                       DISPLAY "I'm an int"
                   WHEN x = 'TRUE'
                       DISPLAY "I'm a bool"
                   WHEN OTHER
                       DISPLAY "Don't know type ", x
               END-EVALUATE
               .

To run the program, compile it using a COBOL compiler and then execute the binary.

$ cobc -x -free switch_example.cob
$ ./switch_example
Write 2 as two
It's a weekday
It's after noon
I'm an int
I'm a bool
Don't know type hey

Now that we can run and build basic COBOL programs, let’s learn more about the language.