Constants
Constants
What is the Constant?
- A constant is a value that does not change throughout the program execution.
- COBOL does not have any system-defined standards for constants except figurative constants.
- Using the VALUE clause, the programmer can declare a variable with an initial value. If the variable value doesn't change during the program's execution, the variable is considered a constant variable, and the value is considered a constant value.
Syntax -
level-number constant-variable
PIC data-type-character(constant-length)
VALUE constant-value.
For example - Declaring a variable to store a value 3.14 (PI value).
01 WS-PI PIC 9(2)V9(2) VALUE 3.14.
- level-number - Specifies the level number of the declaration from 01 to 49. From above example, it is 01.
- constant-variable - Specifies the name of the constant. From above example, it is WS-PI.
- data-type-character - Specifies the type of the variable. From above example, it is 9.
- constant-length - Specifies the variable length to store the data. From above example, it is 04.
- constant-value - Specifies the constant value. From above example, it is 3.14.
Types -
Constants are three types, and those are –
- Numeric constants – Numeric variables having only one value throughout the program execution are called numeric constants. For example - 01 WS-PI PIC 9(2)V9(2) VALUE 3.14.
- Alphanumeric or non-numeric constants – Alphanumeric variables that have only one value throughout the program execution are called as alphanumeric constants. For example - 01 WS-HI PIC X(05) VALUE "HI".
- Figurative Constants - System-defined constants predefined in COBOL are used as replacements for standard values like SPACES, ZEROES, etc. For example - 01 WS-VAR PIC 9(5) VALUE ZEROES.
For example -
01 A PIC X(10) VALUE "MAINFRAMES".
01 B.
02 C PIC 9(3) VALUE 255.
02 D PIC 9(3) VALUE ZEROES.
In the above example, A is a non-numeric constant variable, C is a numeric constant variable, and D is a figurative constant variable.
Practical Example -
Scenario - Example to describe how the constants are used in COBOL programming.
Code -
----+----1----+----2----+----3----+----4----+----5----+
...
WORKING-STORAGE SECTION.
01 WS-VAR.
05 WS-PI PIC 9V99 VALUE 3.14.
05 WS-RADIUS PIC 9(2).
05 WS-AREA PIC 9(3).9(2) VALUE ZEROES.
...
PROCEDURE DIVISION.
MOVE 5 TO WS-RADIUS.
COMPUTE WS-AREA = WS-PI * WS-RADIUS * WS-RADIUS
DISPLAY "AREA OF CIRCLE: " WS-AREA.
...
Output -
AREA OF CIRCLE: 078.50
Explaining Example -
In the above example:
- 3.14 value is not changed in the vriable WS-PI through out the program execution. So the WS-PI is called as constant variable and 3.14 is called as constant value.