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.
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.
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:
In the MAIN-PROCEDURE
, we call these paragraphs using the PERFORM
statement:
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:
COBOL has several other features for structuring code, including sections and nested programs, which we’ll explore in future examples.