In COBOL, the prime use of the comp variable is for faster calculation and to save memory. Here is a resolution on how to check for spaces or Low-values. It’s tricky but not complex. Remember as general notes while coding, if you have a Comp* variable, you need to check for proper initialization.
COBOL Definition for Comp*
Here I use comp-4 to demonstrate.
01 COUNTERS. 05 WS_COUNT COMP-4. 05 WS_COUNT_X REDEFINES WS_COUNT PIC X(02). 01 MY_DATA PIC 9(04).
I move the comp-4 value to MY_DATA, which is a numeric type. When the input WS_COUNT has valid numeric, you will not face any issue, but if the WS_COUNT has spaces or low-values, junk data populates to MY_DATA. Below is my example to avoid junk data. Useful for COBOL/Mainframe projects.
COBOL MOVE Statement
MOVE WS_COUNT TO MY_DATA.
Resolution to Check for Spaces and Low-Values
IF WS_COUNT_X SPACES or LOW_VALUES MOVE ZEROS TO MY_DATA ELSE MOVE WS_COUNT TO MY_DATA END-IF.
This way, you can avoid populating junk data in the target variable. It applies to all COMP* variables. Check out more on Comp-4, Comp-5 and Comp-6.
- Comp-4 internally takes 2 bytes, So I use 2 bytes in redefines
- Comp-5 internally takes 4 bytes
- Comp-6 internally takes 8 bytes