BudiBadu Logo
Samplebadu

COBOL by Example: Literals

COBOL 2002

Understanding numeric literals as constant number values and non-numeric string literals enclosed in quotes written directly in code, working with figurative constants like ZERO, SPACES, HIGH-VALUE, and LOW-VALUE as special reserved words representing specific values, improving code readability by using meaningful constant names instead of hardcoded values, and leveraging figurative constants that automatically expand to fill target field sizes.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. LITERALS.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  NUM-VAL     PIC 99.
       
       PROCEDURE DIVISION.
           MOVE 42 TO NUM-VAL.          *> Numeric Literal
           DISPLAY "Value is " NUM-VAL. *> String Literal
           MOVE ZERO TO NUM-VAL.        *> Figurative Constant
           DISPLAY "Zeroed: " NUM-VAL.
           STOP RUN.

Explanation

Literals are constant values written directly into your code. Numeric literals are numbers like 42 or -12.5. Non-numeric (string) literals are enclosed in quotes, like "Hello". The maximum length of a non-numeric literal is 160 characters in standard COBOL.

COBOL also provides a unique feature called Figurative Constants. These are reserved words that represent specific values. ZERO (or ZEROS) represents the numeric value 0 or a sequence of0 characters. SPACE (or SPACES) represents one or more blank spaces. HIGH-VALUE represents the highest possible character value in the system's collation sequence (often used for file processing logic).

Using figurative constants improves code readability. This code example demonstrates that writing MOVE ZERO TO COUNT is clearer than MOVE 0 TO COUNT, and MOVE SPACES TO NAME-FIELD is much cleaner than moving a quoted string of spaces.

Code Breakdown

9
MOVE 42 TO NUM-VAL. '42' is a numeric literal. It is moved into the variable NUM-VAL.
10
"Value is " is a string literal. It is used here as an argument to the DISPLAY statement.
11
MOVE ZERO TO NUM-VAL. ZERO is a figurative constant. It fills NUM-VAL with the value 0. If NUM-VAL were a string, it would fill it with "000...".
11
Note the comments starting with '*>'. This is the modern inline comment syntax in COBOL 2002+. Older COBOL used an asterisk in column 7.