REDEFINES
REDEFINES
- REDEFINES defines a new variable for the existing variable, which means two variables share the same memory area.
- It is a way to declare multiple variables for a single memory area in different ways based on the requirement.
- The data items involved in a REDEFINES should be at the same level number.
- Redefining the target variable should follow the source item declaration.
Syntax -
level-number target-variable REDEFINES source-variable [PIC ...].
Parameters -
- level-number - The level number at which the variable is defined. It should be the same for both source and target variables.
- target-variable - Name of the new variable that is going to share the storage of source-variable.
- source-variable - Name of the variable whose storage is being redefined by target-variable.
- PIC .. - Optional. Additional clauses that describe the data, like PIC, VALUE, etc.
Rules to remember -
- The source variable can redefine unlimited times without any restrictions.
- The source and target variables should be at the same level.
- We can redefine variables declared with level numbers 01-49 or 77 can be redefined. However, We should not redefine the variables declared with levels 66 or 88.
- We should not redefine variables declared with an OCCURS DEPENDING ON clause.
- PICTURE clause is optional for REDEFINES.
- We can change the data type of the variable the variable.
- Ideally, the source and target variables should have the same length. However, the lengths may differ, and that is acceptable.
- The source or target variables may have elementary variables.
Practical Example -
Scenario - Redefining a variable with same length in COBOL programming.
Code -
----+----1----+----2----+----3----+----4----+----5----+
...
WORKING-STORAGE SECTION.
01 WS-VAR.
05 WS-VAR1 PIC X(20).
05 WS-REQ-VAR1 REDEFINES WS-VAR PIC X(20).
...
PROCEDURE DIVISION.
MOVE "MAINFRAME TECHNOLOGY" TO WS-VAR1.
DISPLAY "WS-VAR1: " WS-VAR1.
DISPLAY "WS-REQ-VAR1: " WS-REQ-VAR1.
DISPLAY " ".
MOVE "MAINFRAME APPLICATION SYSTEM" TO WS-REQ-VAR1.
DISPLAY "WS-VAR1: " WS-VAR1.
DISPLAY "WS-REQ-VAR1: " WS-REQ-VAR1.
...
Output -
WS-VAR1: MAINFRAME TECHNOLOGY WS-REQ-VAR1: MAINFRAME TECHNOLOGY WS-VAR1: MAINFRAME APPLICATIO WS-REQ-VAR1: MAINFRAME APPLICATIO
Note! If data in the source or target variables changes, the data in the other variables automatically changes because both variables point to the exact memory location.