Functions in COBOL

Functions are central in COBOL. We’ll learn about functions (also known as paragraphs or sections in COBOL) with a few different examples.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. FUNCTIONS-EXAMPLE.
       
       ENVIRONMENT DIVISION.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-RESULT PIC 9(4).
       
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           PERFORM PLUS-PARAGRAPH
           PERFORM PLUS-PLUS-PARAGRAPH
           STOP RUN.

       PLUS-PARAGRAPH.
           MOVE FUNCTION ADD(1, 2) TO WS-RESULT
           DISPLAY "1+2 = " WS-RESULT.

       PLUS-PLUS-PARAGRAPH.
           MOVE FUNCTION ADD(1, 2, 3) TO WS-RESULT
           DISPLAY "1+2+3 = " WS-RESULT.

In COBOL, functions are typically implemented as paragraphs or sections. Here, we’ve created two paragraphs: PLUS-PARAGRAPH and PLUS-PLUS-PARAGRAPH.

The PLUS-PARAGRAPH takes two integers and returns their sum. In COBOL, we use the FUNCTION ADD to achieve this.

       PLUS-PARAGRAPH.
           MOVE FUNCTION ADD(1, 2) TO WS-RESULT
           DISPLAY "1+2 = " WS-RESULT.

COBOL doesn’t have a concept of return values in the same way as some other languages. Instead, we store the result in a variable (WS-RESULT) and then display it.

The PLUS-PLUS-PARAGRAPH adds three integers:

       PLUS-PLUS-PARAGRAPH.
           MOVE FUNCTION ADD(1, 2, 3) TO WS-RESULT
           DISPLAY "1+2+3 = " WS-RESULT.

In the MAIN-PROCEDURE, we call these paragraphs using the PERFORM statement:

       MAIN-PROCEDURE.
           PERFORM PLUS-PARAGRAPH
           PERFORM PLUS-PLUS-PARAGRAPH
           STOP RUN.

To run this COBOL program, you would typically compile it and then execute the resulting program. The exact commands may vary depending on your COBOL compiler, but it might look something like this:

$ cobc -x functions-example.cob
$ ./functions-example
1+2 = 0003
1+2+3 = 0006

COBOL has several other features for structuring code, including sections and nested programs, which we’ll explore in future examples.