SYNCHRONIZED Clause
COBOL allocates contiguous memory locations for variables to save them for other storage purposes. In all scenarios, the variable's memory allocation starts from the respective boundaries (means byte boundaries) to increase the computation efficiency of the program.
While allocating elements at the boundaries, there might be some unused bytes between the boundary start and the previous allocation ending. These unused bytes are called as Slack bytes.
The SYNCHRONIZED clause is used to allocate the variables at their respective natural memory boundaries (immediately after the previous allocation ends). It specifies the alignment of an elementary item on a natural boundary and removes the slack bytes.
Syntax -
data-item PIC data-type(length) [SYNCHRONIZED|SYNC [LEFT|RIGHT]]
Parameters -
- data-item - Name of the data item being defined.
- PIC data-type(length) - Picture clause that describes the type and size of the data item.
- LEFT - Optional. It specifies left alignment. It is typically used for alphanumeric items.
- RIGHT - Optional. It specifies right alignment. It is typically used for numeric items. If neither coded, RIGHT is the default.
Slack Bytes -
The memory bytes that are left unused between the memory allocations are called slack bytes. For the binary items that are not on their natural boundaries, the compiler inserts slack bytes within a record to ensure all SYNCHRONIZED items are on their proper boundaries.
There are two types of slack bytes -
- Slack bytes within records
- Slack bytes between records
Slack bytes within records -
Slack bytes (unused character positions) are added before each synchronized item in the records. For Example -
01 STUDENT.
05 STUDENT-NO PIC 9(02).
05 STUDENT-NAME PIC X(12).
05 STUDENT-GRADE PIC 9(02).
05 STUDENT-CLASS PIC X(03).
The compiler inserts the slack bytes after STUDENT-NO to start the next item STUDENT-NAME from the boundary. Similary, for the STUDENT-GRADER to start the STUDENT-CLASS from the boundary. The declaration becomes after slack bytes is -
01 STUDENT.
05 STUDENT-NO PIC 9(02).
[05 SLACK-BYTES PIC XX. INSERTED BY COMPILER]
05 STUDENT-NAME PIC X(12).
05 STUDENT-GRADE PIC 9(02).
[05 SLACK-BYTES PIC XX. INSERTED BY COMPILER]
05 STUDENT-CLASS PIC X(03).
The below diagram represents the memory allocation along with slack bytes -
Total 4 slack bytes inserted if we are not used SYNC clause. To avoid the slack bytes, the layout should be declared with SYNC clause like below -
01 STUDENT.
05 STUDENT-NO PIC 9(02).
05 STUDENT-NAME PIC X(12) SYNC.
05 STUDENT-GRADE PIC 9(02).
05 STUDENT-CLASS PIC X(03) SYNC.
The below diagram represents the same memory allocation along SYNC clause and there will be no slack bytes anymore -