COBOL by Example: EVALUATE
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.

