BudiBadu Logo
Samplebadu

COBOL by Example: EVALUATE

COBOL 2002

Implementing multi-way branching with the EVALUATE statement asmore powerful alternative to nested IF-ELSE chains, matching single or multiple variables against patterns with WHEN clauses, using EVALUATE TRUE pattern for boolean condition evaluation, handling range checking and complex combinations, and implementing default catch-all logic with WHEN OTHER clause.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. EVAL-DEMO.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  GRADE       PIC X VALUE 'B'.
       
       PROCEDURE DIVISION.
           EVALUATE GRADE
               WHEN 'A'
                   DISPLAY "Excellent"
               WHEN 'B'
                   DISPLAY "Good"
               WHEN 'C'
                   DISPLAY "Fair"
               WHEN OTHER
                   DISPLAY "Invalid Grade"
           END-EVALUATE.
           STOP RUN.

Explanation

The EVALUATE statement is COBOL's switch or case statement, but it is significantly more powerful. It can evaluate single variables, multiple variables, expressions, or even boolean conditions (EVALUATE TRUE). It is often used to replace complex "spaghetti logic" formed by nested IF statements.

One common pattern is EVALUATE TRUE, where each WHEN clause contains a conditional expression. The first condition that evaluates to true triggers its associated code block. This is useful for checking ranges of values or complex combinations of conditions.

The WHEN OTHER clause acts as a default catch-all for any values not explicitly handled. It is good practice to always include this to handle unexpected data, ensuring your program doesn't fail silently.

Code Breakdown

9
EVALUATE GRADE. Starts the evaluation block for the variable GRADE.
10
WHEN 'A'. Checks if GRADE equals 'A'. If true, executes the following statements until the next WHEN.
12
WHEN 'B'. Checks if GRADE equals 'B'. Since our variable is 'B', this block will execute.
16
WHEN OTHER. The default case. Executed if GRADE is not 'A', 'B', or 'C'.
18
END-EVALUATE. Terminates the EVALUATE block. Control continues to the next sentence.