0% found this document useful (0 votes)
35 views641 pages

COBOL Set For AIX Programming Guide

Uploaded by

skorlipa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views641 pages

COBOL Set For AIX Programming Guide

Uploaded by

skorlipa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 641

COBOL Set for AIX IBM

Programming Guide
Release 1

SC26-8423-03
COBOL Set for AIX IBM
Programming Guide
Release 1

SC26-8423-03
Note!

Before using this information and the product it supports, be sure to read the general infor-
mation under “Notices” on page xvii.

Sixth Edition (April 1998)

This edition applies to Version 1, Release 1, Modification 1 of IBM COBOL Set for AIX (program number 5765-548)
and to all subsequent releases and modifications until otherwise indicated in new editions.

Order publications through your IBM representative or the IBM branch office serving your locality. Publications are not
stocked at the address given below.

A form for reader's comments appears at the back of this publication. If the form has been removed, address your
comments to:
IBM Corporation, W92/H3
P.O. Box 49023
San Jose, CA 95161-9023
U.S.A.

When you send information to IBM, you grant IBM a non-exclusive right to use or distribute the information in any way
it believes appropriate without incurring any obligation to you.

 Copyright International Business Machines Corporation 1996, 1998. All rights reserved.
Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication or disclosure is
subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.
Contents
Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Programming Interface Information . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviii

About This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix


How This Book Will Help You . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Abbreviated Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx
Syntax Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx
How Examples Are Shown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

Summary of Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii


Major Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii

Part 1. Coding Your Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 1. Introduction to COBOL Terms . . . . . . . . . . . . . . . . . . . . 2


Variables, Structures, Literals, and Constants . . . . . . . . . . . . . . . . . . . . 2
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Assignment and Terminal Interactions . . . . . . . . . . . . . . . . . . . . . . . . 4
Initializing a Variable (INITIALIZE Statement) . . . . . . . . . . . . . . . . . . . 4
Initializing a Structure (INITIALIZE Statement) . . . . . . . . . . . . . . . . . . 6
Assigning Values to Variables or Structures (MOVE Statement) . . . . . . . . . 7
Assigning Terminal/File Input to Variables (ACCEPT Statement) . . . . . . . . 7
Displaying Data Values on the Terminal/File (DISPLAY Statement) . . . . . . . 8
Assigning Arithmetic Results . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Built-in (Intrinsic) Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Introduction to Intrinsic Functions . . . . . . . . . . . . . . . . . . . . . . . . . 9
Using Function References in Other Contexts . . . . . . . . . . . . . . . . . . 9
Types of Intrinsic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Nesting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Substrings of Function-Identifiers . . . . . . . . . . . . . . . . . . . . . . . . 10
Arguments to Intrinsic Functions . . . . . . . . . . . . . . . . . . . . . . . . 10
Arrays and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Procedure Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Chapter 2. Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . 12


IDENTIFICATION DIVISION . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
PROGRAM-ID Paragraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Avoiding Mismatches Between Names . . . . . . . . . . . . . . . . . . . . . 13
Changing Header of Source Listing . . . . . . . . . . . . . . . . . . . . . . . 13

 Copyright IBM Corp. 1996, 1998 iii


ENVIRONMENT DIVISION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
CONFIGURATION SECTION . . . . . . . . . . . . . . . . . . . . . . . . . . 13
INPUT-OUTPUT SECTION: . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Identifying Files to the Operating System . . . . . . . . . . . . . . . . . . . . 17
DATA DIVISION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Limits in the DATA DIVISION . . . . . . . . . . . . . . . . . . . . . . . . . . 18
FILE SECTION (Using Data in Input/Output Operations) . . . . . . . . . . . . 18
Function and Use of FILE SECTION Entries . . . . . . . . . . . . . . . . . . 19
WORKING-STORAGE SECTION and LOCAL-STORAGE SECTION . . . . . 19
LINKAGE SECTION (Using Data from Another Program) . . . . . . . . . . . 21
PROCEDURE DIVISION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
PROCEDURE DIVISION Headers . . . . . . . . . . . . . . . . . . . . . . . 22
How Logic is Divided in the PROCEDURE DIVISION . . . . . . . . . . . . . 23
Statements Used in the PROCEDURE DIVISION . . . . . . . . . . . . . . . 24
Declaratives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Chapter 3. Numbers and Arithmetic . . . . . . . . . . . . . . . . . . . . . . 29


General COBOL View of Numbers (PICTURE clause) . . . . . . . . . . . . . . 29
Defining Numeric Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Separate Sign Position (for Portability) . . . . . . . . . . . . . . . . . . . . . 29
Extra Positions for Displayable Symbols (Numeric Editing) . . . . . . . . . . . 30
Computational Data Representation (USAGE Clause) . . . . . . . . . . . . . . . 30
External Decimal (USAGE DISPLAY) Items . . . . . . . . . . . . . . . . . . 31
External Floating-Point (USAGE DISPLAY) Items . . . . . . . . . . . . . . . 31
Binary Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Packed Decimal (PACKED-DECIMAL or COMP-3) Items . . . . . . . . . . . 32
Floating-Point (COMP-1 and COMP-2) Items . . . . . . . . . . . . . . . . . . 33
Data Format Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Conversion Takes Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Conversions and Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Sign Representation and Processing . . . . . . . . . . . . . . . . . . . . . . . . 37
Checking for Incompatible Data (Numeric Class Test) . . . . . . . . . . . . . . . 37
How to Do a Numeric Class Test . . . . . . . . . . . . . . . . . . . . . . . . 38
Performing Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
COMPUTE and Other Arithmetic Statements . . . . . . . . . . . . . . . . . . 38
Arithmetic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Numeric Intrinsic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Fixed-Point versus Floating-Point Arithmetic . . . . . . . . . . . . . . . . . . . . 43
Floating-Point Evaluations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Fixed-Point Evaluations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Arithmetic Comparisons (Relation Conditions) . . . . . . . . . . . . . . . . . 44
Examples of Fixed-Point and Floating-Point Evaluations . . . . . . . . . . . . 45

Chapter 4. Handling Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . 46


Defining a Table (OCCURS Clause) . . . . . . . . . . . . . . . . . . . . . . . . 46
One Dimension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Two Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Three Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

iv COBOL Set for AIX Programming Guide


Referring to an Item in a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Subscripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Subscripting Using Index-Names (Indexing) . . . . . . . . . . . . . . . . . . 49
Referring to a Substring of a Table Item . . . . . . . . . . . . . . . . . . . . 51
Putting Values into a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Loading the Table Dynamically . . . . . . . . . . . . . . . . . . . . . . . . . 52
Initializing the Table (INITIALIZE Statement) . . . . . . . . . . . . . . . . . . 52
Assigning Values When You Define the Table (VALUE Clause) . . . . . . . . 52
Creating Variable-Length Tables (DEPENDING ON Clause) . . . . . . . . . . . 56
ODO Object and Subject Contained in Group Item . . . . . . . . . . . . . . . 56
ODO Object outside the Group . . . . . . . . . . . . . . . . . . . . . . . . . 58
Complex OCCURS DEPENDING ON . . . . . . . . . . . . . . . . . . . . . . 59
Searching a Table (SEARCH Statement) . . . . . . . . . . . . . . . . . . . . . 60
Serial Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Binary Search (SEARCH ALL Statement) . . . . . . . . . . . . . . . . . . . 61
Processing Table Items (Intrinsic Functions) . . . . . . . . . . . . . . . . . . . . 62
Processing Multiple Table Items (ALL Subscript) . . . . . . . . . . . . . . . . 62
Efficient Coding for Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Chapter 5. Selection and Iteration . . . . . . . . . . . . . . . . . . . . . . . . 64


Selection (IF and EVALUATE Statements) . . . . . . . . . . . . . . . . . . . . . 64
IF Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
EVALUATE statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Conditional Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Iterative Loops (PERFORM Statement) . . . . . . . . . . . . . . . . . . . . . . 70
Coding a Loop to Be Performed a Definite Number of Times . . . . . . . . . 71
Conditional Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Looping through a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Executing a Group of Paragraphs or Sections . . . . . . . . . . . . . . . . . 72

Chapter 6. String Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 73


Joining Data Items (STRING Statement) . . . . . . . . . . . . . . . . . . . . . . 73
STRING Statement Example . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Splitting Data Items (UNSTRING Statement) . . . . . . . . . . . . . . . . . . . 75
UNSTRING Statement Example . . . . . . . . . . . . . . . . . . . . . . . . 75
Manipulating Null-Terminated Strings . . . . . . . . . . . . . . . . . . . . . . . 78
Referencing Substrings of Data Items (Reference Modifiers) . . . . . . . . . . . 79
Common Reference Modification Mistakes . . . . . . . . . . . . . . . . . . . 80
Benefits of Reference Modification . . . . . . . . . . . . . . . . . . . . . . . 80
Using Arithmetic Expressions as Reference Modifiers . . . . . . . . . . . . . 81
Referencing Substrings of Table Items . . . . . . . . . . . . . . . . . . . . . 82
Tallying and Replacing Data Items (INSPECT Statement) . . . . . . . . . . . . . 82
INSPECT Statement Examples . . . . . . . . . . . . . . . . . . . . . . . . . 82
Converting Data Items (Intrinsic Functions) . . . . . . . . . . . . . . . . . . . . 84
Converting to Uppercase or Lowercase (UPPER-CASE, LOWER-CASE) . . . 84
Converting to Reverse Order (REVERSE) . . . . . . . . . . . . . . . . . . . 84
Converting to Numbers (NUMVAL, NUMVAL-C) . . . . . . . . . . . . . . . . 85
Evaluating Data Items (Intrinsic Functions) . . . . . . . . . . . . . . . . . . . . 86

Contents v
Evaluating Single Characters for Collating Sequence (CHAR, ORD) . . . . . . 86
Finding the Largest or Smallest Data Item (MAX, MIN, ORD-MAX, ORD-MIN) 86
Finding the Length of Data Items (LENGTH) . . . . . . . . . . . . . . . . . . 88
Finding the Date of Compilation (WHEN-COMPILED) . . . . . . . . . . . . . 88

Chapter 7. Processing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 90


File Input/Output Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
File Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
File Access Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
COBOL Coding for Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Accessing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Distributed File Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Coding Input/Output Statements for Files . . . . . . . . . . . . . . . . . . . . 98
File Position Indicator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Reading Records from a File . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Updating Records in a File . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Adding Records to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Replacing Records in a File . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Deleting Records from a File . . . . . . . . . . . . . . . . . . . . . . . . . . 104
File Sorting and Merging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Basics of Sorting and Merging . . . . . . . . . . . . . . . . . . . . . . . . . 105
The SORT Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Coding the Input Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Coding the Output Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Restrictions on Input and Output Procedures . . . . . . . . . . . . . . . . . . 111
The MERGE Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Determining Whether the Sort or Merge Was Successful . . . . . . . . . . . 111
Prematurely Stopping a Sort or Merge Operation . . . . . . . . . . . . . . . 112
SORT Special Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
The STL File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
File Status and the STL File System . . . . . . . . . . . . . . . . . . . . . . 113

Chapter 8. Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116


STRING and UNSTRING Operations . . . . . . . . . . . . . . . . . . . . . . . 116
Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Example of Checking for Division by Zero . . . . . . . . . . . . . . . . . . . 117
Input/Output Error Handling Techniques . . . . . . . . . . . . . . . . . . . . . . 118
End-of-File Phrase (AT END) . . . . . . . . . . . . . . . . . . . . . . . . . . 120
EXCEPTION/ERROR Declarative . . . . . . . . . . . . . . . . . . . . . . . . 120
File Status Key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
File System Return Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
INVALID KEY Phrase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
CALL Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

Part 2. Compiling, Linking, and Running Your Program . . . . . . . . . . . . . 127

Chapter 9. Compiling, Linking, and Running Programs . . . . . . . . . . . . 128

vi COBOL Set for AIX Programming Guide


Setting Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Definitions of COBOL Environment Variables . . . . . . . . . . . . . . . . . . . 129
Compiler Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . 129
Object-Oriented Programming Environment Variables . . . . . . . . . . . . . 130
Run-Time Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . 130
Compiling and Linking Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Options Supported by cob2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Examples using cob2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Modifying the Default Compiler Configuration . . . . . . . . . . . . . . . . . . 139
Alternative Ways to Specify Compiler Options . . . . . . . . . . . . . . . . . 141
Compiler-Detected Errors and Messages . . . . . . . . . . . . . . . . . . . . . 142
Running COBOL Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

Chapter 10. Compiler Options . . . . . . . . . . . . . . . . . . . . . . . . . . 147


Compiler Options Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Default Values for Compiler Options . . . . . . . . . . . . . . . . . . . . . . 148
Performance Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Compiler Option Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
ADATA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
ANALYZE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
APOST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
BINARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
CALLINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
CHAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
COLLSEQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
COMPILE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
CURRENCY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
| DATEPROC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
DYNAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
ENTRYINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
EXIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
FLAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
FLAGSTD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
FLOAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
IDLGEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
LIB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
LINECOUNT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
LIST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
MAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
| MAXMEM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
NUMBER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
OPTIMIZE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
PGMNAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
PROFILE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
QUOTE/APOST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
SEPOBJ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
SEQUENCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
SIZE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

Contents vii
SOURCE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
SPACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
SPILL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
SSRANGE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
TERMINAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
TEST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
THREAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
TRUNC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
TYPECHK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
VBREF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
WORD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
| WSCLEAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
XREF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
| YEARWINDOW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
ZWB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Compiler-Directing Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Chapter 11. Run-Time Options . . . . . . . . . . . . . . . . . . . . . . . . . 193


Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
CHECK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
DEBUG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
ERRCOUNT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
FILESYS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
TRAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
UPSI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

Chapter 12. Debugging Techniques . . . . . . . . . . . . . . . . . . . . . . . 197


Using Source Language to Debug . . . . . . . . . . . . . . . . . . . . . . . . . 197
Tracing Program Logic (DISPLAY Statements) . . . . . . . . . . . . . . . . . 197
Handling Input/Output Errors (USE EXCEPTION/ERROR Declaratives) . . . . 198
Validating Data (Class Test) . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Assessing Switch Problems (INITIALIZE or SET Statements) . . . . . . . . . 198
Improving Program Readability (Explicit Scope Terminators) . . . . . . . . . . 198
Finding Input/Output Errors (File Status Keys) . . . . . . . . . . . . . . . . . 199
Generating Information about Procedures (USE FOR DEBUGGING
Declaratives) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Using Compiler Options for Debugging . . . . . . . . . . . . . . . . . . . . . . 202
The FLAG Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
The NOCOMPILE Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
The SEQUENCE Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
The XREF Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
The MAP Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
The SSRANGE Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
The TEST Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Getting Useful Listing Components . . . . . . . . . . . . . . . . . . . . . . . . . 207
A Short Listing—the Bare Minimum . . . . . . . . . . . . . . . . . . . . . . . 207
A Listing of Your Source Code—for Historical Records . . . . . . . . . . . . 210

viii COBOL Set for AIX Programming Guide


Using Your Own Line Numbers . . . . . . . . . . . . . . . . . . . . . . . . . 210
Data Map Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
A PROCEDURE DIVISION Listing with Assembler Expansion (LIST Output) . 215
A Verb Cross-Reference Listing . . . . . . . . . . . . . . . . . . . . . . . . . 215
A Data-Name, Procedure-Name, and Program-Name Cross-Reference Listing 216
Debugging User Exit Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Debugging Assembler Routines . . . . . . . . . . . . . . . . . . . . . . . . . . 220

Part 3. Object-Oriented Programming Topics . . . . . . . . . . . . . . . . . . . . 221

Chapter 13. Writing Object-Oriented Programs . . . . . . . . . . . . . . . . 222


Writing a Class Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Class IDENTIFICATION DIVISION: Required . . . . . . . . . . . . . . . . . 224
Class ENVIRONMENT DIVISION: Required . . . . . . . . . . . . . . . . . . 224
Class DATA DIVISION: Optional . . . . . . . . . . . . . . . . . . . . . . . . 225
Class PROCEDURE DIVISION: Optional . . . . . . . . . . . . . . . . . . . 226
Complete Class Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Writing a Method Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Method IDENTIFICATION DIVISION: Required . . . . . . . . . . . . . . . . 228
Method ENVIRONMENT DIVISION: Optional . . . . . . . . . . . . . . . . . 229
Method DATA DIVISION: Optional . . . . . . . . . . . . . . . . . . . . . . . 229
Method PROCEDURE DIVISION: Optional . . . . . . . . . . . . . . . . . . 230
Complete Class with Methods Example . . . . . . . . . . . . . . . . . . . . . . 232
Writing a Client Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Client IDENTIFICATION DIVISION: Required . . . . . . . . . . . . . . . . . 238
Client ENVIRONMENT DIVISION: Required . . . . . . . . . . . . . . . . . . 238
Client DATA DIVISION: Optional . . . . . . . . . . . . . . . . . . . . . . . . 238
Client PROCEDURE DIVISION: Optional . . . . . . . . . . . . . . . . . . . . 239
Complete Client Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Writing a Subclass Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Subclass IDENTIFICATION DIVISION: Required . . . . . . . . . . . . . . . 244
Subclass ENVIRONMENT DIVISION: Required . . . . . . . . . . . . . . . . 244
Subclass DATA DIVISION: Optional . . . . . . . . . . . . . . . . . . . . . . 245
Subclass PROCEDURE DIVISION: Optional . . . . . . . . . . . . . . . . . 245
Subclass Method IDENTIFICATION DIVISION: Optional . . . . . . . . . . . . 245
Subclass Method ENVIRONMENT DIVISION: Optional . . . . . . . . . . . . 246
Subclass Method DATA DIVISION: Optional . . . . . . . . . . . . . . . . . . 246
Subclass Method PROCEDURE DIVISION: Optional . . . . . . . . . . . . . . 246
Complete Subclass with Methods Example . . . . . . . . . . . . . . . . . . . . 246
Writing a Metaclass Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Metaclass IDENTIFICATION DIVISION: Required . . . . . . . . . . . . . . . 259
Metaclass ENVIRONMENT DIVISION: Required . . . . . . . . . . . . . . . 259
Metaclass DATA DIVISION: Optional . . . . . . . . . . . . . . . . . . . . . 260
Metaclass PROCEDURE DIVISION: Optional . . . . . . . . . . . . . . . . . 260
Metaclass Method IDENTIFICATION DIVISION: Optional . . . . . . . . . . . 260
Metaclass Method ENVIRONMENT DIVISION: Optional . . . . . . . . . . . . 260
Metaclass Method DATA DIVISION: Optional . . . . . . . . . . . . . . . . . 260
Metaclass Method PROCEDURE DIVISION: Optional . . . . . . . . . . . . . 260

Contents ix
Changes to Class or Subclass Definitions . . . . . . . . . . . . . . . . . . . 261
Changes to the Client Program . . . . . . . . . . . . . . . . . . . . . . . . . 261
Complete Metaclass with Methods Example . . . . . . . . . . . . . . . . . . . . 262

Chapter 14. Using System Object Model (SOM) . . . . . . . . . . . . . . . . 269


SOM Interface Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Accessing the IR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Populating the IR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
SOM Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
System Object Model (SOM) Services . . . . . . . . . . . . . . . . . . . . . . . 271
SOM Methods and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 271
SOM Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Class Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Class Interface Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273

Chapter 15. Using SOM IDL-Based Class Libraries . . . . . . . . . . . . . . 275


SOM Objects—a Refresher . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
SOM IDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Mapping IDL to COBOL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
IDL Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
IDL Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
IDL Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Common IDL Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Complex Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Argument and Return Value Passing Conventions . . . . . . . . . . . . . . . 287
Operation Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Other SOM Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
If You Need to Look at the IDL File . . . . . . . . . . . . . . . . . . . . . . . 302
Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Helper Routines Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 308

Chapter 16. Converting Procedure-Oriented Programs to Object-Oriented


Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Wrapping a Procedure-Oriented Program . . . . . . . . . . . . . . . . . . . . . 310
Glass-top Coordination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Boundary Interface Coordination . . . . . . . . . . . . . . . . . . . . . . . . 311
Required Change to Procedural Code . . . . . . . . . . . . . . . . . . . . . 312
Coexistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Converting a Procedure-Oriented Program . . . . . . . . . . . . . . . . . . . . 312
Identify Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Analyze Data Flow and Usage . . . . . . . . . . . . . . . . . . . . . . . . . 313
Reallocate Code to Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Write the Object-Oriented Code . . . . . . . . . . . . . . . . . . . . . . . . . 314

Part 4. Advanced Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

x COBOL Set for AIX Programming Guide


Chapter 17. Porting Applications between Platforms . . . . . . . . . . . . . 316
Getting Mainframe Applications to Compile under AIX . . . . . . . . . . . . . . . 316
Choosing the Right Compiler Options . . . . . . . . . . . . . . . . . . . . . . 316
AIX Differences from Mainframe COBOL Language Features . . . . . . . . . 316
Using the COPY Statement to Help Port Programs . . . . . . . . . . . . . . 317
Getting Mainframe Applications to Run under AIX . . . . . . . . . . . . . . . . . 317
Data Representations Causing Run-Time Differences . . . . . . . . . . . . . 318
Environment Differences Affecting Portability . . . . . . . . . . . . . . . . . 320
Language Elements Causing Run-Time Differences . . . . . . . . . . . . . . 320
Writing AIX Code to Run on the Mainframe . . . . . . . . . . . . . . . . . . . . 321
Language Features Supported Only by the AIX Compiler . . . . . . . . . . . 321
Compiler Options Supported Only under AIX . . . . . . . . . . . . . . . . . . 321
Names Supported Only under AIX . . . . . . . . . . . . . . . . . . . . . . . 321
Writing Applications That Are Portable between AIX and the PC . . . . . . . . . 322

Chapter 18. Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323


Transferring Control to Another Program . . . . . . . . . . . . . . . . . . . . . . 323
Recursive Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Main Programs and Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . 323
Making Calls between COBOL Programs . . . . . . . . . . . . . . . . . . . . . 324
Structure of Nested Programs . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Static, Dynamic, and Run-time Linking . . . . . . . . . . . . . . . . . . . . . . . 327
CALL identifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
CALL literal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Making Calls between COBOL and C/C++ Programs . . . . . . . . . . . . . . . 328
Rules and Guidelines for ILC Applications . . . . . . . . . . . . . . . . . . . 328
Matching Data and Linkages . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Example - Calling C/C++ Functions from a COBOL Program . . . . . . . . . 330
Example - C Programs That are Called by and Call COBOL Programs . . . . 332
Example - COBOL Program Called by a C Program . . . . . . . . . . . . . . 334
Results of Running COBCALLC . . . . . . . . . . . . . . . . . . . . . . . . . 334

Chapter 19. Data Sharing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336


Passing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Describing Arguments in the Calling Program . . . . . . . . . . . . . . . . . 337
Describing Parameters in the Called Program . . . . . . . . . . . . . . . . . 338
LINKAGE SECTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
PROCEDURE DIVISION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
Grouping Data to Be Passed . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Null-Terminated Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
Using Pointers to Process a Chained List . . . . . . . . . . . . . . . . . . . 340
Using Procedure Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Rules for Using Procedure Pointers . . . . . . . . . . . . . . . . . . . . . . . 344
Passing Return Code Information . . . . . . . . . . . . . . . . . . . . . . . . . 345
RETURN-CODE Special Register . . . . . . . . . . . . . . . . . . . . . . . . 345
PROCEDURE DIVISION RETURNING . . . . . . . . . . . . . . . . . . . . . . 345
CALL . . . RETURNING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Sharing Data Using the EXTERNAL Clause . . . . . . . . . . . . . . . . . . . . 346

Contents xi
Sharing Files between Programs (EXTERNAL Files) . . . . . . . . . . . . . . . 346
Advantages of EXTERNAL Files . . . . . . . . . . . . . . . . . . . . . . . . 346
Example Using EXTERNAL Files . . . . . . . . . . . . . . . . . . . . . . . . 347
Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Without -host Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
With -host Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352

Chapter 20. Programming for a DB2 Environment . . . . . . . . . . . . . . . 354


Compiling with the DB2 Co-Processor . . . . . . . . . . . . . . . . . . . . . . . 354
Options for the DB2 Co-Processor . . . . . . . . . . . . . . . . . . . . . . . . . 354
How Options Are Accumulated . . . . . . . . . . . . . . . . . . . . . . . . . 355
Package and Bind File Names . . . . . . . . . . . . . . . . . . . . . . . . . 355
Ignored Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
SQL INCLUDE Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
COBOL Language Usage with SQL . . . . . . . . . . . . . . . . . . . . . . . . 356
Level of SQL Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Testing the Return Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

Chapter 21. Programming for a CICS Environment . . . . . . . . . . . . . . 358


An Overview of COBOL in a CICS Environment . . . . . . . . . . . . . . . . . . 358
Preparing COBOL Applications to Run under CICS . . . . . . . . . . . . . . . . 359
CICS has a Special Reserved Word Table . . . . . . . . . . . . . . . . . . . 359
Additional Language Restrictions . . . . . . . . . . . . . . . . . . . . . . . . 359
Selecting Compiler Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Selecting Run-Time Options . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Planning for ASCII-EBCDIC Differences . . . . . . . . . . . . . . . . . . . . 361
| System Date under CICS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Dynamic Calls under CICS . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Accessing SFS Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Calls between COBOL and C++ under CICS . . . . . . . . . . . . . . . . . . 363
Object-Oriented COBOL Support Under CICS . . . . . . . . . . . . . . . . . . . 363
Examples of Object-Oriented COBOL Support Under CICS AIX . . . . . . . . 364
Preparing the Examples to Run under CICS AIX . . . . . . . . . . . . . . . . 367
Debugging CICS Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 368

Chapter 22. Open Database Connectivity . . . . . . . . . . . . . . . . . . . 369


Introducing ODBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
ODBC Driver Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Choosing Embedded SQL or ODBC . . . . . . . . . . . . . . . . . . . . . . 370
Using the ODBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
ODBC APIs from COBOL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
CALL Interface Convention . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Using the Supplied Copybooks . . . . . . . . . . . . . . . . . . . . . . . . . 371
Mapping of ODBC C Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Passing a Pointer as an Argument . . . . . . . . . . . . . . . . . . . . . . . 373
Accessing Function Return Values . . . . . . . . . . . . . . . . . . . . . . . 376
Testing Bits with a Bit Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . 376

xii COBOL Set for AIX Programming Guide


| Null-Terminated Character Strings . . . . . . . . . . . . . . . . . . . . . . . 377
Sample Program Using Supplied Copybooks . . . . . . . . . . . . . . . . . . . 377

Chapter 23. Building Shared Libraries . . . . . . . . . . . . . . . . . . . . . 386


Static Linking Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Shared Library Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Terminology Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
How the Linker Resolves References to Shared Libraries . . . . . . . . . . . . . 387
Creating a Shared Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Example of CALL Identifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
COBOL Main Program Using CALL identifier . . . . . . . . . . . . . . . . . . 392
COBOL Main Program Using COBOL and C Shared Libraries . . . . . . . . . 394

Chapter 24. Preparing COBOL Programs for Multithreading . . . . . . . . . 397


How Language Elements Are Interpreted in a Multithreaded Environment . . . . 398
Working with Run-Unit Scoped Elements . . . . . . . . . . . . . . . . . . . . 400
Working with Program Invocation Instance Scoped Elements . . . . . . . . . 400
Choosing THREAD for Multithreading Support . . . . . . . . . . . . . . . . . . . 400
Language Restrictions under THREAD . . . . . . . . . . . . . . . . . . . . . 400
Recursion with Threading . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
Control Transfer within a Multithreaded Environment . . . . . . . . . . . . . . . 401
Limitations on COBOL in a Multithreaded Environment . . . . . . . . . . . . . . 402
Example of Using COBOL in a Multithreaded Environment . . . . . . . . . . . . 402
Sample Code for the Multithreading Example . . . . . . . . . . . . . . . . . 402
Compiling, Linking, and Running the Multithreading Example . . . . . . . . . 405

Chapter 25. National Language Support Considerations . . . . . . . . . . . 407


Locales and Code Sets Supported on AIX . . . . . . . . . . . . . . . . . . . . . 408
DBCS and EUC User-Defined Word Support . . . . . . . . . . . . . . . . . . . 408
Usage Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Restrictions on Specific User-Defined Words . . . . . . . . . . . . . . . . . . 408
DBCS Literal Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
DBCS Data Type Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Declaring DBCS Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
DBCS Class Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Collating Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Intrinsic Functions with Collating Sequence Sensitivity . . . . . . . . . . . . . 412
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Messages Enabled for NLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Cross-Reference Output Sequence . . . . . . . . . . . . . . . . . . . . . . . . 413
Locale Sensitivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413

Chapter 26. Pre-initializing the COBOL Run-Time Environment . . . . . . . 415


Initialize Persistent COBOL Environment . . . . . . . . . . . . . . . . . . . . . 415
Terminate Pre-initialized COBOL Environment . . . . . . . . . . . . . . . . . . . 416
Example of Pre-initializing the COBOL Environment . . . . . . . . . . . . . . . . 417

Chapter 27. Productivity and Tuning Techniques . . . . . . . . . . . . . . . 422

Contents xiii
Simplifying Complex Coding and Other Programming Tasks . . . . . . . . . . . 422
Intrinsic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
Date and Time Callable Services . . . . . . . . . . . . . . . . . . . . . . . . 422
Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
The OPTIMIZE Compiler Option . . . . . . . . . . . . . . . . . . . . . . . . 432
Other Compiler Features that Affect Optimization . . . . . . . . . . . . . . . 433
Compiler Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433

Chapter 28. The "Year 2000" Problem . . . . . . . . . . . . . . . . . . . . . 436


| Date Processing Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Year 2000 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
The Full Field Expansion Solution . . . . . . . . . . . . . . . . . . . . . . . . 437
| The Internal Bridging Solution . . . . . . . . . . . . . . . . . . . . . . . . . . 439
The Century Window Solution . . . . . . . . . . . . . . . . . . . . . . . . . . 440
| The Mixed Field Expansion and Century Window Solution . . . . . . . . . . . 441
The Century Encoding/Compression Solution . . . . . . . . . . . . . . . . . 442
The Integer Format Date Solution . . . . . . . . . . . . . . . . . . . . . . . . 442
| Performance Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
| Performance Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
| How to Get 4-digit Year Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . 444

| Chapter 29. Using the Millennium Language Extensions . . . . . . . . . . . 446


| Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
| Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
| Implementing Date Processing . . . . . . . . . . . . . . . . . . . . . . . . . 447
| Resolving Date-Related Logic Problems . . . . . . . . . . . . . . . . . . . . . . 448
| Basic Remediation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
| Internal Bridging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
| Full Field Expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
| Programming Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
| Date Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
| Arithmetic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
| Other Date Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
| Controlling Date Processing Explicitly . . . . . . . . . . . . . . . . . . . . . . 458
| Eliminating Warning-Level Messages . . . . . . . . . . . . . . . . . . . . . . 460
| Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
| Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
| Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
| Date Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
| Compatible Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
| Treatment of Non-Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463

Appendix A. Summary of Differences with Host COBOL . . . . . . . . . . . 466

Appendix B. System/390 Host Data Type Considerations . . . . . . . . . . 469


CICS Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Date and Time Callable Services . . . . . . . . . . . . . . . . . . . . . . . . 469
Floating Point Overflow Exceptions . . . . . . . . . . . . . . . . . . . . . . . 469

xiv COBOL Set for AIX Programming Guide


DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
MQSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Remote File Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
SORT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470

Appendix C. Intermediate Results and Arithmetic Precision . . . . . . . . . 471


Calculating Precision of Intermediate Results . . . . . . . . . . . . . . . . . . . 471
Fixed-Point Data and Intermediate Results . . . . . . . . . . . . . . . . . . . . 473
Exponentiations Evaluated in Fixed-Point Arithmetic . . . . . . . . . . . . . . 473
Truncated Intermediate Results . . . . . . . . . . . . . . . . . . . . . . . . . 475
Binary Data and Intermediate Results . . . . . . . . . . . . . . . . . . . . . 475
Intrinsic Functions Evaluated in Fixed-Point Arithmetic . . . . . . . . . . . . . 475
Floating-Point Data and Intermediate Results . . . . . . . . . . . . . . . . . . . 477
Exponentiations Evaluated in Floating-Point Arithmetic . . . . . . . . . . . . . 477
Intrinsic Functions Evaluated in Floating-Point Arithmetic . . . . . . . . . . . 477
Arithmetic Expressions in Non-arithmetic Statements . . . . . . . . . . . . . . . 478

Appendix D. Complex OCCURS DEPENDING ON . . . . . . . . . . . . . . . 479


Be Sure to Set Values of ODO Objects . . . . . . . . . . . . . . . . . . . . . . 479
Complex ODO Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
How Length Will be Calculated . . . . . . . . . . . . . . . . . . . . . . . . . 480
Changes in ODO Object Value . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
Changing ODO Object with Complex-ODO Index Names . . . . . . . . . . . 481
Changing ODO Object with Variable Occurrence Table . . . . . . . . . . . . 481

Appendix E. Date and Time Callable Services Reference . . . . . . . . . . . 484


CEECBLDY—Convert Date to COBOL Integer Format . . . . . . . . . . . . . . 484
CEEDATE—Convert Lilian Date to Character Format . . . . . . . . . . . . . . . 488
CEEDATM—Convert Seconds to Character Timestamp . . . . . . . . . . . . . . 493
CEEDAYS—Convert Date to Lilian Format . . . . . . . . . . . . . . . . . . . . 498
CEEDYWK—Calculate Day of Week from Lilian Date . . . . . . . . . . . . . . . 502
CEEGMT—Get Current Greenwich Mean Time . . . . . . . . . . . . . . . . . . 505
CEEGMTO—Get Offset from Greenwich Mean Time to Local Time . . . . . . . 508
CEEISEC—Convert Integers to Seconds . . . . . . . . . . . . . . . . . . . . . 510
CEELOCT—Get Current Local Date or Time . . . . . . . . . . . . . . . . . . . 514
CEEQCEN—Query the Century Window . . . . . . . . . . . . . . . . . . . . . . 516
CEESCEN—Set the Century Window . . . . . . . . . . . . . . . . . . . . . . . 518
CEESECI—Convert Seconds to Integers . . . . . . . . . . . . . . . . . . . . . 521
CEESECS—Convert Timestamp to Seconds . . . . . . . . . . . . . . . . . . . 525
CEEUTC—Get Coordinated Universal Time . . . . . . . . . . . . . . . . . . . . 530
IGZEDT4—Get Current Date . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530

Appendix F. Run-Time Messages . . . . . . . . . . . . . . . . . . . . . . . . 532

Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
COBOL Set for AIX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
Related Publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
COBOL for OS/390 & VM . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562

Contents xv
VisualAge COBOL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
CICS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
SMARTdata Utilities for AIX . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
SOMobjects for AIX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586

xvi COBOL Set for AIX Programming Guide


Notices
References in this publication to IBM products, programs, or services do not imply that
IBM intends to make these available in all countries in which IBM operates. Any refer-
ence to an IBM product, program, or service is not intended to state or imply that only
that IBM product, program, or service may be used. Any functionally equivalent
product, program, or service that does not infringe any of the intellectual property rights
of IBM may be used instead of the IBM product, program, or service. The evaluation
and verification of operation in conjunction with other products, except those expressly
designated by IBM, are the responsibility of the user.

IBM may have patents or pending patent applications covering subject matter in this
document. The furnishing of this document does not give you any license to these
patents. You can send license inquiries, in writing, to the IBM Director of Licensing,
IBM Corporation, 500 Columbus Avenue, Thornwood, NY 10594, U.S.A.

Licensees of this program who wish to have information about it for the purpose of
enabling: (1) the exchange of information between independently created programs and
other programs (including this one) and (2) the mutual use of the information which has
been exchanged, should contact:

IBM Corporation, W92/H3


P.O. Box 49023
San Jose, CA 95161-9023
U.S.A.

Such information may be available, subject to appropriate terms and conditions,


including in some cases, payment of a fee.

Programming Interface Information


This COBOL Set for AIX Programming Guide is intended to help the user create,
compile, link, and run IBM COBOL Set for AIX application programs. This book docu-
ments General-Use Programming Interface and Associated Guidance Information pro-
vided by IBM COBOL Set for AIX.

General-Use programming interfaces allow the customer to write programs that obtain
the services of IBM COBOL Set for AIX.

 Copyright IBM Corp. 1996, 1998 xvii


Trademarks
The following terms are trademarks of the IBM Corporation in the United States or other
countries or both:

AD/Cycle IBM
AIX IMS
AIX/6000 Language Environment
C/370 OS/2
CICS OS/390
CICS OS/2 RS/6000
COBOL/370 System Object Model
DATABASE 2 System/390
DB2 SOMobjects
DFSMS/MVS System/370
DFSORT VisualAge

UNIX is a registered trademark in the United States and other countries licensed exclu-
sively through X/Open Company Limited.

Microsoft, Windows, Windows NT, the Windows 95 logo, and Open Database
Connectivity are trademarks or registered trademarks of Microsoft Corporation.

Other company, product, and service names, which may be denoted by a double
asterisk (**), may be trademarks or service marks of others.

xviii COBOL Set for AIX Programming Guide


About This Book
Welcome to IBM COBOL Set for AIX, IBM's new COBOL development environment for
AIX! IBM COBOL Set for AIX gives you a comprehensive development environment
designed specifically for mission-critical, client/server applications.

IBM COBOL Set for AIX supports local and remote access to DB2, CICS, and VSAM,
giving you access to data and transactions nearly anywhere in your enterprise. And all
the IBM COBOL family of solutions support high subset ANSI 85 COBOL functions, so
your applications can be ported across supported platforms, whether they are running
on a mainframe, an RS/6000, or a personal computer with OS/2.

IBM COBOL Set for AIX supports object-oriented extensions, allowing you to move your
applications to object-orientation at the level and pace you desire.

IBM COBOL Set for AIX provides an integrated development environment, with easy
access to visual tools and project file management. IBM COBOL Set for AIX is fully
integrated with the new industry-standard UNIX** interface specification, the Common
Desktop Environment (CDE). CDE integrates your tools and files, so selecting a file
also selects the application you need to control the execution of a program, examine
and modify data, and perform many other useful functions. Integrated within the
Common Desktop Environment are visual tools that will help you create, edit, debug,
and manage your applications.

How This Book Will Help You


This book will help you write, compile, link-edit, and run your IBM COBOL Set for AIX
programs. It will also help you define object-oriented classes and methods, invoke
methods, and refer to objects in your programs.

This book assumes experience in developing application programs and some know-
ledge of COBOL. It focuses on using COBOL to meet your programming objectives
and not on the definition of the COBOL language. For complete information on COBOL
syntax, refer to IBM COBOL Language Reference.

There are some differences between host and workstation COBOL. For details on lan-
guage and system differences between IBM COBOL Set for AIX and IBM COBOL for
OS/390 & VM, see Appendix A, “Summary of Differences with Host COBOL” on
page 466.

This book also assumes familiarity with AIX and the IBM COBOL Set for AIX develop-
ment environment. For information on AIX, see your operating system documentation.
To learn about the IBM COBOL Set for AIX development environment, see the Getting
Started guide.

 Copyright IBM Corp. 1996, 1998 xix


Syntax Notation

Abbreviated Terms
Certain terms are used in a shortened form in this book. Abbreviations for the product
names used most frequently in this book are listed alphabetically in Figure 1. Abbrevi-
ations for other terms, if not commonly understood, are shown in italics the first time
they appear, and are listed in the glossary in the back of this book.

Figure 1. Common Abbreviations in this Book


Term Used Long Form
CICS CICS for AIX
SOM System Object Model
STL Standard Language file system

In addition to these abbreviated terms, the term “COBOL 85 Standard” is used in this
book to refer to the combination of the following standards:
Ÿ ISO 1989:1985, Programming languages - COBOL
Ÿ ISO 1989/Amendment 1, Programming Languages - COBOL - Amendment 1:
Intrinsic function module
Ÿ X3.23-1985, American National Standard for Information Systems - Programming
Language - COBOL
Ÿ X3.23a-1989, American National Standard for Information Systems - Programming
Language - Intrinsic Function Module for COBOL

The two ISO standards are identical to the American National standards.

Syntax Notation
Throughout this book, syntax for the compiler options is described using the structure
defined below.
Ÿ Read the syntax diagrams from left to right, from top to bottom, following the path
of the line. The following table shows the meaning of symbols at the beginning
and end of syntax diagram lines.

Symbol Indicates
55─── The syntax diagram starts here
───5 The syntax diagram is continued on the next line
5─── The syntax diagram is continued from the previous line
───5% The syntax diagram ends here

Diagrams of syntactical units other than complete statements start with the 5───
symbol and end with the ───5 symbol.
Ÿ Required items appear on the horizontal line (the main path).

xx COBOL Set for AIX Programming Guide


How Examples Are Shown

55──STATEMENT──required item─────────────────────────────────────────────5%

Ÿ Optional items appear below the main path.


55──STATEMENT──┬───────────────┬─────────────────────────────────────────5%
└─optional item─┘

Ÿ When you can choose from two or more items, they appear vertically in a stack.
If you must choose one of the items, one item of the stack appears on the main
path.
55──STATEMENT──┬─required choice 1─┬─────────────────────────────────────5%
└─required choice 2─┘

If choosing one of the items is optional, the entire stack appears below the main
path.
55──STATEMENT──┬───────────────────┬─────────────────────────────────────5%
├─optional choice 1─┤
└─optional choice 2─┘

Ÿ An arrow returning to the left above the main line indicates an item that can be
repeated.
┌──
─────────────────┐
55──STATEMENT───6─repeatable item─┴───────────────────────────────────────5%

A repeat arrow above a stack indicates that you can make more than one choice
from the stacked items, or repeat a single choice.
Ÿ Keywords appear in uppercase letters (for example, PRINT). They must be spelled
exactly as shown. Variables appear in all lowercase letters (for example, item).
They represent user-supplied names or values.
Ÿ If punctuation marks, parentheses, arithmetic operators, or such symbols are
shown, they must be entered as part of the syntax.
Ÿ Use at least one blank or comma to separate parameters.

How Examples Are Shown


This book shows numerous examples of sample COBOL statements, program frag-
ments, and small programs to help illustrate the concepts being discussed. The exam-
ples of program code are written in lowercase, uppercase, or mixed case to
demonstrate that you can write your programs in any of these three cases.

Where it helps to more clearly separate the examples from the explanatory text, they
are indented, presented in a different font style, or are shown in boxes.

About This Book xxi


How Examples Are Shown

Names of files, COBOL keywords, commands, and options appearing in text are gener-
ally shown in SMALL UPPER CASE, unless they are mixed-case, in which case they are
presented in a different font style.

xxii COBOL Set for AIX Programming Guide


Summary of Changes
This section lists the key changes that have been made to the IBM COBOL Set for AIX
product since Version 1 Release 1. Those documented in this publication have an
associated page reference for you convenience. The latest technical changes are
marked in the text by a change bar in the left margin.

Major Changes
Ÿ New compiler option -host to facilitate setting of all host data compiler options
(“Options Supported by cob2” on page 136).
Ÿ New compiler option ANALYZE to check the syntax of embedded SQL and CICS
statements (“ANALYZE” on page 149).
Ÿ Host DBCS, removal of restriction “CHAR (EBCDIC) does not apply to DBCS
data.,” (removed from Appendix B, “System/390 Host Data Type Considerations”
on page 469 ).
Ÿ Default EBCDIC code page based on run time locale, (“Locale Sensitivity” on
page 413 and “Definitions of COBOL Environment Variables” on page 129).
Ÿ Enable Japanese Era and Chinese Era support in the date/time callable services.
Ÿ Extension of the ACCEPT statement to cover the recommendation in the Working
Draft for Proposed Revision of ISO 1989:1985 Programming Language COBOL
(“How to Get 4-digit Year Dates” on page 444).
Ÿ New intrinsic date functions.
| Ÿ The millennium language extensions, enabling compiler-assisted date processing
| for dates containing 2-digit and 4-digit years (Chapter 29, “Using the Millennium
| Language Extensions” on page 446).
| Ÿ New compiler option WSCLEAR to clear working storage at program initialization
| (“WSCLEAR” on page 185).

 Copyright IBM Corp. 1996, 1998 xxiii


xxiv COBOL Set for AIX Programming Guide
Part 1. Coding Your Program
This part of the book explains how to do various programming tasks using the COBOL
language. It discusses the most common topics, starting with basic ones, then building
on those in succeeding chapters. Topics related to object-oriented COBOL are in
Part 3, “Object-Oriented Programming Topics” on page 221. More complex program-
ming topics are treated in Part 4, “Advanced Topics” on page 315.

For complete details on the COBOL language, see IBM COBOL Language Reference.

Chapter 1. Introduction to COBOL Terms . . . . . . . . . . . . . . . . . . . . 2

Chapter 2. Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Chapter 3. Numbers and Arithmetic . . . . . . . . . . . . . . . . . . . . . . 29

Chapter 4. Handling Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Chapter 5. Selection and Iteration . . . . . . . . . . . . . . . . . . . . . . . . 64

Chapter 6. String Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Chapter 7. Processing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Chapter 8. Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

 Copyright IBM Corp. 1996, 1998 1


COBOL Terms for Data

Chapter 1. Introduction to COBOL Terms


This chapter is intended to help the non-COBOL programmer relate terms used in other
programming languages to COBOL terms.

This chapter introduces COBOL fundamentals for:


Ÿ Variables, Structures, Literals, and Constants
Ÿ Assignment and Terminal Interaction
Ÿ Built-In (Intrinsic) Functions
Ÿ Tables and Pointers

Variables, Structures, Literals, and Constants


Most high-level programming languages share the concept of data being represented
as variables, structures, literals, and constants. This section describes how these data
representations are defined in COBOL. You place all data-item definitions in the DATA
DIVISION of your program.

Variables
In COBOL you refer to a variable by a data-name. For example, if a customer name is
a variable in your program, code:
Data Division.
.
.
ð1 Customer-Name Pic X(2ð).
ð1 Original-Customer-Name Pic X(2ð).
.
.
Procedure Division.
.
.
Move Customer-Name to Original-Customer-Name
.
.

The data used in a COBOL program can be divided into three classes: alphabetic,
alphanumeric, and numeric. For complete details on the classes and categories of data
and the PICTURE clause rules for defining data, see IBM COBOL Language Reference.

Data Structure
Related data items are often parts of a larger, hierarchical data structure. A data item
that is composed of subordinated data items is called a group item. An elementary
data item is a data item that does not have any subordinate items. A record can be
either an elementary data item or a group of data items.

2  Copyright IBM Corp. 1996, 1998


COBOL Terms for Data

Group Items Example


In the following example, Customer-Record is a group item composed of two group
items (Customer-Name and Part-Order) both of which contain elementary data items.
You can refer to the entire group item or to parts of the group item as shown in the
MOVE statements in the Procedure Division.
Data Division.
File Section.
FD Customer-File
Record Contains 45 Characters.
ð1 Customer-Record.
ð5 Customer-Name.
1ð Last-Name Pic x(17).
1ð Filler Pic x.
1ð Initials Pic xx.
ð5 Part-Order.
1ð Part-Name Pic x(15).
1ð Part-Color Pic x(1ð).
Working-Storage Section.
ð1 Orig-Customer-Name.
ð5 Surname Pic x(17).
ð5 Initials Pic x(3).
ð1 Inventory-Part-Name Pic x(15).
.
.
Procedure Division.
.
.
Move Customer-Name to Orig-Customer-Name
Move Part-Name to Inventory-Part-Name
.
.

Literals
When you know the value you want to use for a data item, you don't need to define or
refer to a data-name; instead use a literal representation of the data value in the Proce-
dure Division.

For example, you might want to prepare an error message for an output file:
Move “Invalid Data” To Customer-Name

Or, you might want to compare a data item to a certain number:


ð1 Part-number Pic 9(5).
.
.
If Part-number = ð3519 then display "Part number was found"

In these examples, "Invalid Data" is a non-numeric literal, and ð3519 is a numeric


literal.

Chapter 1. Introduction to COBOL Terms 3


Assigning Values to Data

Constants
COBOL does not define a construct specifically for constants, but most programmers
define a data item with an initial VALUE (as opposed to initializing a variable using the
INITIALIZE statement):
Data Division.
.
.
ð1 Report-Header pic x(5ð) value "Company Sales Report".
.
.
ð1 Interest pic 9v9999 value 1.ð265.

Figurative Constants
Certain commonly used constants and literals are provided as reserved words, called
figurative constants. Because they represent fixed values, figurative constants do not
require a data definition: ZERO, SPACE, HIGH-VALUE, LOW-VALUE, QUOTE, NULL, ALL.

For example: Move Spaces To Report-Header.

Assignment and Terminal Interactions


After you have defined a data item, you can assign a value to it at any time. Assign-
ment takes many forms in COBOL, depending on the purpose behind the assignment:

Figure 2. How to Assign Values to a Data Item


What You Want to Do How to Do It
Assign values to a data item One of these ways:
or large data area
Ÿ INITIALIZE statement
Ÿ MOVE statement
Ÿ STRING or UNSTRING statement
Ÿ VALUE clause (To set data items to the values you want
them to have when the program is in its initial state.)
Replace characters or groups INSPECT statement
of characters in a data item
Receive input values from the ACCEPT statement
terminal or a file
Receive input values from a READ (or READ INTO) statement
file
Assign the results of arith- COMPUTE statement
metic

Initializing a Variable (INITIALIZE Statement)


The following examples illustrate some uses of the INITIALIZE statement. (The symbol ␣
indicates a space.)

4 COBOL Set for AIX Programming Guide


Assigning Values to Data

Initializing a Variable to Blanks or Zeroes:


INITIALIZE identifier-1

IDENTIFIER-1 IDENTIFIER-1 IDENTIFIER-1


PICTURE Before After
9(5) 12345 ððððð
X(5) AB123 ␣␣␣␣␣
99XX9 12AB3 ␣␣␣␣␣
XXBX/XX ABbC/DE ␣␣␣␣/␣␣
**99.9CR 1234.5CR \\ðð.ð␣␣
A(5) ABCDE ␣␣␣␣␣
+99.99E+99 +12.34E+ð2 +ðð.ððE+ðð

Initializing a Right-Justified Field:


ð1 ANJUST PIC X(8) JUSTIFIED RIGHT.
ð1 ALPHABETIC-1 PIC A(4) VALUE "ABCD".
.
.
INITIALIZE ANJUST
REPLACING ALPHANUMERIC DATA BY ALPHABETIC-1

ALPHABETIC-1 ANJUST Before ANJUST After


ABCD ␣␣␣␣␣␣␣␣ ␣␣␣␣ABCD

Initializing an Alphanumeric Variable:


ð1 ALPHANUMERIC-1 PIC X.
ð1 ALPHANUMERIC-3 PIC X(1) VALUE "A".
.
.
INITIALIZE ALPHANUMERIC-1
REPLACING ALPHANUMERIC DATA BY ALPHANUMERIC-3

ALPHANUMERIC-3 ALPHANUMERIC-1 ALPHANUMERIC-1


Before After
A y A

Initializing a Numeric Variable:


ð1 NUMERIC-1 PIC 9(8).
ð1 NUM-INT-CMPT-3 PIC 9(7) COMP VALUE 1234567.
.
.
.
INITIALIZE NUMERIC-1
REPLACING NUMERIC DATA BY NUM-INT-CMPT-3

Chapter 1. Introduction to COBOL Terms 5


Assigning Values to Data

NUM-INT-CMPT-3 NUMERIC-1 NUMERIC-1


Before After
1234567 98765432 ð1234567

Initializing an Edited Alphanumeric Variable:


ð1 ALPHANUM-EDIT-1 PIC XXBX/XXX.
ð1 ALPHANUM-EDIT-3 PIC X/BB VALUE "M/␣␣".
.
.
INITIALIZE ALPHANUM-EDIT-1
REPLACING ALPHANUMERIC-EDITED DATA BY ALPHANUM-EDIT-3

ALPHANUM-EDIT-3 ALPHANUM-EDIT-1 ALPHANUM-EDIT-1


Before After
M/␣␣ AB␣C/DEF M/␣␣/␣␣␣

Initializing a Structure (INITIALIZE Statement)


You can reset the values of all subordinate items in a group by applying the INITIALIZE
statement to the group item. However, it is inefficient to initialize an entire group unless
you really need all the items in the group initialized.

The following example shows how you can reset fields in a transaction record produced
by a program to spaces and zeros. (Notice that the fields are not identical in each
record produced.)
ð1 TRANSACTION-OUT.
ð5 TRANSACTION-CODE PIC X.
ð5 PART-NUMBER PIC 9(6).
ð5 TRANSACTION-QUANTITY PIC 9(5).
ð5 PRICE-FIELDS.
1ð UNIT-PRICE PIC 9(5)V9(2).
1ð DISCOUNT PIC V9(2).
1ð SALES-PRICE PIC 9(5)V9(2).
.
.
INITIALIZE TRANSACTION-OUT

TRANSACTION-OUT Before TRANSACTION-OUT After


Record 1 Rðð1383ððð24ðððððððððððððððð ␣ððððððððððððððððððððððððððð
Record 2 Rðð139ðððð48ðððððððððððððððð ␣ððððððððððððððððððððððððððð
Record 3 Sðð141ðððð12ðððððððððððððððð ␣ððððððððððððððððððððððððððð
Record 4 Cðð1383ððððððððð425ððððððððð ␣ððððððððððððððððððððððððððð
Record 5 Cðð2ð1ððððððððððððð1ðððððððð ␣ððððððððððððððððððððððððððð
Note: The symbol ␣ represents a blank space.

6 COBOL Set for AIX Programming Guide


Assigning Values to Data

Assigning Values to Variables or Structures (MOVE Statement)


Use the MOVE statement to assign values to variables or structures. For example, the
following statement:
Move Customer-Name to Orig-Customer-Name
assigns the contents of the variable Customer-Name to the variable Orig-Customer-Name.
If Customer-Name were longer than Orig-Customer-Name, truncation would occur on the
right. If it were shorter, the extra character positions on the right would be filled with
spaces.

When you move a group item to another group item, be sure the subordinate data
descriptions are compatible. The compiler performs all MOVE statements regardless of
whether items fit, even if that means a destructive overlap could occur at run time. In
such cases, you'll get a warning message when you compile your program.

Assigning Values to Numeric Variables


For variables containing numbers, moves can be more complicated because there are
several ways numbers are represented. In general, the algebraic values of numbers
are moved if possible (as opposed to the digit-by-digit move performed with character
data):
ð1 Item-x Pic 999v9.
.
.
Move 3.ð6 to Item-x
This move would result in Item-x containing the value 3.0, represented by 0030.

Assigning Terminal/File Input to Variables (ACCEPT Statement)


Another way to assign a value to a variable is to read the value from the terminal or a
file. To enter data from the terminal, first associate the terminal with a mnemonic-name
in the SPECIAL-NAMES Paragraph:
Environment Division.
Configuration Section.
Special-Names.
Console is Names-Input.

Then the statement:


Accept Customer-Name From Names-Input
assigns the line of input entered at the terminal to the variable Customer-Name.

To read from a file instead of the terminal, either:


Ÿ Change
Console is Names-Input
to
device is Names-Input

Chapter 1. Introduction to COBOL Terms 7


Assigning Values to Data

in the above example, where device is any valid system device (for example,
SYSIN).
-or-
Ÿ Set the environment variable CONSOLE to a valid file specification using the
export command. For example:
export CONSOLE=/myfiles/myinput.rpt
Note that the environment variable must be the same as the system device used.
In the above example, the system device is Console, but the method of assigning
an environment variable to the system device name is supported for all valid
system devices. For example, if the system device is SYSIN, the environment vari-
able which must be assigned a file specification is SYSIN also).

For more information on setting environment variables, see “Setting Environment


Variables” on page 128.

Displaying Data Values on the Terminal/File (DISPLAY Statement)


In addition to assigning a variable a value read in from the terminal or a file, you can
also display the value of a variable on the terminal or write it to a file. For example, if
the contents of the variable Customer-Name is JOHNSON, then the following statement:
Display “No entry for surname '” Customer-Name “' found in the file.”
will display this message on the terminal:
No entry for surname 'JOHNSON' found in the file.

To write data to a destination other than the system logical output unit, the UPON
clause must be used on the DISPLAY statement. For example:
Display "Hello" UPON SYSOUT
writes to the system logical output device, or to the destination specified in the
SYSOUT environment variable, if defined.

Assigning Arithmetic Results


When assigning a number to a variable, it is sometimes better to use the COMPUTE
statement instead of the MOVE statement. For example, the following two statements
accomplish the same thing in most cases:
Move w to z
Compute z = w
However, when significant left-order digits would be lost in execution, the COMPUTE
statement can detect the condition and allow you to handle it. The MOVE statement
carries out the assignment with destructive truncation.

When you use the ON SIZE ERROR phrase of the COMPUTE statement, the compiler
generates code to detect a size-overflow condition. If the condition occurs, the code in
the ON SIZE ERROR phrase is performed, and the content of z remains unchanged. If
the ON SIZE ERROR phrase is not specified, the assignment is carried out with trun-
cation. There is no ON SIZE ERROR support for the MOVE statement.

8 COBOL Set for AIX Programming Guide


Introducing Intrinsic Functions

Assigning Results of Computations (COMPUTE Statement)


The COMPUTE statement is also used to assign the result of an arithmetic expression
(or intrinsic function) to a variable. For example:
Compute z = y + (x \\ 3)
Compute x = Function Max(x y z)

For information on intrinsic functions, see the IBM COBOL Language Reference.

Built-in (Intrinsic) Functions


Some high-level programming languages have built-in functions that you can reference
in your program as if they were variables having defined attributes and a predetermined
value. In COBOL, these are called intrinsic functions; they provide various string- and
number-manipulation capabilities.

Introduction to Intrinsic Functions


The groups of highlighted words in the following examples are referred to as function-
identifiers. A function-identifier is the combination of the COBOL reserved word FUNC-
TION followed by a function-name (such as Max), followed by any arguments to be
used in the evaluation of the function (such as x, y, z):
Unstring Function Upper-case(Name) Delimited By Space Into Fname Lname

Compute A = 1 + Function Log1ð(x)

Compute M = Function Max(x y z)

A function-identifier represents both the function's invocation and the data value
returned by the function. Because it actually represents a data item, a function-
identifier can be used in most places in the Procedure Division where a data item
having the attributes of the returned value can be used.

Because the value of an intrinsic function is derived automatically at the time of refer-
ence, you do not need to define functions in the Data Division. Define only the non-
literal data items that you use as arguments. Figurative constants are not allowed as
arguments.

Using Function References in Other Contexts


Function-identifiers are loosely referred to in this book as function references. Whereas
the COBOL word FUNCTION is a reserved word, the function-names are not reserved;
you can use them in other contexts, such as for the name of a variable, and without
references to a function.

For example, you could use SQRT to invoke an intrinsic function and/or to name a vari-
able in your program:

Chapter 1. Introduction to COBOL Terms 9


Introducing Intrinsic Functions

Working-Storage Section.
ð1 x Pic 99 value 2.
ð1 y Pic 99 value 4.
ð1 z Pic 99 value ð.
ð1 Sqrt Pic 99 value ð.
.
.
Compute Sqrt = 16 \\ .5
Compute z = x + Function Sqrt(y)
.
.

Types of Intrinsic Functions


A function-identifier represents a value that is either a character string (alphanumeric
| data class) or a number (numeric data class) depending on the type of function. The
| functions MAX, MIN, DATEVAL, and UNDATE can return either type of value depending
on the type of arguments you supply.

| Three functions, DATEVAL, UNDATE, and YEARWINDOW are provided with the
| millennium language extensions to assist with manipulationg and converting windowed
| date fields. For details on the millennium language extensions, see Chapter 29, “Using
| the Millennium Language Extensions” on page 446. The three functions are described
| individually in IBM COBOL Language Reference.

Numeric intrinsic functions are further classified according to the type of numbers they
return. See the IBM COBOL Language Reference for more details.

Nesting Functions
Functions can reference other functions as arguments as long as the results of the
nested functions meet the requirements for the arguments of the outer function. For
example:
Compute x = Function Max((Function Sqrt(5)) 2.5 3.5)
In this case, Function Sqrt(5) returns a numeric value. Thus, the three arguments to
the MAX function are all numeric, which are allowable argument types for this function.

Some of the examples in the next three chapters show nesting of functions.

Substrings of Function-Identifiers
You can include a substring specification (reference modifier) in your function-identifier
for alphanumeric functions.

Arguments to Intrinsic Functions


The ALL subscript, which enables you to easily reference all of the elements of an array
as function arguments, and allowable types of function arguments are discussed in IBM
COBOL Language Reference.

10 COBOL Set for AIX Programming Guide


Arrays and Pointers

Arrays and Pointers


In COBOL, arrays are called tables. The language constructs available for representing
and handling tables are discussed in Chapter 4, “Handling Tables” on page 46.

Pointers
Pointer data items can contain virtual storage addresses. You define them explicitly
with the USAGE IS POINTER clause in the Data Division or implicitly as ADDRESS OF
special registers.

Pointer data items can be:


Ÿ Passed between programs using the CALL ... BY REFERENCE statement
Ÿ Moved to other pointers using the SET statement
Ÿ Compared to other pointers for equality using a relation condition
Ÿ Initialized to contain an invalid address, using VALUE IS NULL

Use pointer data items to:


Ÿ Accomplish limited base addressing, particularly if you want to pass and receive
addresses of a variably located record area.
Ÿ Handle a chained list.

Procedure Pointers
A procedure pointer is a pointer to an entry point. Define the entry address for a proce-
dure entry point with the USAGE IS PROCEDURE-POINTER clause in the Data Divi-
sion.

Chapter 1. Introduction to COBOL Terms 11


IDENTIFICATION DIVISION

Chapter 2. Program Structure


A COBOL program consists of four divisions, each with a specific logical function. Only
the IDENTIFICATION DIVISION is required.
Ÿ The IDENTIFICATION DIVISION, discussed on page 12.
Ÿ The ENVIRONMENT DIVISION, discussed on page 13.
Ÿ The DATA DIVISION, discussed on page 18.
Ÿ The PROCEDURE DIVISION, discussed on page 22.

To define a COBOL class or method, you need to define some divisions differently than
you would for a program. For detail on the differences, see “Writing a Class Definition”
on page 224 or “Writing a Method Definition” on page 228.

IDENTIFICATION DIVISION
Use the IDENTIFICATION DIVISION to name your program and to optionally give other
identifying information. For example:
Identification Division.
Program-ID. Helloprog.
Author. A. Programmer.
Installation. Computing Laboratories.
Date-Written. ð8/18/1997.
Date-Compiled. ð2/27/1998.

You can use the optional AUTHOR, INSTALLATION, DATE-WRITTEN, and DATE-COMPILED
paragraphs for descriptive information about your program. The data you enter on the
DATE-COMPILED paragraph is replaced with the latest compilation date.

PROGRAM-ID Paragraph
Use the PROGRAM-ID paragraph to name your program. The program name you
assign is used in these ways:
Ÿ Other programs use the name to call your program.
Ÿ The name appears in the header on each page, except the first page, of the
program listing generated when the program is compiled. (See “Changing Header
of Source Listing” on page 13 for details.)

Marking Programs as RECURSIVE


Code the RECURSIVE attribute on the PROGRAM-ID clause so your program can be
recursively re-entered while a previous invocation is still active.

RECURSIVE can be coded only on the outermost program of a compilation unit. Neither
programs containing nested subprograms nor nested subprograms can be recursive.

12  Copyright IBM Corp. 1996, 1998


ENVIRONMENT DIVISION

Marking Programs as COMMON


Use the COMMON attribute with the PROGRAM-ID clause so your program can be called
by the containing program or by any program in the containing program. However, the
COMMON program cannot be called by any program contained in itself. Only contained
programs can have the COMMON attribute. For more information, see “Structure of
Nested Programs” on page 324.

Marking Programs as INITIAL


Use the INITIAL attribute to specify that whenever a program is called, it is placed in its
initial state, and any of its contained programs are also placed in their initial states.

Definition of Initial State: Essentially, a program is in its initial state when data items
having VALUE clauses are set to the specified value, changed GO TO statements and
PERFORM statements are set to their initial states, and non-EXTERNAL files are closed.

Avoiding Mismatches Between Names


To avoid mistakes when the name is case-sensitive, verify that the appropriate setting
of the PGMNAME option is used.

Changing Header of Source Listing


The header on the first page of your source statement listing contains the identification
of the compiler and the current release level, plus the date and time of compilation and
the page number. For example:

PP 5765-548 IBM COBOL Set for AIX 1.1.ð Date ð2/27/1998 Time 15:ð5:19 Page 1

You can customize the header on succeeding pages of the listing with the compiler-
directing TITLE statement. See the IBM COBOL Language Reference for details of the
TITLE statement.

ENVIRONMENT DIVISION
In the ENVIRONMENT DIVISION you can describe those aspects of your program that are
dependent upon the characteristics of the computing environment in which you are
working.

CONFIGURATION SECTION
You can use the CONFIGURATION SECTION to describe the computer for compiling your
program (in the SOURCE-COMPUTER paragraph); describe the computer for running
your program (in the OBJECT-COMPUTER paragraph); and specify such items as the
currency sign, symbolic characters (in the SPECIAL-NAMES paragraph), and user-
defined classes (in the REPOSITORY paragraph). Figure 3 on page 15 shows a
sample of some of the entries you might include in the CONFIGURATION SECTION.

Chapter 2. Program Structure 13


ENVIRONMENT DIVISION

Specify the Collating Sequence


Using the PROGRAM COLLATING SEQUENCE clause and the ALPHABET clause of the
SPECIAL-NAMES paragraph, you can establish the collating sequence used in the fol-
lowing operations:
Ÿ Non-numeric comparisons explicitly specified in relation conditions and condition-
name conditions
Ÿ HIGH-VALUE and LOW-VALUE settings
Ÿ SEARCH ALL
Ÿ SORT and MERGE unless overridden by a COLLATING SEQUENCE phrase on the
SORT or MERGE statement.

The sequence you use can be based on one of these alphabets:


Ÿ NATIVE
NATIVE is the collating sequence specified by the locale setting. The locale setting
refers to the national language locale name in effect at compile time. It is usually
set at installation. See “Locale Sensitivity” on page 413 for more information about
locale sensitivity.
Ÿ EBCDIC
Ÿ ASCII (use NATIVE if the native character set is ASCII, STANDARD-11 if it is not).
Ÿ ISO 7-bit code2, International Reference Version (use STANDARD-2).
Ÿ An alteration of the ASCII sequence that you define in the SPECIAL-NAMES para-
graph.

You can also specify a collating sequence of your own definition.


Caution: If the code page is DBCS or EUC the ALPHABET-NAME clause is not
allowed.

Specifying Collating Sequence Example: Figure 3 on page 15 shows the ENVIRON-


MENT DIVISION coding used to specify a collating sequence where uppercase and low-
ercase letters are similarly handled for comparisons and for sorting or merging. When
you change the ASCII sequence in the SPECIAL-NAMES paragraph, the overall collating
sequence is affected, not just the collating sequence of the characters included in the
SPECIAL-NAMES paragraph.

1 STANDARD-1 refers to American National Standard X3.4, Code for Information Interchange.
2 ISO 7-bit code, as defined in International 646, 7-Bit Coded Character Set for Information Processing Interchange, International
Reference.

14 COBOL Set for AIX Programming Guide


ENVIRONMENT DIVISION

Identification Division.
.
.
Environment Division.
Configuration Section.
Object-Computer.
Program Collating Sequence Special-Sequence.
Special-Names.
Alphabet Special-Sequence Is
"A" Also "a"
"B" Also "b"
"C" Also "c"
"D" Also "d"
"E" Also "e"
"F" Also "f"
"G" Also "g"
"H" Also "h"
"I" Also "i"
"J" Also "j"
"K" Also "k"
"L" Also "l"
"M" Also "m"
"N" Also "n"
"O" Also "o"
"P" Also "p"
"Q" Also "q"
"R" Also "r"
"S" Also "s"
"T" Also "t"
"U" Also "u"
"V" Also "v"
"W" Also "w"
"X" Also "x"
"Y" Also "y"
"Z" Also "z".

Figure 3. Example of an Alternate Collating Sequence

Define Symbolic Characters


Use the SYMBOLIC CHARACTER clause to give symbolic names to any character of the
specified alphabet. For example, to give a name to the plus character (X'2B' in the
ASCII alphabet) code:
SYMBOLIC CHARACTERS PLUS IS 44
Use ordinal position to identify the character; position 1 corresponds to character
X'00'.

Define a User-Defined Class


Use the CLASS clause to give a name to a set of characters listed in the clause. For
example, name the set of digits by coding:
CLASS DIGIT IS "ð" THROUGH "9"

Chapter 2. Program Structure 15


ENVIRONMENT DIVISION

The class name can only be referenced in a class condition. (This user-defined class is
not the same concept as an object-oriented class.)

INPUT-OUTPUT SECTION:
Your IBM COBOL Set for AIX programs can process files with line sequential, sequen-
tial, indexed, or relative organization.

Use the FILE-CONTROL and I-O-CONTROL paragraphs to:


Ÿ Identify and describe the characteristics of your program files.
Ÿ Associate your files with the corresponding system file name, directly or indirectly.
Ÿ Optionally identify the file system (for example, VSAM or STL file system) associ-
ated with the file. You can also do this at program execution time.
Ÿ Provide information on how the file is accessed.

FILE-CONTROL Paragraph
The FILE-CONTROL paragraph associates each file in the COBOL program with a phys-
ical file known to your file system. Figure 4 shows an example of a FILE-CONTROL
paragraph for a VSAM indexed file.

FILE-CONTROL Entries for a VSAM Indexed File

SELECT COMMUTER-FILE .1/


ASSIGN TO COMMUTER .2/
ORGANIZATION IS INDEXED .3/
ACCESS IS RANDOM .4/
RECORD KEY IS COMMUTER-KEY .5/
FILE STATUS IS .5/
COMMUTER-FILE-STATUS
COMMUTER-VSAM-STATUS.

Figure 4. Example of a FILE-CONTROL Paragraph

.1/ The SELECT clause chooses a file in the COBOL program to be associated with
a corresponding system file.
.2/ The ASSIGN clause associates the program's name for the file with the name of
the file as known to the system. COMMUTER may be the system file name or the
name of the environment variable whose value (at run time) is used as the
system file name with optional directory and path names.
.3/ Use the ORGANIZATION clause to describe the file's organization. If omitted, the
default is ORGANIZATION IS SEQUENTIAL.
.4/ Use the ACCESS MODE clause to define the manner in which the records in the
file will be made available for processing—sequential, random, or dynamic. If
you omit this clause, ACCESS IS SEQUENTIAL is assumed.

16 COBOL Set for AIX Programming Guide


ENVIRONMENT DIVISION

.5/ You might have additional statements in the FILE-CONTROL paragraph


depending on the type of file and file system you use. See the IBM COBOL
Language Reference for more information about the FILE-CONTROL paragraph.

Chapter 7, “Processing Files” on page 90 provides a general overview on files and file
processing.

Identifying Files to the Operating System


As stated in the previous example, the ASSIGN clause associates the program's name
for a file with the name of the file as known to the operating system.

You can use either an environment variable, a system file name, a literal, or a data
name in the ASSIGN clause. If you specify an environment variable, its value is evalu-
ated at run time and is used as the system file name with optional directory and path
names.

If you plan to use a file system other than the default file system, you need to select the
file system explicitly, for example, by specifying the file system identifier before the
system file name. For example, if the file MYFILE is an Encina SFS file and you use F1
as the file's name in your program, the ASSIGN clause would be
SELECT F1 ASSIGN TO VSA-MYFILE
Note that this assumes that MYFILE is a system file name and not an environment vari-
able. If MYFILE is an environment variable, then its value will be used. For example, if
it is set to MYFILE=VSAM-YOURFILE, the system file name in the ASSIGN clause becomes
YOURFILE at run time, and the file is treated as a VSAM file, overriding the file system ID
used in ASSIGN clause in the program.

Vary the Input/Output File at Run Time


The file-name you code in your SELECT sentence is used as a constant throughout your
COBOL program, while the name of the file in your export command can be associated
with a different file at run time.

Changing a file-name in your COBOL program requires changing input/output state-


ments and recompiling the program. In contrast, you can change the assignment-name
in your export command.

Example of Using Different Input Files: As an example, consider a COBOL program


that might be used in exactly the same way for several different master files. It con-
tains this SELECT sentence:
SELECT MASTER
ASSIGN TO MASTERA
For example, if you are accessing both checking and savings files using the same
MASTER file, you can set the MASTERA environment variable prior to the program exe-
cution as follows:
export MASTERA=/accounts/checking
to access the file named checking in the /accounts directory and

Chapter 2. Program Structure 17


DATA DIVISION

export MASTERA=/accounts/savings
to do the same for the file named savings

The same program can be used to access both checking and savings files by way of
the COBOL MASTER file without source program changes or recompilation.

Environment variable values in effect at the time of the program invocation are used for
associating COBOL file names to the system file names (including any path specifica-
tions).

DATA DIVISION
Define the characteristics of your data and group your data definitions into one of the
sections in the DATA DIVISION:
Ÿ Define data used in input/output operations in the FILE SECTION (discussed in
“FILE SECTION (Using Data in Input/Output Operations)”).
Ÿ Define data developed for internal processing:
– To be statically allocated and exist for the life of the run-unit:
WORKING-STORAGE SECTION (discussed on page 19).

– To be allocated each time a program is called and deallocated when the


program ends: LOCAL-STORAGE SECTION (discussed on page 20).
Ÿ Describe data from another program in the LINKAGE SECTION (discussed on page
21).

Limits in the DATA DIVISION


The IBM COBOL Set for AIX compiler limits the maximum size of data division ele-
ments. For a complete list of these compiler limits, see IBM COBOL Language Refer-
ence.

FILE SECTION (Using Data in Input/Output Operations)


Define the data you use in input and output operations in the FILE SECTION:
Ÿ Name the input and output files your program will use.
Use the FD entry to give names to your files that the input/output statements in the
PROCEDURE DIVISION can refer to.

Caution: Data items defined in the FILE SECTION are not available to PROCEDURE
DIVISION statements until the file has been successfully opened.

Ÿ In the record description following the FD entry describe the records and their fields
in the file. The record-name established is the object of WRITE and REWRITE state-
ments.

18 COBOL Set for AIX Programming Guide


DATA DIVISION

Function and Use of FILE SECTION Entries


Entries in the FILE SECTION are summarized in Figure 5.

Figure 5. FILE SECTION Entries


Clause To Define
FD The file-name to be referred to in PROCEDURE DIVISION input/output state-
ments (OPEN, CLOSE, READ, START, and DELETE). Must match file-name in
the SELECT clause. file-name is associated with the system file through the
assignment-name.
RECORD CONTAINS n Size of logical records (fixed length)
RECORD IS VARYING Size of logical records (variable length)
RECORD CONTAINS n TO m Size of logical records (variable length)
VALUE OF An item in the label records associated with file. Comments only.
DATA RECORDS Names of records associated with file. Comments only.
RECORDING MODE Record type for sequential files.

Sharing Files Using the EXTERNAL and GLOBAL Clauses


Programs in the same run unit can refer to the same COBOL file names. You can also
share physical files without using external or global file definitions in COBOL source
programs.

For example, if you specify:


SELECT F1 ASSIGN TO MYFILE.
SELECT F2 ASSIGN TO MYFILE.

The application has two COBOL file names, but these COBOL files are associated with
one system file.

EXTERNAL: Is used for separately compiled programs. A file that is defined as


EXTERNAL can be referenced by any program in the run unit that describes the file.
See “Sharing Files between Programs (EXTERNAL Files)” on page 346 for an
example.

GLOBAL: Is used for programs in a nested, or contained, structure. If a program


contains another program (directly or indirectly), both programs can access a common
file by referencing a GLOBAL file name. For more information on contained programs
and the GLOBAL clause, see “Structure of Nested Programs” on page 324.

WORKING-STORAGE SECTION and LOCAL-STORAGE SECTION


You can write a program that processes data without performing any input/output oper-
ations. All the data would be defined in the WORKING-STORAGE SECTION or
LOCAL-STORAGE SECTION.

Chapter 2. Program Structure 19


DATA DIVISION

Most programs, however, have a combination of input and output file processing and
internal data manipulation; the data files are defined in the FILE SECTION, and the data
developed by the program is defined in the WORKING-STORAGE SECTION or
LOCAL-STORAGE section.

What is the WORKING-STORAGE SECTION?


When a program is invoked, the WORKING STORAGE associated with the program is
allocated. Any data items with VALUE clauses are initialized to the appropriate value at
that time. For the duration of the run-unit, Working-Storage items persist in their last-
used state. Exceptions are:
Ÿ A program with INITIAL specified on the PROGRAM-ID.
In this case, WORKING-STORAGE data items are reinitialized each time the program
is entered.
Ÿ A subprogram that is called and then cancelled.
In this case, WORKING-STORAGE DATA items are reinitialized on the first reentry
into the program following the CANCEL.

Working-Storage is deallocated at the termination of the run-unit.

What is the LOCAL-STORAGE SECTION?


Local-Storage is allocated each time the program is called and is deallocated when the
program returns via an EXIT PROGRAM, GOBACK, or STOP RUN. Any data items with
VALUE clauses are initialized to the appropriate value each time the program is called.
The value in the data items is lost when the program returns.

Storage Sections Example


The following is an example of a recursive program that uses both Working-Storage
and Local-Storage.

20 COBOL Set for AIX Programming Guide


DATA DIVISION

CBL apost,pgmn(lu)
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Recursive Program - Factorials
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification Division.
Program-Id. factorial recursive.
Environment Division.
Data Division.
Working-Storage Section.
ð1 numb pic 9(4) value 5.
ð1 fact pic 9(8) value ð.
Local-Storage Section.
ð1 num pic 9(4).
Procedure Division.
move numb to num.

if numb = ð
move 1 to fact
else
subtract 1 from numb
call 'factorial'
multiply num by fact
end-if.

display num '! = ' fact.


goback.
End Program factorial.

Figure 6. Storage Sections Example

Recursive
CALL's: Main 1 2 3 4 5
------------------------------------
L-S num 5 4 3 2 1 ð
------------------------------------
W-S numb 5 4 3 2 1 ð
fact ð ð ð ð ð ð
------------------------------------
Recursive
GOBACK's: 5 4 3 2 1 Main
------------------------------------
L-S num ð 1 2 3 4 5
------------------------------------
W-S numb ð ð ð ð ð ð
fact 1 1 2 6 24 12ð
------------------------------------

LINKAGE SECTION (Using Data from Another Program)


How you share data depends on whether the programs are separately compiled or are
nested.

Chapter 2. Program Structure 21


PROCEDURE DIVISION

Separately Compiled Programs


Many times an application's solution consists of many separately compiled programs
that call and pass data to one another. The LINKAGE SECTION in the called program
describes the data passed from another program. The calling program must use a
CALL ... USING or INVOKE ... USING statement to pass the data. For details on using
data from other programs, see “Passing Data” on page 336.

Nested Programs
An application's solution might consist of nested programs—programs that are con-
tained in other programs. Level-01 LINKAGE SECTION data items can include the
GLOBAL attribute. This allows any nested program that includes the declarations to
access these LINKAGE SECTION data items.

A nested program can also access data items in a sibling program (one at the same
nesting level in the same containing program) that is declared with the COMMON attri-
bute. For more details, see “Structure of Nested Programs” on page 324.

With Recursion or Multithreading


If you compile your program as recursive or with the THREAD option, data defined in the
LINKAGE SECTION may not be accessible between entries.

The ability to address a record in the LINKAGE SECTION is established by:


Ÿ Passing an argument to the program and specifying the record in an appropriate
position in the USING phrase in the program or
Ÿ Using the Format 5 SET statement.

If you compile your program as recursive or with the THREAD option, the address to that
record is valid for the particular instance of the program invocation. The address to the
record in another execution instance of the same program must be re-established for
that execution instance. Unpredictable results will occur if reference is made to a data
item whose address has not been established.

PROCEDURE DIVISION
In the PROCEDURE DIVISION of a program you code the executable statements that
process the data you have defined in the other divisions. The PROCEDURE DIVISION
contains one or two headers and the logic of your program.

PROCEDURE DIVISION Headers


The PROCEDURE DIVISION begins with the division header and a procedure-name
header. The division header for a program can simply be:
PROCEDURE DIVISION.

Or, you can code your division header to receive parameters with the USING phrase or
to return a value with the RETURNING Phrase.

22 COBOL Set for AIX Programming Guide


PROCEDURE DIVISION

USING Phrase

To receive an argument that was passed by reference (the default) or by content, code
the division header for a program like this:
PROCEDURE DIVISION USING dataname
Or this:
PROCEDURE DIVISION USING BY REFERENCE dataname
Take Note: dataname in these examples would need to be defined in the LINKAGE
SECTION of the program.

To receive a parameter that was passed by value, code the division header for a
program like this:
PROCEDURE DIVISION USING BY VALUE dataname

See “Passing Data” on page 336 for more information on BY VALUE.

RETURNING Phrase

To return a value as a result, code the division header like this:


Procedure Division RETURNING dataname2

You can also combine USING AND RETURNING in a PROCEDURE DIVISION header:
Procedure Division USING dataname RETURNING dataname2
Take Note: dataname and dataname2 in these examples would need to be defined in
the LINKAGE SECTION.

How Logic is Divided in the PROCEDURE DIVISION


The PROCEDURE DIVISION of a program is divided into sections, paragraphs, sen-
tences, and statements:
Section Logical subdivision of your processing logic.
A section can contain several paragraphs.
A section can be the subject of the PERFORM statement.
Paragraph Subdivides a section, procedure, or program.
It contains a set of related statements that provide a function and is one
of the basic building blocks of a structured program. A paragraph can be
the subject of a statement.
Sentence Series of one or more COBOL statements ending with a period.
Many structured programs do not have separate sentences. Each para-
graph can contain one sentence. Using scope terminators instead of
periods to show the logical end of a statement is preferred. Scope termi-
nators, both explicit and implicit, are discussed beginning on page 25.

Chapter 2. Program Structure 23


PROCEDURE DIVISION

Statement Performs a defined step of COBOL processing, such as adding two


numbers.
A statement is a valid combination of words, beginning with a COBOL
verb.

Statements Used in the PROCEDURE DIVISION


In the COBOL language, statements are imperative (indicating unconditional action),
conditional, or compiler-directing.

Imperative and conditional statements can be ended implicitly or explicitly. If you end a
conditional statement explicitly, it becomes a delimited scope statement (which is an
imperative statement).

Imperative Statements
An imperative statement indicates that an unconditional action is to be taken. Exam-
ples are ADD, MOVE, INVOKE, and CLOSE. A full list of imperative statements can be
found in IBM COBOL Language Reference.

Conditional Statements
A conditional statement is either a simple conditional statement (IF, EVALUATE,
SEARCH) or a conditional statement made up of an imperative statement that includes a
conditional phrase or option.

Examples of Conditional Phrases: For example, an arithmetic statement without ON


SIZE ERROR is an imperative statement. But an arithmetic statement with the condi-
tional option ON SIZE ERROR and without a scope terminator is a conditional statement.

The following are examples of conditional statements if they are coded without scope
terminators:
Ÿ Data-manipulation statements with ON OVERFLOW.
Ÿ CALL statements with ON OVERFLOW.
Ÿ I/O statements with INVALID KEY, AT END, AT END-OF-PAGE.
Ÿ RETURN with AT END.

Using the NOT Phrase: For additional program control, the NOT phrase can also be
used with conditional statements. For example, you can provide instructions to be per-
formed when a particular exception does not occur, such as NOT ON SIZE ERROR. The
NOT phrase cannot be used with the ON OVERFLOW phrase of the CALL statement, but
it can be used with the ON EXCEPTION phrase.

Do Not Nest Conditional Statements: An unterminated conditional statement cannot


be contained by (nested within) another statement. Except for nesting statements
within IF statements, nested statements must be imperative statements and must follow
the rules for imperative statements.

24 COBOL Set for AIX Programming Guide


PROCEDURE DIVISION

Compiler-Directing Statements
A compiler-directing statement is not part of the program logic. A compiler-directing
statement causes the compiler to take specific action about the program structure,
COPY processing, listing control, control flow, or CALL interface convention.

A description of compiler-directing statements can be found in IBM COBOL Language


Reference. See “Compiler-Directing Statements” on page 187 for usage notes.

Explicit Scope Terminators


Explicit scope terminators end certain conditional and imperative forms of PROCEDURE
DIVISION statements. Use an explicit scope terminator to make a conditional statement
imperative (see “Delimited Scope Statements” on page 26). Or use an explicit scope
terminator to clearly end an imperative statement. Explicit scope terminators are pro-
vided for certain COBOL verbs, such as scope terminator END-IF for the IF verb, and
can be found in IBM COBOL Language Reference.

Example of Using Explicit Scope Terminators


MOVE ð TO TOTAL
PERFORM UNTIL X = 1ð
ADD 1 TO TOTAL
IF X = 5
DISPLAY "HALFWAY THROUGH"
DISPLAY "TOTAL IS " TOTAL
END-IF
ADD 1 TO X
END-PERFORM
DISPLAY "FINAL TOTAL IS " TOTAL

Implicit Scope Terminators


An implicit scope terminator is a period (.) that ends the scope of all previous state-
ments not yet ended.

Example of Using Implicitly Terminated Statements:


IF CAT
DISPLAY "It is a cat."
ELSE
IF DOG
DISPLAY "It is a dog."
ELSE
DISPLAY "It is not a dog or cat.".

Each of the two periods in the above program fragment end the IF statements, making
the code equivalent to the following example that has explicit scope terminators:

Chapter 2. Program Structure 25


PROCEDURE DIVISION

IF CAT
DISPLAY "It is a cat."
ELSE
IF DOG
DISPLAY "It is a dog."
ELSE
DISPLAY "It is not a dog or cat."
END-IF
END-IF

If you use implicit terminators, it can be unclear where statements end. As a result,
you might end statements unintentionally, changing your program's logic. Explicit scope
terminators make a program easier to understand and prevent unintentional ending of
statements. For example, in the program fragment below, changing the location of the
first period in the first implicit scope example changes the meaning of the code:
IF ITEM = "A"
DISPLAY "VALUE OF ITEM IS " ITEM
ADD 1 TO TOTAL.
MOVE "C" TO ITEM
DISPLAY " VALUE OF ITEM IS NOW " ITEM
IF ITEM = "B"
ADD 2 TO TOTAL.
The two statements:
MOVE "C" TO ITEM
DISPLAY " VALUE OF ITEM IS NOW " ITEM
will be performed regardless of the value of ITEM, despite what the indentation indi-
cates, because the first period terminates the IF statement. For improved program
clarity and to avoid unintentional ending of statements, you should use explicit scope
terminators instead of implicit scope terminators, especially within paragraphs. Use
implicit scope terminators only at the end of a paragraph or the end of the program.

Delimited Scope Statements


A delimited scope statement is a conditional statement ended with an explicit scope
terminator. A delimited scope statement can be used in these ways:
Ÿ To delimit the range of operation for a COBOL conditional statement and to explic-
itly show the levels of nesting.
For example, use an END-IF statement instead of a period to end the scope of an
IF statement within a nested IF.

Ÿ To code a conditional statement where the COBOL syntax calls for an imperative
statement.
For example, code a conditional statement as the object of an inline PERFORM:

26 COBOL Set for AIX Programming Guide


PROCEDURE DIVISION

PERFORM UNTIL TRANSACTION-EOF


PERFORM 2ðð-EDIT-UPDATE-TRANSACTION
IF NO-ERRORS
PERFORM 3ðð-UPDATE-COMMUTER-RECORD
ELSE
PERFORM 4ðð-PRINT-TRANSACTION-ERRORS
END-IF
READ UPDATE-TRANSACTION-FILE INTO WS-TRANSACTION-RECORD
AT END
SET TRANSACTION-EOF TO TRUE
END-READ
END-PERFORM
An explicit scope terminator is required for the inline PERFORM statement, but it is
not valid for the out-of-line PERFORM statement.

Rules for Delimited Scope Statements: Because a period implicitly ends the scope
of all previous statements, do not use a period in a delimited scope statement.

In general, a delimited scope statement can be coded wherever an imperative state-


ment is allowed by language rules.

Using Nested Delimited Scope Statements: When nested within another delimited
scope statement with the same verb, each explicit scope terminator ends the statement
begun by the most recently preceding (and as yet unpaired) occurrence of that verb.

Be careful when coding an explicit scope terminator for an imperative statement that is
nested within a conditional statement. Ensure that the scope terminator is paired with
the statement for which it was intended. In the following example, the scope terminator
will be paired with the second READ statement, though the programmer intended it to
be paired with the first.
READ FILE1
AT END
MOVE A TO B
READ FILE2
END-READ

To ensure that the explicit scope terminator is paired with the intended statement, the
preceding example can be recoded in this way:
READ FILE1
AT END
MOVE A TO B
READ FILE2
END-READ
END-READ

Declaratives
Declaratives provide one or more special-purpose sections that are executed when an
exceptional condition occurs.

Chapter 2. Program Structure 27


PROCEDURE DIVISION

Each Declarative Section starts with a USE statement that identifies the function of the
section; the series of procedures that follow specify what actions are to be taken when
the condition occurs. See the IBM COBOL Language Reference for a complete
description of declaratives and Chapter 12, “Debugging Techniques” on page 197 and
“Input/Output Error Handling Techniques” on page 118 for instances of their use.

28 COBOL Set for AIX Programming Guide


How COBOL Views Numbers

Chapter 3. Numbers and Arithmetic


This chapter explains how COBOL views numeric data and how you can best represent
numeric data and perform efficient arithmetic operations. The topics are:
Ÿ “General COBOL View of Numbers (PICTURE clause).”
Ÿ “Computational Data Representation (USAGE Clause)” on page 30.
Ÿ “Data Format Conversions” on page 35.
Ÿ “Sign Representation and Processing” on page 37.
Ÿ “Checking for Incompatible Data (Numeric Class Test)” on page 37.
Ÿ “Performing Arithmetic” on page 38.
Ÿ “Fixed-Point versus Floating-Point Arithmetic” on page 43.

General COBOL View of Numbers (PICTURE clause)


In general, you can view COBOL numeric data in a way similar to character-string
data—as a series of decimal digit positions. However, numeric items can have special
properties, such as an arithmetic sign.

Defining Numeric Items


Define numeric items using the character "9" in the data description to represent the
decimal digits of the number instead of using an "x" like with alphanumeric items:
ð5 Count-x Pic 9(4) Value 25.
ð5 Customer-name Pic x(2ð) Value "Johnson".

You can code up to 18 digits in the PICTURE clause, as well as various other characters
of special significance. The "s" in the following example means that the value is
signed:
ð5 Price Pic s99v99.
The field can hold a positive or negative value. The "v" indicates the position of an
implied decimal point. Neither "s" nor "v" are counted in the size of the item, nor do
they require extra storage positions, unless the item is coded as USAGE DISPLAY with
the SIGN IS SEPARATE clause. An exception is internal floating point data (COMP-1 or
COMP-2), for which there is no PICTURE clause.

Separate Sign Position (for Portability)


If you plan to port your program or data to a different machine, you might want to code
the sign as a separate digit position in storage:
ð5 Price Pic S99V99 Sign Is Leading, Separate.
This ensures that the convention your machine uses for storing a non-separate sign will
not cause strange results when you use a machine that uses a different convention.

 Copyright IBM Corp. 1996, 1998 29


How COBOL Stores Your Numbers

Extra Positions for Displayable Symbols (Numeric Editing)


You can also define numeric items with certain editing symbols (such as decimal points,
commas, and dollar signs) to make the data easier to read and understand when dis-
played or printed on reports. For example:
ð5 Price Pic 9(5)v99.
ð5 Edited-price Pic $zz,zz9v99.
..
.
Move Price To Edited-price
Display Edited-price
If the contents of Price were 0150099 (representing the value 1,500.99), then $
1,5ðð.99 would be displayed after the code is run.

How to Use Numeric-Edited Items as Numbers


Numeric-edited items are classified as alphanumeric data items, not as numbers.
Therefore, they cannot be operands in arithmetic expressions or ADD, SUBTRACT, MUL-
TIPLY, DIVIDE, and COMPUTE statements.

Numeric-edited items can be moved to numeric and numeric-edited items. In the fol-
lowing example, the numeric-edited item is de-edited and its numeric value is moved to
the numeric data item.
Move Edited-price to Price
Display Price
If these two statements were to immediately follow the statements shown in the pre-
vious example, then Price would be displayed as 0150099, representing the value
1,500.99.

For complete information on the data descriptions for numeric data, refer to IBM
COBOL Language Reference.

Computational Data Representation (USAGE Clause)


Control how the computer internally stores your numeric data items by coding the
USAGE clause in your data description entries. The numeric data you use in your
program will be one of the formats available with COBOL:
External decimal (USAGE DISPLAY)
External floating-point (USAGE DISPLAY)
Internal decimal (USAGE PACKED-DECIMAL)
Binary (USAGE BINARY)
Binary (COMP-5).
Internal floating-point (USAGE COMP-1, USAGE COMP-2)

COMP and COMP-4 are synonymous with BINARY, and COMP-3 is synonymous with
PACKED-DECIMAL.

30 COBOL Set for AIX Programming Guide


How COBOL Stores Your Numbers

Regardless of what USAGE clause you use to control the computer's internal represen-
tation of the value, you use the same PICTURE clause conventions and decimal value in
the VALUE clause except for floating point data.

External Decimal (USAGE DISPLAY) Items


When you code USAGE DISPLAY or omit the USAGE clause, each position (or byte) of
storage contains one decimal digit. This corresponds to the format used for printing or
displaying output, meaning the items are stored in displayable form.

What USAGE DISPLAY Items Are For


External decimal items are primarily intended for receiving and sending numbers
between your program and files, terminals, and printers. However, it is also acceptable
to use external decimal items as operands and receivers in your program's arithmetic
processing, and it is often convenient to program this way.

Should You Use Them for Arithmetic


If your program performs a lot of intensive arithmetic and efficiency is a high priority,
you might want to use one of COBOL's computational numeric data types for the data
items used in the arithmetic.

The compiler has to automatically convert displayable numbers to the internal represen-
tation of their numeric value before they can be used in arithmetic operations. There-
fore, it is often more efficient to define your data items as computational items to begin
with, rather than as DISPLAY items. For example:
ð5 Count-x Pic s9v9(5) Usage Comp Value 3.14159.

External Floating-Point (USAGE DISPLAY) Items


Displayable numbers coded in a floating-point format are called external floating-point
items. Like external decimal items, you define external floating-point items explicitly
with USAGE DISPLAY or implicitly by omitting the USAGE clause.

In the following example, Compute-Result is implicitly defined as an external floating-


point item. Each byte of storage contains one character (except for V).
ð5 Compute-Result Pic -9v9(9)E-99.

The VALUE clause is not allowed in the data description for external floating-point items.
Also, the minus signs (-) do not mean that the mantissa and exponent will always be
negative numbers, but that when displayed the sign will appear as a blank for positive
and a minus sign for negative. If a plus sign (+) were used, positive would be displayed
as a plus sign and negative as a minus sign.

Just as with external decimal numbers, external floating-point numbers have to be con-
verted (automatically by the compiler) to an internal representation of the numeric value
before they can be operated on.

Chapter 3. Numbers and Arithmetic 31


How COBOL Stores Your Numbers

Binary Items
BINARY, COMP, and COMP-4 are synonyms on all platforms. COMP-5 is a new USAGE
type based on the X/OPEN COBOL specification.

Binary format occupies 2, 4, or 8 bytes of storage and is handled for arithmetic pur-
poses as a fixed-point number with the leftmost bit being the operational sign. For
byte-reversed binary data, the sign bit is the leftmost bit of the rightmost byte.

How Much Storage BINARY Occupies


A PICTURE description with 4 or fewer decimal digits occupies 2 bytes; with 5 to 9
decimal digits, 4 bytes; with 10 to 18 decimal digits, 8 bytes.

Why Use Binary


Binary items can, for example, contain subscripts, switches, and arithmetic operands or
results.

However, you might want to use packed decimal format instead of binary because:
Ÿ Binary format might not be as well suited for decimal alignment as packed decimal
format.
Ÿ Binary format is not converted to and from DISPLAY format as easily as packed
decimal format.

Truncation of Binary Data (TRUNC Compiler Option)


Use the TRUNC(STD|OPT|BIN) compiler option (described in “TRUNC” on page 180) to
indicate how binary data (BINARY, COMP, and COMP-4) is truncated.
COMP-5 Note: COMP-5 data is truncated according to TRUNC(BIN) regardless of
which suboption of TRUNC you set.

Packed Decimal (PACKED-DECIMAL or COMP-3) Items


Packed decimal format occupies 1 byte of storage for every two decimal digits you
code in the PICTURE description, except that the right-most byte contains only 1 digit
and the sign. Packed decimal format is handled as a fixed-point number for arithmetic
purposes.

Why Use Packed Decimal


Ÿ Packed decimal format requires less storage per digit than DISPLAY format
requires.
Ÿ Packed decimal format might be better suited for decimal alignment than binary
format.
Ÿ Packed decimal format is converted to and from DISPLAY format more easily than
binary format.
Ÿ Packed decimal format can, for example, contain arithmetic operands or results.

32 COBOL Set for AIX Programming Guide


How COBOL Stores Your Numbers

Floating-Point (COMP-1 and COMP-2) Items


COMP-1 refers to short (single-precision) floating-point format, and COMP-2 refers to
long (double-precision) floating-point format, which occupy 4 and 8 bytes of storage,
respectively.

On AIX, COMP-1 and COMP-2 data items are represented in IEEE format if the
FLOAT(NATIVE) compiler option is in effect. See “FLOAT” on page 165 for additional
information.

A PICTURE clause is not allowed in the data description of floating-point data items,
but you can provide an initial value using a floating-point literal in the VALUE clause:
ð5 Compute-result Usage Comp-1 Value ð6.23E-24.

The characteristics of conversions between floating-point format and other number


formats are discussed in the next section, “Data Format Conversions” on page 35.

Floating-point format is well suited for containing arithmetic operands and results and
for maintaining the highest level of accuracy in arithmetic.

For complete information on the data descriptions for numeric data, see IBM COBOL
Language Reference.

Figure 7. Internal Representation of Numeric Items—Binary Data Type


Numeric PICTURE and USAGE and Optional
Type SIGN Clause Value Internal Representation
Binary PIC S9999 BINARY + 1234 ð4 D2
COMP - 1234 FB 2E
COMP-4
COMP-5 + 1234 ð4 D2
- 1234 FB 2E
PIC 9999 BINARY 1234 ð4 D2
COMP
COMP-4
COMP-5 1234 ð4 D2

Chapter 3. Numbers and Arithmetic 33


How COBOL Stores Your Numbers

Figure 8. Internal Representation of Numeric Items—Native Data Types. This table assumes that
the CHAR(NATIVE) and FLOAT(NATIVE) compiler options are in effect.
Numeric PICTURE and USAGE and Optional
Type SIGN Clause Value Internal Representation
External PIC S9999 DISPLAY + 1234 31 32 33 34
Decimal - 1234 31 32 33 74
1234 31 32 33 34
PIC 9999 DISPLAY 1234 31 32 33 34
PIC S9999 DISPLAY + 1234 31 32 33 34
SIGN LEADING - 1234 71 32 33 34
PIC S9999 DISPLAY + 1234 2B 31 32 33 34
SIGN LEADING SEPARATE - 1234 2D 31 32 33 34
PIC S9999 DISPLAY + 1234 31 32 33 34 2B
SIGN TRAILING SEPARATE - 1234 31 32 33 34 2D
Internal PIC S9999 PACKED-DECIMAL + 1234 ð1 23 4C
Decimal COMP-3 - 1234 ð1 23 4D
PIC 9999 PACKED-DECIMAL 1234 ð1 23 4F
COMP-3
Internal COMP-1 + 1234 44 9A 4ð ðð
Floating - 1234 C4 9A 4ð ðð
Point
Internal COMP-2 + 1234 4ð 93 48 ðð ðð ðð ðð ðð
Floating - 1234 Cð 93 48 ðð ðð ðð ðð ðð
Point
External PIC +9(2).9(2)E+99 DISPLAY + 1234 2B 31 32 2E 33
Floating 34 45 2B 3ð 32
Point
- 1234 2D 31 32 2E 33
34 45 2B 3ð 32

34 COBOL Set for AIX Programming Guide


Data Format Conversions

Figure 9. Internal Representation of Numeric Items—System/390 Host Data Types. This table
assumes that the CHAR(EBCDIC) and FLOAT(HEX) compiler options are in effect.
Numeric PICTURE and USAGE and Optional
Type SIGN Clause Value Internal Representation
External PIC S9999 DISPLAY + 1234 F1 F2 F3 C4
Decimal - 1234 F1 F2 F3 D4
1234 F1 F2 F3 C4
PIC 9999 DISPLAY 1234 F1 F2 F3 F4
PIC S9999 DISPLAY + 1234 C1 F2 F3 F4
SIGN LEADING - 1234 D1 F2 F3 F4
PIC S9999 DISPLAY + 1234 4E F1 F2 F3 F4
SIGN LEADING SEPARATE - 1234 6ð F1 F2 F3 F4
PIC S9999 DISPLAY + 1234 F1 F2 F3 F4 4E
SIGN TRAILING SEPARATE - 1234 F1 F2 F3 F4 6ð
Internal PIC S9999 PACKED-DECIMAL + 1234 ð1 23 4C
Decimal COMP-3 - 1234 ð1 23 4D
PIC 9999 PACKED-DECIMAL 1234 ð1 23 4F
COMP-3
Internal COMP-1 + 1234 43 4D 2ð ðð
Floating - 1234 C3 4D 2ð ðð
Point
Internal COMP-2 + 1234 43 4D 2ð ðð ðð ðð ðð ðð
Floating - 1234 C3 4D 2ð ðð ðð ðð ðð ðð
Point
External PIC +9(2).9(2)E+99 DISPLAY + 1234 4E F1 F2 4B F3
Floating F4 C5 4E Fð F2
Point
- 1234 6ð F1 F2 4B F3
F4 C5 4E Fð F2

Data Format Conversions


When the code in your program involves the interaction of items with different data
formats, the compiler converts these items:
Ÿ Temporarily, for comparisons and arithmetic operations.
Ÿ Permanently, for assignment to the receiver in a MOVE, COMPUTE, and other
arithmetic statement.

When possible, the compiler performs the move to preserve the numeric “value” as
opposed to a direct digit-for-digit move. (For more information on truncation and pre-
dicting the loss of significant digits, refer to Appendix C, “Intermediate Results and
Arithmetic Precision” on page 471.)

Chapter 3. Numbers and Arithmetic 35


Data Format Conversions

Conversion Takes Time


Conversion generally requires additional storage and processing time because data is
moved to an internal work area and converted before the operation is performed. The
results might also have to be moved back into a work area and converted again.

Conversions and Precision


Conversions between fixed-point data formats (external decimal, packed decimal, and
binary) are completed without loss of precision, as long as the target field can contain
all the digits of the source operand.

Conversions Where Loss of Precision Is Possible


A loss of precision is possible in conversions between fixed-point data formats and
floating-point data formats (short floating-point, long floating-point, and external floating-
point). These conversions happen during arithmetic evaluations that have a mixture of
both fixed-point and floating-point operands. (Because fixed-point and external floating-
point items both have decimal characteristics, reference to fixed-point items in the fol-
lowing examples includes external floating-point items as well, unless stated otherwise.)

When converting from fixed-point to internal floating-point format, fixed-point numbers in


base 10 are converted to the numbering system used internally, base 16.

Although the compiler converts short form to long form for comparisons, zeros are used
for padding the short number.

When a USAGE COMP-1 data item is moved to a fixed-point data item with more than
6 digits, the fixed-point data item will receive only 6 significant digits, and the remaining
digits will be zero.

Conversions that Preserve Precision: If a fixed-point data item with 6 or fewer digits
is moved to a USAGE COMP-1 data item and then returned to the fixed-point data
item, the original value is recovered.

If a USAGE COMP-1 data item is moved to a fixed-point data item of 6 or more digits
and then returned to the USAGE COMP-1 data item, the original value is recovered.

If a fixed-point data item with 15 or fewer digits is moved to a USAGE COMP-2 data
item and then returned to the fixed-point data item, the original value is recovered.

If a USAGE COMP-2 data item is moved to a fixed-point (not external floating-point)


data item of 18 digits and then returned to the USAGE COMP-2 data item, the original
value is recovered.

Conversions that Result In Rounding: If a USAGE COMP-1 data item, a USAGE


COMP-2 data item, an external floating-point data item, or a floating-point literal is
moved to a fixed-point data item, rounding occurs in the low-order position of the target
data item.

36 COBOL Set for AIX Programming Guide


Numeric Class Test

If a USAGE COMP-2 data item is moved to a USAGE COMP-1 data item, rounding
occurs in the low-order position of the target data item.

If a fixed-point data item is moved to an external floating-point data item where the
PICTURE of the fixed-point data item contains more digit positions than the PICTURE
of the external floating-point data item, rounding occurs in the low-order position of the
target data item.

Sign Representation and Processing


Sign representation affects the processing and interaction of your numeric data.

Given X'sd', where s is the sign representation and d represents the digit, the valid
sign representations for external decimal (USAGE DISPLAY without the SIGN IS SEP-
ARATE clause) are :
Positive: 0, 1, 2, 3, 8, 9, A, and B.
Negative: 4, 5, 6, 7, C, D, E, and F.

When the CHAR(NATIVE) compiler option is in effect, signs generated internally are 3 for
positive and unsigned, and 7 for negative.

When the CHAR(EBCDIC) compiler option is in effect, signs generated internally are C
for positive, F for unsigned, and D for negative.

Given X'ds', where d represents the digit and s is the sign representation, the valid
sign representations for internal decimal (USAGE PACKED-DECIMAL) COBOL data
are:
Positive: A, C, E, and F.
Negative: B and D.

Signs generated internally are C for positive, F for unsigned, and D for negative.

Checking for Incompatible Data (Numeric Class Test)


The compiler assumes that the values you supply for a data item are valid for the item's
PICTURE and USAGE clauses and assigns the value you supply without checking for
validity. When an item is given a value that is incompatible with its data description,
references to that item in the PROCEDURE DIVISION will be undefined and your
results will be unpredictable.

Frequently, values are passed into your program and assigned to items that have
incompatible data descriptions for those values. For example, non-numeric data might
be moved or passed into a field in your program that is defined as a numeric item. Or,
perhaps a signed number is passed into a field in your program that is defined as an
unsigned number. In either case, these fields contain invalid data. Ensure that the
contents of a data item conforms to its PICTURE and USAGE clauses before using the
data item in any further processing steps.

Chapter 3. Numbers and Arithmetic 37


Doing Math

How to Do a Numeric Class Test


You can use the numeric class test to perform data validation. For example:
Linkage Section.
ð1 Count-x Pic 999.
.
.
Procedure Division Using Count-x.
If Count-x is numeric then display "Data is good"
.
.
The numeric class test checks the contents of a data item against a set of values that
are valid for the particular PICTURE and USAGE of the data item.

Performing Arithmetic
COBOL provides various language features to perform arithmetic:
Ÿ ADD, SUBTRACT, MULTIPLY, DIVIDE, and COMPUTE statements (discussed in
“COMPUTE and Other Arithmetic Statements”).
Ÿ Arithmetic expressions (discussed in “Arithmetic Expressions” on page 39).
Ÿ Intrinsic functions (discussed in “Numeric Intrinsic Functions” on page 39).

For the complete details of syntax and usage for COBOL language constructs, refer to
IBM COBOL Language Reference.

COMPUTE and Other Arithmetic Statements


The general practice is to use the COMPUTE statement for most arithmetic evaluations
rather than ADD, SUBTRACT, MULTIPLY, and DIVIDE statements. This is because
one COMPUTE statement can often be coded instead of several individual statements.

The COMPUTE statement assigns the result of an arithmetic expression to a data item:
Compute z = a + b / c \\ d - e
or to many data items:
Compute x y z = a + b / c \\ d - e

When to Use Other Arithmetic Statements


Some arithmetic might be more intuitive using the other arithmetic statements. For
example:
Add 1 To Increment
instead of:
Compute Increment = Increment + 1
Or,
Subtract Overdraft From Balance

38 COBOL Set for AIX Programming Guide


Doing Math

instead of:
Compute Balance = Balance - Overdraft
Or,
Add 1 To Increment-1, Increment-2, Increment-3
instead of:
Compute Increment-1 = Increment-1 + 1
Compute Increment-2 = Increment-2 + 1
Compute Increment-3 = Increment-3 + 1

You might also prefer to use the DIVIDE statement (with its REMAINDER phrase) for
division in which you want to process a remainder. The REM intrinsic function also
provides the ability to process a remainder. For an example of the REM function, see
“Mathematics” on page 43.

Arithmetic Expressions
In the examples of COMPUTE shown above, everything to the right of the equal sign
represents an arithmetic expression. Arithmetic expressions can consist of a single
numeric literal, a single numeric data item or a single intrinsic function reference. They
can also consist of several of these items connected by arithmetic operators. These
operators are evaluated in a hierarchic order:

Figure 10. Operator Evaluation


Operator Meaning Order of Evaluation
Unary + or - Algebraic Sign First
** Exponentiation Second
/ or * Division or multiplication Third
Binary + or - Addition or subtraction Last

Operators at the same level are evaluated from left to right; however, you can use
parentheses with these operators to change the order in which they are evaluated.
Expressions in parentheses are evaluated before any of the individual operators are
evaluated. Parentheses, necessary or not, make your program easier to read.

In addition to using arithmetic expressions in COMPUTE statements, you can also use
them in other places where numeric data items are allowed. For example, you can use
arithmetic expressions as comparands in relation conditions:
If (a + b) > (c - d + 5) Then...

Numeric Intrinsic Functions


Intrinsic functions can return an alphanumeric or numeric value.

Numeric intrinsic functions:


Ÿ Return a signed numeric value.

Chapter 3. Numbers and Arithmetic 39


Doing Math

Ÿ Are considered to be temporary numeric data items.


Ÿ Can be used only in the places in the language syntax where expressions are
allowed.
Ÿ Can save you time because you don't have to provide the arithmetic for the many
common types of calculations that these functions cover.
For more information on the practical application of intrinsic functions, including
examples of their usage, refer to “Intrinsic Function Examples.”

Types of Numeric Functions


Numeric functions are classified into these categories:
Integer Those that return an integer
Floating-Point Those that return a long floating-point value
Mixed Those that return an integer, a long floating-point value, or a fixed-
point number with decimal places, depending on the arguments

The numeric functions available in COBOL under these categories are described in IBM
COBOL Language Reference.

Nesting Functions and Arithmetic Expressions


Numeric functions can be nested; you can reference one function as the argument of
another. A nested function is evaluated independently of the outer function, except
when determining whether a mixed function should be evaluated with fixed-point or
floating-point procedures.

Because numeric functions and arithmetic expressions hold similar status syntactically
speaking, you can also nest an arithmetic expression as an argument to a numeric
function:
Compute x = Function Sum(a b (c / d))

In this example, there are only three function arguments: a, b and the arithmetic
expression (c / d).

ALL Subscripting and Special Registers


Two other useful features of intrinsic functions are the ALL subscript and special
registers:
Ÿ You can reference all the elements of an array as function arguments by using the
ALL subscript. This feature is used with tables, and examples of its use are shown
under “Processing Table Items (Intrinsic Functions)” on page 62.
Ÿ The integer-type special registers are allowed as arguments wherever integer argu-
ments are allowed.

Intrinsic Function Examples


You can use intrinsic functions to perform several different kinds of arithmetic, as out-
lined in Figure 11.

40 COBOL Set for AIX Programming Guide


Doing Math

Figure 11. Types of Arithmetic that Numeric Intrinsic Functions Handle


Number Han-
dling Date/Time Finance Mathematics Statistics
LENGTH CURRENT-DATE ANNUITY ACOS MEAN
MAX DATE-OF-INTEGER PRESENT-VALUE ASIN MEDIAN
MIN DATE-TO-YYYYMMDD ATAN MIDRANGE
NUMVAL DAY-OF-INTEGER COS RANDOM
NUMVAL-C DAY-TO-YYYYDDD FACTORIAL RANGE
ORD-MAX INTEGER-OF-DATE INTEGER STANDARD-DEVIATION
ORD-MIN INTEGER-OF-DAY INTEGER-PART VARIANCE
WHEN-COMPILED LOG
YEAR-TO-YYYY LOG10
MOD
REM
SIN
SQRT
SUM
TAN

The following examples and accompanying explanations show intrinsic functions in


each of the categories listed in the preceding table.

General Number-Handling: Suppose you want to find the maximum value of two
prices (represented as alphanumeric items with dollar signs), put this value into a
numeric field in an output record, and determine the length of the output record. You
could use NUMVAL-C (a function that returns the numeric value of an alphanumeric
string) and the MAX function to do this:
ð1 X Pic 9(2).
ð1 Price1 Pic x(8) Value "$8ððð".
ð1 Price2 Pic x(8) Value "$2ððð.
ð1 Output-Record.
ð5 Product-Name Pic x(2ð).
ð5 Product-Number Pic 9(9).
ð5 Product-Price Pic 9(6).
.
.
.
Procedure Division.
Compute Product-Price =
Function Max (Function Numval-C(Price1) Function Numval-C(Price2))
Compute X = Function Length(Output-Record)
Additionally, to ensure that the contents in Product-Name are in uppercase letters, you
could use the following statement:
Move Function Upper-case(Product-Name) to Product-Name

Date/Time: The following example shows how to calculate a due date that is 90 days
from today. The first eight characters returned by the CURRENT-DATE function repre-
sent the date in a 4-digit year, 2-digit month, and 2-digit day format (YYYYMMDD). In
the example, this date is converted to its integer value. Then 90 is added to this value,
and the integer is converted back to the YYYYMMDD format.

Chapter 3. Numbers and Arithmetic 41


Doing Math

ð1 YYYYMMDD Pic 9(8).


ð1 Integer-Form Pic S9(9).
.
.
.
Move Function Current-Date(1:8) to YYYYMMDD
Compute Integer-Form = Function Integer-of-Date(YYYYMMDD)
Add 9ð to Integer-Form
Compute YYYYMMDD = Function Date-of-Integer(Integer-Form)
Display 'Due Date: ' YYYYMMDD

Finance: Business investment decisions frequently require computing the present


value of expected future cash inflows to evaluate the profitability of a planned invest-
ment. The present value of money is its value today. The present value of an amount
that you expect to receive at a given time in the future is that amount which if invested
today at a given interest rate would accumulate to that future amount.

For example, assume a proposed investment of $1,000 produces a payment stream of


$100, $200, and $300 over the next three years, one payment per year respectively.
The following COBOL statements show how to calculate the present value of those
cash inflows at a 10% interest rate:
ð1 Series-Amt1 Pic 9(9)V99 Value 1ðð.
ð1 Series-Amt2 Pic 9(9)V99 Value 2ðð.
ð1 Series-Amt3 Pic 9(9)V99 Value 3ðð.
ð1 Discount-Rate Pic S9(2)V9(6) Value .1ð.
ð1 Todays-Value Pic 9(9)V99.
..
.
Compute Todays-Value =
Function
Present-Value(Discount-Rate Series-Amt1 Series-Amt2 Series-Amt3)

The ANNUITY function can be used in business problems that require you to determine
the amount of an installment payment (annuity) necessary to repay the principal and
interest of a loan. The series of payments is characterized by an equal amount each
period, periods of equal length, and an equal interest rate each period. The following
example shows how you could calculate the monthly payment required to repay a
$15,000 loan at 12% annual interest in three years (36 monthly payments, interest per
month = .12/12):
ð1 Loan Pic 9(9)V99.
ð1 Payment Pic 9(9)V99.
ð1 Interest Pic 9(9)V99.
ð1 Number-Periods Pic 99.
..
.
Compute Loan = 15ððð
Compute Interest = .12
Compute Number-Periods = 36
Compute Payment =
Loan \ Function Annuity((Interest / 12) Number-Periods)

42 COBOL Set for AIX Programming Guide


Fixed-Point vs. Floating-Point

Mathematics: The following COBOL statement demonstrates how intrinsic functions


can be nested, how arguments can be arithmetic expressions, and how previously
complex mathematical calculations can be simply performed:
Compute Z = Function Log(Function Sqrt (2 \ X + 1)) + Function Rem(X 2)
Here, the remainder of dividing X by 2 is found with an intrinsic function instead of
using a DIVIDE statement with a REMAINDER clause.

Statistics: Intrinsic functions also make calculating statistical information on data


easier. Assume you are analyzing various city taxes and want to calculate the mean,
median, and range (the difference between the maximum and minimum taxes):
ð1 Tax-S Pic 99v999 value .ð45.
ð1 Tax-T Pic 99v999 value .ð2.
ð1 Tax-W Pic 99v999 value .ð35.
ð1 Tax-B Pic 99v999 value .ð3.
ð1 Ave-Tax Pic 99v999.
ð1 Median-Tax Pic 99v999.
ð1 Tax-Range Pic 99v999.
..
.
Compute Ave-Tax = Function Mean(Tax-S Tax-T Tax-W Tax-B)
Compute Median-Tax = Function Median(Tax-S Tax-T Tax-W Tax-B)
Compute Tax-Range = Function Range (Tax-S Tax-T Tax-W Tax-B)

Fixed-Point versus Floating-Point Arithmetic


Many statements in your program might involve arithmetic. For example, each of the
following COBOL statements requires some kind of arithmetic evaluation:
Ÿ General arithmetic.
compute report-matrix-col = (emp-count \\ .5) + 1
add report-matrix-min to report-matrix-max giving report-matrix-tot
Ÿ Expressions and functions.
compute report-matrix-col = function sqrt(emp-count) + 1
compute whole-hours = function integer-part((average-hours) + 1)
Ÿ Arithmetic comparisons.
if report-matrix-col < function sqrt(emp-count) + 1
if whole-hours not = function integer-part((average-hours) + 1)

For each arithmetic evaluation in your program—whether it is a statement, an intrinsic


function, an expression, or some combination of these nested within each other—how
you code the arithmetic determines whether it will be floating-point or fixed-point evalu-
ation.

The following discussion explains when arithmetic and arithmetic comparisons are eval-
uated in fixed-point and floating-point. For details on the precision of arithmetic evalu-
ations, see Appendix C, “Intermediate Results and Arithmetic Precision” on page 471.

Chapter 3. Numbers and Arithmetic 43


Fixed-Point vs. Floating-Point

Floating-Point Evaluations
In general, if your arithmetic evaluation has either of the characteristics listed below, it
will be evaluated by the compiler in floating-point arithmetic:
Ÿ An operand or result field is floating-point.
A data item is floating-point if you code it as a floating-point literal, or if you define
it as USAGE COMP-1, USAGE COMP-2, or as external floating-point (USAGE
DISPLAY with a floating-point PICTURE).
An operand that is a nested arithmetic expression or a reference to numeric
intrinsic function results in floating-point when:
– An argument in an arithmetic expression results in floating-point.
– The function is a floating-point function.
– The function is a mixed-function with one or more floating-point arguments.
Ÿ An exponent contains decimal places.
This is true if you use a literal that contains decimal places, give the item a
PICTURE containing decimal places, or use an arithmetic expression or function
whose result has decimal places.
An arithmetic expression or numeric function yields a result with decimal places if
any operand or argument—excluding divisors and exponents—has decimal places.

Fixed-Point Evaluations
In general, if your arithmetic operation contains neither of the characteristics listed
above for floating-point, it will be evaluated by the compiler in fixed-point arithmetic. In
other words, your arithmetic evaluations will be handled by the compiler as fixed-point
only if all your operands are given in fixed-point, your result field is defined to be fixed-
point, and none of your exponents represent values with decimal places. Nested arith-
metic expression and function references must represent fixed-point values.

Arithmetic Comparisons (Relation Conditions)


If your arithmetic is a comparison (contains a relational operator), then the numeric
expressions being compared—whether they are data items, arithmetic expressions,
function references, or some combination of these—are really operands (comparands)
in the context of the entire evaluation. This is also true of abbreviated comparisons;
although one comparand might not explicitly appear, both are operands in the compar-
ison. For example, in the following statement:
if (a + d) = (b + e) and c
there are two comparisons: (a + d) = (b + e) and (a + d) = c. Although (a + d)
does not explicitly appear in the second comparison, it is nevertheless an operand in
that comparison (and thus, evaluation of (a + d) is influenced by the attributes of c).
Implicit Note: Implicit comparisons (no relational operator used) are not handled as a
unit—the two expressions being compared are treated separately as to whether they
will be evaluated in floating-point or fixed-point. In the following example we actually
have five arithmetic expressions that are evaluated independent of one another's attri-
butes, and then are compared to each other.

44 COBOL Set for AIX Programming Guide


Fixed-Point vs. Floating-Point

Thus, the rules outlined so far for determining whether your evaluation will be done in
fixed-point or floating-point arithmetic apply to your comparison statement as a unit.
evaluate (a + d)
when (b + e) thru c
when (f / g) thru (h \ i)
.
.
.
end-evaluate

Your comparison operation (and the evaluation of any arithmetic expressions nested in
your comparison) will be handled by the compiler as floating-point arithmetic if either of
your comparands is a floating-point value or resolves to a floating-point value.

Your comparison operation (and the evaluation of any arithmetic expressions nested in
your comparison) will be handled by the compiler as fixed-point arithmetic if both of
your comparands are fixed-point values or resolve to fixed-point values.

Examples of Fixed-Point and Floating-Point Evaluations


For the examples shown on page 43, if you define the data items in the following
manner:
ð1 employee-table.
ð5 emp-count pic 9(4).
ð5 employee-record occurs 1 to 1ððð times
depending on emp-count.
1ð hours pic +9(5)e+99.
..
.
ð1 report-matrix-col pic 9(3).
ð1 report-matrix-min pic 9(3).
ð1 report-matrix-max pic 9(3).
ð1 report-matrix-tot pic 9(3).
ð1 average-hours pic 9(3)v9.
ð1 whole-hours pic 9(4).
Ÿ These evaluations would be done in floating-point arithmetic:
compute report-matrix-col = (emp-count \\ .5) + 1
compute report-matrix-col = function sqrt(emp-count) + 1
if report-matrix-tot < function sqrt(emp-count) + 1
Ÿ These evaluations would be done in fixed-point arithmetic:
add report-matrix-min to report-matrix-max giving report-matrix-tot
compute report-matrix-max =
function max(report-matrix-max report-matrix-tot)
if whole-hours not = function integer-part((average-hours) + 1)

Chapter 3. Numbers and Arithmetic 45


Defining a Table

Chapter 4. Handling Tables


A table is a collection of data items that have the same description. It is the COBOL
equivalent to an array of elements. This chapter explains the concepts and coding
techniques necessary for defining, referencing, initializing, searching, and processing
table items, including both fixed-length and variable-length items.

Defining a Table (OCCURS Clause)


You could define table items as separate, consecutive entries in the DATA DIVISION,
but this practice has disadvantages. First, the code does not clearly show the unity of
the items. Second, you cannot take advantage of subscripting and indexing for easy
reference to the table elements. (See “Referring to an Item in a Table” on page 48 for
information on subscripting and indexing.)

Use the COBOL OCCURS clause in the DATA DIVISION entry to define a table, and
you do not need separate entries for repeated data items. The OCCURS clause also
supplies the information necessary for the use of subscripts or indexes. (For more
information on the format of the OCCURS clause, refer to IBM COBOL Language Ref-
erence).

To code a table, give the table a group name and define a subordinate item (the table
element) that is to be repeated n times:
ð1 table-name.
ð5 element-name OCCURS n TIMES.
.
. (subordinate items of the table element might follow)
.

The following figures show how to code tables:


Ÿ One-Dimensional Table—Figure 12 on page 47
Ÿ Two-Dimensional Table—Figure 13 on page 47
Ÿ Three-Dimensional Table—Figure 14 on page 48.

For all the tables, the table element definition (which includes the OCCURS clause) is
subordinate to the group item that contains the table; the OCCURS clause cannot
appear in a level-01 description.

To create tables of more than one dimension, use nested OCCURS clauses. Tables of
up to seven dimensions can be defined using this same method.

One Dimension
To create a one-dimensional table, use one OCCURS clause. For example:

46  Copyright IBM Corp. 1996, 1998


Defining a Table

COBOL Code Graphic Representation

SAMPLE-TABLE-ONE

01 SAMPLE-TABLE-ONE.
05 TABLE-COLUMN OCCURS 3 TIMES.
10 TABLE-ITEM-1 PIC X(2).
10 TABLE-ITEM-2 PIC X(1).

Figure 12. Coding a One-Dimensional Table

SAMPLE-TABLE-ONE is the group item that contains the table. TABLE-COLUMN names the
table element of a one-dimensional table that occurs three times.

Two Dimensions
To create a two-dimensional table, define a one-dimensional table in each occurrence
of another one-dimensional table. For example:

COBOL Code Graphic Representation

SAMPLE-TABLE-TWO

01 SAMPLE-TABLE-TWO.
05 TABLE-ROW OCCURS 2 TIMES.
10 TABLE-COLUMN OCCURS 3 TIMES.
15 TABLE-ITEM-1 PIC X(2).
15 TABLE-ITEM-2 PIC X(1).

Figure 13. Coding a Two-Dimensional Table

SAMPLE-TABLE-TWO is the name of a two-dimensional table. TABLE-ROW is an element of


a one-dimensional table that occurs two times. TABLE-COLUMN is an element of a two-
dimensional table that occurs three times in each occurrence of TABLE-ROW.

Three Dimensions
To create a three-dimensional table, define a one-dimensional table in each occurrence
of another one-dimensional table, which is itself contained in each occurrence of
another one-dimensional table. For example:

Chapter 4. Handling Tables 47


Referring to a Table Item

Graphic Representation
COBOL Code
SAMPLE-TABLE-THREE

01 SAMPLE-TABLE-THREE.
05 TABLE-DEPTH OCCURS 2 TIMES.
10 TABLE-ROW OCCURS 2 TIMES.
15 TABLE-COLUMN OCCURS 3 TIMES.
20 TABLE-ITEM-1 PIC X(2).
20 TABLE-ITEM-2 PIC X(1).

Figure 14. Coding a Three-Dimensional Table

In SAMPLE-TABLE-THREE, TABLE-DEPTH is an element of a one-dimensional table that


occurs two times. TABLE-ROW is an element of a two-dimensional table that occurs two
times within each occurrence of TABLE-DEPTH. TABLE-COLUMN is an element of a three-
dimensional table that occurs three times within each occurrence of TABLE-ROW.

Referring to an Item in a Table


A table element has a collective name, but the individual occurrences within it do not
have unique data-names. To refer to them, use the data-name of the table element,
together with the occurrence number, called a subscript, of the desired item within the
element.

The technique of supplying the occurrence number of individual table elements is called
subscripting. See page 48. A related technique, called subscripting using index-names
(indexing) is also available for table references.

An index is a symbol used to locate an item in a table. An index differs from a sub-
script in that an index is a value to be added to the address of a table to locate an item
(the displacement from the beginning of the table). See page 49.

Subscripting
The lowest possible subscript value is 1, which points to the first occurrence of the
table-element. In a one-dimensional table, the subscript corresponds to the row
number. In a two-dimensional table, the two subscripts correspond to the column and
row numbers. In a three-dimensional table, the three subscripts correspond to the
depth, column, and row numbers.

You can use a literal subscript or a data-name for a variable subscript.

48 COBOL Set for AIX Programming Guide


Referring to a Table Item

Literal Subscripts
The following are valid literal subscript references to SAMPLE-TABLE-THREE:
TABLE-COLUMN (2, 2, 1)
TABLE-COLUMN (2 2 1) (The spaces are required for subscripting.)

In the table reference TABLE-COLUMN (2, 2, 1), the first value (2) refers to the second
occurrence within TABLE-DEPTH, the second value (2) refers to the second occurrence
within TABLE-ROW, and the third value (1) refers to the first occurrence within
TABLE-COLUMN.

If a subscript is represented by a literal and the subscripted item is of fixed length, then
the compiler resolves the location of the subscripted data item within the table at
compile time.

Variable Subscripts
The following is a valid, variable subscript reference to SAMPLE-TABLE-TWO, (assuming
that SUB1 and SUB2 are data-names containing positive integer values within the range
of the table):
TABLE-COLUMN (SUB1 SUB2)

The data-name used as a variable subscript must be described as an elementary


numeric integer data item.

If a data-name is being used as a subscript or qualifier, it cannot itself be subscripted.

If a subscript is represented by a data-name, the code generated for the application


resolves the location at run time. The most efficient format for data used as a variable
subscript is COMPUTATIONAL (COMP) with a PICTURE size of less than five digits.

Relative Subscripts
In relative subscripting, the subscript can be incremented or decremented by a speci-
fied integer amount. Relative subscripting is valid with either literal or variable sub-
scripts. For example:
TABLE-COLUMN (SUB1 - 1, SUB2 + 3)

Subscripting Using Index-Names (Indexing)


You can refer to table elements by using a subscript, an index, or both. An index is a
displacement from the start of the table, based on the length of the table element.

To reference a table by an index:


1. Define the index-name for a table in the INDEXED BY clause of the OCCURS
clause in the table definition.
2. Choose direct or relative indexing (described below).
3. Initialize the index-name with a SET, PERFORM VARYING, or SEARCH ALL
statement before using it in a table reference.

Chapter 4. Handling Tables 49


Referring to a Table Item

4. Use the index in SET, SEARCH, SEARCH ALL, PERFORM VARYING, or rela-
tional condition statements.

How the Index Value Is Determined


The compiler determines the index of an entry using the following formula:

I = L * (S-1)

where:

I is the index value.


L is the length of a table entry.
S is the subscript (occurrence number) of an entry.

To be valid during execution, an index value must correspond to a table element occur-
rence of not less than 1 nor greater than the highest permissible occurrence number.
This restriction applies to both direct and relative indexing.

Direct Indexing
In direct indexing, the index-name is in the form of a displacement. The value con-
tained in the index is then calculated as the occurrence number minus 1, multiplied by
the length of the individual table entry.

For example:
ð5 TABLE-ITEM OCCURS 1ð INDEXED BY INX-A PIC X(8).

For the fifth occurrence of TABLE-ITEM, the binary value contained in INX-A is (5 - 1) * 8
= 32.

Relative Indexing
In relative indexing, the index-name is followed by a space, followed by a + or a -,
followed by another space, followed by an unsigned numeric literal. The literal is con-
sidered to be an occurrence number, and is converted to an index value before being
added to or subtracted from the index-name.

Relative Indexing Example: If you code indexing for SAMPLE-TABLE-THREE as follows:


ð1 SAMPLE-TABLE-THREE
ð5 TABLE-DEPTH OCCURS 3 TIMES INDEXED BY INX-A.
1ð TABLE-COLUMN OCCURS 4 TIMES INDEXED BY INX-B.
15 TABLE-ROW OCCURS 8 TIMES INDEXED BY INX-C PIC X(8).
a relative indexing reference to:
TABLE-ROW (INX-A + 1, INX-B + 2, INX-C - 1)
causes the following computation of the displacement:
(contents of INX-A) + (256 \ 1)
+ (contents of INX-B) + (64 \ 2)
+ (contents of INX-C) - (8 \ 1)

50 COBOL Set for AIX Programming Guide


Referring to a Table Item

That is,
Ÿ Each occurrence of TABLE-DEPTH is 256 characters in length.
Ÿ Each occurrence of TABLE-COLUMN is 64 characters in length.
Ÿ Each occurrence of TABLE-ROW is 8 characters in length.

More Ways to Use Index References


Ÿ An index can be modified using a PERFORM, SEARCH, or SET statement.
Ÿ To compare two different occurrences of a table element, use a direct indexing
reference together with a relative indexing reference, or use subscripting, which is
easier to read in your code.
Ÿ An index can be shared among different tables. That is, you can use the index
defined with one table to index another table if both table descriptions are identical.
To be identical, the tables must have the same number of occurrences, as well as
occurrences of the same length.
Ÿ Store index values in index data items you define with the USAGE IS INDEX
clause. Use the SET statement to assign to an index the value that you stored in
the index data item.
For example, when you read records to load a variable-length table, you can store
the index value of the last record in a data item defined as USAGE IS INDEX.
Then, when you use the table index to look through or process the variable-length
table, you can test for the end of the table by comparing the current index value
with the index value of the last record you stored in the index data item.
Because you're comparing a physical displacement, you can use index data items
only in SEARCH and SET statements or for comparisons with indexes or other
index data items. You cannot use index data items as subscripts or indexes.

Referring to a Substring of a Table Item


Both reference modification and subscripting can be coded for a table element in the
same statement. For example, if you define a table like this:
ð1 ANY-TABLE.
ð5 TABLE-ELEMENT PIC X(1ð)
OCCURS 3 TIMES
VALUE "ABCDEFGHIJ".
the statement
MOVE "??" TO TABLE-ELEMENT ( 1 ) ( 3 : 2 )
will move the value "??" into table element number 1, beginning at character position
3, for a length of 2.

Chapter 4. Handling Tables 51


Putting Values into a Table

So, if ANY-TABLE looked ANY-TABLE would look


like this before the change: like this after the change:
┌──────────┐ ┌──────────┐
│ABCDEFGHIJ│ │AB??EFGHIJ│
├──────────┤ ├──────────┤
│ABCDEFGHIJ│ │ABCDEFGHIJ│
├──────────┤ ├──────────┤
│ABCDEFGHIJ│ │ABCDEFGHIJ│
└──────────┘ └──────────┘

Putting Values into a Table


Use one of these methods to put values in a table:
Ÿ Load the table dynamically.
Ÿ Initialize the table (INITIALIZE statement).
Ÿ Assign values when you define the table (VALUE clause).

Loading the Table Dynamically


If the initial values of your table are different with each execution of your program, the
table can be defined without initial values, and the changed values can be read into the
table before your program refers to the table.

To load a table, use:


Ÿ The PERFORM . . . VARYING statement.
Ÿ Either subscripting or indexing.

When reading data to load your table, test to make sure that the data does not exceed
the space allocated for the table. Use a named value giving the item count, rather than
using a literal. Then, if you make the table bigger, you need to change only one value,
instead of all references to a literal.

Initializing the Table (INITIALIZE Statement)


You can also load your table with a value during execution with the INITIALIZE state-
ment. For example, to fill a table with 3s:
INITIALIZE TABLE-ONE REPLACING NUMERIC DATA BY 3.

The INITIALIZE statement cannot load a variable-length table (one that was defined
using OCCURS DEPENDING ON).

Assigning Values When You Define the Table (VALUE Clause)


If your table contains stable values (for example a table that contains the days and
months of the year), set the specific values your table holds when you define it.

Define static values in Working-Storage in one of the these ways:


Ÿ Initialize each table item individually.

52 COBOL Set for AIX Programming Guide


Putting Values into a Table

Ÿ Initialize an entire table at the 01 level.


Ÿ Initialize all occurrences of a given table element to the same value.

Initializing Each Table Item Individually


Ÿ Describe the table storage area by arranging subordinate data description entries,
setting the initial value of each subordinate entry in a VALUE clause.
Ÿ Code a REDEFINES entry to describe the table as a record that contains a
repeating subordinate entry, defined with an OCCURS clause.

For an example of this method, see "Error Flag Table” and “Error Message Table” in
Figure 15 on page 54.

This technique is practical only for small tables. To initialize larger tables, use MOVE,
PERFORM, or INITIALIZE statements, as described above.

Initializing a Table at the 01 Level


Code a level-01 record and assign to it, through the VALUE clause, the contents of the
whole table. Then, in a subordinate level data item, use an OCCURS clause to define
the individual table items.

For example:
ð1 TABLE-ONE VALUE "1234".
ð5 TABLE-TWO OCCURS 4 TIMES PIC X.

Initializing a Variable-Size Table: A VALUE clause can also be present on a group


item that contains an OCCURS clause with the DEPENDING ON option. Each subordi-
nate structure that contains the DEPENDING ON option is initialized using the
maximum number of occurrences. If the entire table is defined with the DEPENDING
ON option, all the elements are initialized using the maximum defined value of the
DEPENDING ON object.

In both cases, if the ODO object has a VALUE clause, it is logically initialized after the
ODO subject has been initialized. For example:
ð1 TABLE-THREE VALUE "3ABCDE".
ð5 X PIC 9.
ð5 Y OCCURS 5 TIMES
DEPENDING ON X PIC X.
causes Y(1) to be initialized to A, Y(2) to B,... Y(5) to E, and finally the object of the
ODO (X) is initialized to 3. Any subsequent reference to TABLE-THREE (such as
DISPLAY) would refer to the first 3 elements, Y(1) through Y(3).

Initializing All Occurrences of a Table Element


You can use the VALUE clause on a table element to initialize the element to the indi-
cated value.

As an example, this code:

Chapter 4. Handling Tables 53


Putting Values into a Table

ð1 T2.
ð5 T-OBJ PIC 9 VALUE 3.
ð5 T OCCURS 5 TIMES DEPENDING ON T-OBJ.
1ð X PIC XX VALUE "AA".
1ð Y PIC 99 VALUE 19.
1ð Z PIC XX VALUE "BB".
causes all the X elements (1 through 5) to be initialized to AA, all the Y elements (1
through 5) to be initialized to 19, and all the Z elements (1 through 5) to be initialized to
BB. T-OBJ is then set to 3.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\\ E R R O R F L A G T A B L E \\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ð1 Error-Flag-Table Value Spaces.
88 No-Errors Value Spaces.
ð5 Type-Error Pic X.
ð5 Shift-Error Pic X.
ð5 Home-Code-Error Pic X.
ð5 Work-Code-Error Pic X.
ð5 Name-Error Pic X.
ð5 Initials-Error Pic X.
ð5 Duplicate-Error Pic X.
ð5 Not-Found-Error Pic X.
ð5 Address-Error Pic X.
ð5 City-Error Pic X.
ð5 State-Error Pic X.
ð5 Zipcode-Error Pic X.
ð5 Home-Phone-Error Pic X.
ð5 Work-Phone-Error Pic X.
ð5 Home-Junction-Error Pic X.
ð5 Work-Junction-Error Pic X.
ð5 Driving-Status-Error Pic X.
ð1 Filler Redefines Error-Flag-Table.
ð5 Error-Flag Occurs 17 Times
Indexed By Flag-Index Pic X.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\\ E R R O R M E S S A G E T A B L E \\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ð1 Error-Message-Table.
ð5 Filler Pic X(25) Value
"Transaction Type Invalid".
ð5 Filler Pic X(25) Value
"Shift Code Invalid".
ð5 Filler Pic X(25) Value
"Home Location Code Inval.".

Figure 15 (Part 1 of 2). Table with Static Values Defined for Every Table Element

54 COBOL Set for AIX Programming Guide


Putting Values into a Table

ð5 Filler Pic X(25) Value


"Work Location Code Inval.".
ð5 Filler Pic X(25) Value
"Last Name - Blanks".
ð5 Filler Pic X(25) Value
"Initials - Blanks".
ð5 Filler Pic X(25) Value
"Duplicate Record Found".
ð5 Filler Pic X(25) Value
"Commuter Record Not Found".
ð5 Filler Pic X(25) Value
"Address - Blanks".
ð5 Filler Pic X(25) Value
"City - Blanks".
ð5 Filler Pic X(25) Value
"State Is Not Alphabetic".
ð5 Filler Pic X(25) Value
"ZipCode Is Not Numeric".
ð5 Filler Pic X(25) Value
"Home Phone Number Error".
ð5 Filler Pic X(25) Value
"Work Phone Number Error".
ð5 Filler Pic X(25) Value
"Home Junction Is Blanks".
ð5 Filler Pic X(25) Value
"Work Junction Is Blanks".
ð5 Filler Pic X(25) Value
"Driving Status Invalid".
ð1 Filler Redefines Error-Message-Table.
ð5 Error-Message Occurs 17 Times
Indexed By Message-Index Pic X(25).

Figure 15 (Part 2 of 2). Table with Static Values Defined for Every Table Element

Processing a Table Using Subscripting and PERFORM...VARYING


The procedure shown in Figure 16 processes the entire table shown in Figure 15 on
page 54, using subscripting and the PERFORM...VARYING statement.

Perform
Varying Sub From 1 By 1
Until No-Errors
If Error-Flag (Sub) = Error-On
Move Space To Error-Flag (Sub)
Move Error-Message (Sub) To Print-Message
Perform 26ð-Print-Report
End-If
End-Perform

Figure 16. Processing the Sample Table, Using Subscripting

Chapter 4. Handling Tables 55


Variable-Length Tables

Processing a Table Using Indexing


The procedure shown in Figure 17 processes the entire table, using indexing.

Set Flag-Index To 1
Perform Until No-Errors
Search Error-Flag
When Error-Flag (Flag-Index) = Error-On
Move Space To Error-Flag (Flag-Index)
Set Message-Index To Flag-Index
Move Error-Message (Message-Index) To
Print-Message
Perform 26ð-Print-Report
End-Search
End-Perform

Figure 17. Processing the Sample Table, Using Indexing

Creating Variable-Length Tables (DEPENDING ON Clause)


If you don't know before execution how many occurrences of a table element there are,
you need to set up a variable-length table definition. To do this, use the OCCURS
DEPENDING ON (ODO) clause. For example:
X OCCURS 1 TO 1ð TIMES DEPENDING ON Y
X is the ODO subject, Y is the ODO object.

The cases to consider when using the ODO clause are:


Ÿ ODO object and subject are contained within the same group item, and that item is
a sending field or that item is a receiving field.
Ÿ ODO object is outside of the group item that contains the subject.

ODO Object and Subject Contained in Group Item

Whether Maximum Length or Actual Length Is Used


If a group item is not complex ODO, contains both the subject and object of the ODO,
and it is a receiving item, then the maximum length of the item is used. In this situation
it is not necessary to set the value of the ODO object before a reference is made.

If the receiving item is followed by a data-item which is in the same record but is not
subordinate to the receiver (is complex ODO), then the actual length is used and a
compiler message is issued to inform you that the actual length, not the maximum, will
be used. In this situation it is necessary to set the value of the ODO object before any
reference to the item.

The following example contrasts how the length is determined for a group item whose
subordinate items contain an OCCURS clause with the DEPENDING ON option and

56 COBOL Set for AIX Programming Guide


Variable-Length Tables

the object of that DEPENDING ON option, depending on whether it is the sending


group item or the receiving group item.
WORKING-STORAGE SECTION.
ð1 MAIN-AREA.
ð3 REC-1.
ð5 FIELD-1 PIC S9.
ð5 FIELD-2 OCCURS 1 TO 5 TIMES
DEPENDING ON FIELD-1 PIC X(ð5).

ð1 REC-2.
ð5 REC-2-DATA PIC X(5ð).

Sending Group Item


If you want to move REC-1 to REC-2, the length of REC-1 is determined immediately prior
to the MOVE, using the current value in FIELD-1. If the contents of FIELD-1 do not
conform to its PICTURE, that is, if FIELD-1 does not contain an external decimal item,
the result is unpredictable. (See Chapter 3, “Numbers and Arithmetic” on page 29 for
more information on data and sign representation).

As you can see, you must be sure that you have the correct value placed in the ODO
object before the MOVE is initiated.

Receiving Group Item


If you want to do a MOVE to REC-1, the length of REC-1, for the purpose of the MOVE,
is determined using the maximum number of occurrences. In this example, that would
be 5 occurrences of FIELD-2 plus FIELD-1 for a length of 26.

In this case, the ODO object (FIELD-1) need not be set before referencing REC-1 as a
receiving item. However, the sending field's ODO object needs to be set to a valid
numeric value between 1 and 5 for the ODO object of the receiving field to be validly
set by the move.

Another Record Makes this Complex ODO


However, if REC-2 were followed by a data item which is in the same record but is not
subordinate to REC-2, then the actual length of REC-2 is used and the ODO object must
be set before the reference.

In the following example, REC-1 is followed by REC-2.


ð1 MAIN-AREA
ð3 REC-1.
ð5 FIELD-1 PIC S9.
ð5 FIELD-3 PIC S9.
ð5 FIELD-2 OCCURS 1 TO 5 TIMES
DEPENDING ON FIELD-1 PIC X(ð5).
ð3 REC-2.
ð5 FIELD-4 OCCURS 1 TO 5 TIMES
DEPENDING ON FIELD-3 PIC X(ð5).

Chapter 4. Handling Tables 57


Variable-Length Tables

If you do a MOVE to REC-1 in this case, the actual length of REC-1 is calculated imme-
diately prior to the move using the current value of the ODO object (FIELD-1), and a
compiler message is issued letting you know that the actual length, instead of the
maximum length, was used. This case requires that you set the value of the ODO
object (FIELD-1) prior to using the item as a receiving field.

ODO Object outside the Group


You must ensure that the object of the OCCURS DEPENDING ON clause contains a
value that correctly specifies the current number of occurrences of the table elements.
Figure 18 shows how to define a variable-length table.

DATA DIVISION.
FILE SECTION.

FD LOCATION-FILE.
ð1 LOCATION-RECORD.
ð5 LOC-CODE PIC XX.
ð5 LOC-DESCRIPTION PIC X(2ð).
ð5 FILLER PIC X(58).

WORKING-STORAGE SECTION.
ð1 FLAGS.
ð5 LOCATION-EOF-FLAG PIC X(5) VALUE SPACE.
88 LOCATION-EOF VALUE "FALSE".
ð1 MISC-VALUES.
ð5 LOCATION-TABLE-LENGTH PIC 9(3) VALUE ZERO.
ð5 LOCATION-TABLE-MAX PIC 9(3) VALUE 1ðð.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\\ L O C A T I O N T A B L E \\\
\\\ FILE CONTAINS LOCATION CODES. \\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ð1 LOCATION-TABLE.
ð5 LOCATION-CODE OCCURS 1 TO 1ðð TIMES
DEPENDING ON LOCATION-TABLE-LENGTH PIC X(8ð).

Figure 18. Defining a Variable-Length Table

Figure 19 shows a do-until structure used to control loading of a variable-length table.


When initialization is complete, LOCATION-TABLE-LENGTH will contain the subscript of the
last item in the table. (This variable-length table is defined in Figure 18.)

58 COBOL Set for AIX Programming Guide


Variable-Length Tables

Perform Test After


Varying Location-Table-Length From 1 By 1
Until Location-EOF
Or Location-Table-Length = Location-Table-Max
Move Location-Record To
Location-Code (Location-Table-Length)
Read Location-File
At End Set Location-EOF To True
End-Read
End-Perform

Figure 19. Loading a Variable-Length Table

Two factors that affect the successful manipulation of variable-length records are the
correct calculation of records lengths and the conformance of the data in the
OCCURS...DEPENDING ON object to its picture. If you are using variable-length group
items in either a READ...INTO or WRITE...FROM statement, in conjunction with an
OCCURS...DEPENDING ON statement, make sure that the receiver or intermediate
field length is correct. The length of the variable portions of a group item is the product
of the object of the DEPENDING ON option and the length of the subject of the
OCCURS clause.

If the content of the ODO object does not match its PICTURE clause, the program may
abnormally terminate. See Chapter 3, “Numbers and Arithmetic” on page 29 for more
information on data and sign representation.

Complex OCCURS DEPENDING ON


Complex OCCURS DEPENDING ON is supported as an extension to the COBOL 85
Standard.

The basic forms of complex ODO permitted by the compiler are:


Ÿ A data item described by an OCCURS clause with the DEPENDING ON option is
followed by a non-subordinate element or group (variably-located item).
Ÿ A data item described by an OCCURS clause with the DEPENDING ON option is
followed by a non-subordinate data item described by an OCCURS clause with the
DEPENDING ON option (variably-located table).
Ÿ A data item described by an OCCURS clause with the DEPENDING ON option is
nested within another data item described by an OCCURS clause with the
DEPENDING ON option (table with variable-length elements).
Ÿ Index-name for a table with variable-length elements.

Complex ODO is tricky to use and can make maintaining your code more difficult. If
you choose to use it in order to save disk space, follow the guidelines in Appendix D,
“Complex OCCURS DEPENDING ON” on page 479.

Chapter 4. Handling Tables 59


Searching a Table

Searching a Table (SEARCH Statement)


COBOL provides two search techniques for tables: serial and binary.

To perform serial searches:


Ÿ Use the PERFORM . . . VARYING statement with subscripting or indexing (dis-
cussed in “Creating Variable-Length Tables (DEPENDING ON Clause)” on
page 56).
Ÿ Use SEARCH and indexing.

To perform binary searches, use indexing and the SEARCH ALL statement.

The following discussion assumes you are familiar with the format of the SEARCH and
SEARCH ALL statements. If you are not, see IBM COBOL Language Reference.

Serial Search
Use the SEARCH statement to perform a serial search beginning at the current index
setting. To modify the index setting, use the SET statement.

The conditions in the WHEN option are evaluated in the order in which they are written.
Ÿ If none of the conditions is satisfied, the index is increased to correspond to the
next table element, and the WHEN conditions are evaluated again.
Ÿ If one of the WHEN conditions is satisfied, the search ends; the index remains
pointing to the table element that satisfied the condition.
Ÿ If the entire table has been searched and no conditions were met, the AT END
imperative statement is executed, if there is one. If you do not use the AT END
option, control passes to the next statement in your program.

Searching More than One Level of a Table


Only one level of a table (a table element) can be referenced with each SEARCH state-
ment. SEARCH statements can be nested to search multiple levels of a table.
However, SEARCH statements can be nested only if you delimit each nested SEARCH
statement with END-SEARCH. The WHEN condition must be followed by an imper-
ative statement; the SEARCH statement is an imperative statement only when it is
delimited by END-SEARCH.

Speeding Up Your Search


It is important to know if the found condition comes after some intermediate point in the
table element. You can speed up the SEARCH by using the SET statement to set the
index to begin the search after that point.

Arranging the table so that the data used most often is at the beginning also enables
more efficient serial searching. If the table is large and is pre-sorted, a binary search is
more efficient. See “Binary Search (SEARCH ALL Statement)” on page 61 more infor-
mation on binary searches.

60 COBOL Set for AIX Programming Guide


Searching a Table

Serial Search Example


ð1 TABLE-ONE.
ð5 TABLE-ENTRY1 OCCURS 1ð TIMES
INDEXED BY TE1-INDEX.
1ð TABLE-ENTRY2 OCCURS 1ð TIMES
INDEXED BY TE2-INDEX.
15 TABLE-ENTRY3 OCCURS 5 TIMES
ASCENDING KEY IS KEY1
INDEXED BY TE3-INDEX.
2ð KEY1 PIC X(5).
2ð KEY2 PIC X(1ð).
.
.
PROCEDURE DIVISION.
.
.
SET TE1-INDEX TO 1
SET TE2-INDEX TO 4
SET TE3-INDEX TO 1
MOVE "A1234" TO KEY1 (TE1-INDEX, TE2-INDEX, TE3-INDEX + 2)
MOVE "AAAAAAAAðð" TO KEY2 (TE1-INDEX, TE2-INDEX, TE3-INDEX + 2)
SEARCH TABLE-ENTRY3
AT END
MOVE 4 TO RETURN-CODE
WHEN TABLE-ENTRY3(TE1-INDEX, TE2-INDEX, TE3-INDEX)
= "A1234AAAAAAAAðð"
MOVE ð TO RETURN-CODE
END-SEARCH

Values after execution:


TE1-INDEX = 1
TE2-INDEX = 4
TE3-INDEX points to the TABLE-ENTRY3
that equals "A1234AAAAAAAAðð"
RETURN-CODE = ð

Binary Search (SEARCH ALL Statement)


When you use SEARCH ALL to perform a binary search, you do not need to set the
index before you begin. The index used is always the one associated with the first
index-name in the OCCURS clause, and it varies during execution to maximize the
search efficiency.

To use the SEARCH ALL statement, your table must be ordered on the key or keys
coded in the OCCURS clause. You can use any key in the WHEN condition, but all
preceding data-names in the KEY option must also be tested. The test must be an
equal-to condition, and the KEY data-name must be either the subject of the condition
or the name of a conditional variable with which the tested condition-name is associ-
ated. The WHEN condition can also be a compound condition, formed from one of the
simple conditions listed above, with AND as the only logical connective. The KEY and
its object of comparison must be compatible, as stated in the relation test rules.

Chapter 4. Handling Tables 61


Referencing All Table Items

Binary Search Example


For example, a table defined like this:
ð1 TABLE-A.
ð5 TABLE-ENTRY OCCURS 9ð TIMES
ASCENDING KEY-1, KEY-2
DESCENDING KEY-3
INDEXED BY INDX-1.
1ð PART-1 PIC 99.
1ð KEY-1 PIC 9(5).
1ð PART-2 PIC 9(6).
1ð KEY-2 PIC 9(4).
1ð PART-3 PIC 9(18).
1ð KEY-3 PIC 9(5).

can be searched using the following instructions:


SEARCH ALL TABLE-ENTRY
AT END
PERFORM NOENTRY
WHEN KEY-1 (INDX-1) = VALUE-1 AND
KEY-2 (INDX-1) = VALUE-2 AND
KEY-3 (INDX-1) = VALUE-3
MOVE PART-1 (INDX-1) TO OUTPUT-AREA
END-SEARCH

These instructions will execute a search on the given table that contains 90 elements of
40 bytes and 3 keys. The primary and secondary keys (KEY-1 and KEY-2) are in
ascending order, but the least significant key (KEY-3) is in descending order. If an entry
is found in which three keys are equal to the given values (VALUE-1, VALUE-2, and
VALUE-3), PART-1 of that entry will be moved to OUTPUT-AREA. If the matching keys are
not found in any of the entries in TABLEA, the NOENTRY routine is performed.

Processing Table Items (Intrinsic Functions)


You can process alphanumeric or numeric table items using intrinsic functions as long
as the table item's data description is compatible with the function's argument require-
ments. The IBM COBOL Language Reference describes the required data formats for
the arguments of the various intrinsic functions.

Use a subscript or index to reference an individual data item as a function argument.


Assuming Table-One is a 3x3 array of numeric items, you can find the square root of
the middle element with a statement such as:
Compute X = Function Sqrt(Table-One(2,2))

Processing Multiple Table Items (ALL Subscript)


You might often need to process the data in tables iteratively. For intrinsic functions
that accept multiple arguments, you can use the ALL subscript to reference all the
items in the table or single dimension of the table. The iteration is handled automat-
ically, making your code shorter and simpler.

62 COBOL Set for AIX Programming Guide


Efficient Table Coding

Example 1
This example sums a cross section of Table-Two:
Compute Table-Sum = FUNCTION SUM (Table-Two(ALL, 3, ALL)))
Assuming that Table2 is a 2x3x2 array, the above statement would cause these ele-
ments to be summed:
Table-Two(1,3,1)
Table-Two(1,3,2)
Table-Two(2,3,1)
Table-Two(2,3,2)

Example 2
This example computes values for all employees.
ð1 Employee-Table.
ð5 Emp-Count Pic s9(4) usage binary.
ð5 Emp-Record occurs 1 to 5ðð times
depending on Emp-Count.
1ð Emp-Name Pic x(2ð).
1ð Emp-Idme Pic 9(9).
1ð Emp-Salary Pic 9(7)v99.
.
.
Procedure Division.
Compute Max-Salary = Function Max(Emp-Salary(ALL))
Compute I = Function Ord-Max(Emp-Salary(ALL))
Compute Avg-Salary = Function Mean(Emp-Salary(ALL))
Compute Salary-Range = Function Range(Emp-Salary(ALL))
Compute Total-Payroll = Function Sum(Emp-Salary(ALL))

Example 3
Scalars and array arguments can be mixed for functions that accept multiple
arguments:
Compute Table-Median = Function Median(Arg1 Table-One(ALL))

Efficient Coding for Tables


For efficient table-handling, follow these suggestions:
Ÿ If the table is searched sequentially, put the data values most likely to satisfy the
search criteria at the beginning of a table.
Ÿ Use index-names instead of subscripts. This method is more efficient, but sub-
scripting might be easier to understand and maintain. Relative index references
are executed as fast as direct index references. For additional details, see
“Subscripting” on page 48 and “Subscripting Using Index-Names (Indexing)” on
page 49.
Ÿ Use binary (COMP) data items with 8 or fewer digits for subscripts and OCCURS
DEPENDING ON objects. Use fewer than five digits, if possible.
Ÿ Avoid referencing errors by coding subscript and index checks into your program.

Chapter 4. Handling Tables 63


Selecting Program Actions

Chapter 5. Selection and Iteration

Selection (IF and EVALUATE Statements)


Use control structures to:
Ÿ Choose program actions based on the outcome of a decision.
Ÿ Control looping in your program.

Selection is providing for different program actions depending on the tested value of
some data item or data items.

The IF and EVALUATE statements are COBOL selection constructs. The testing of a
data item or data items is done in both of these statements by means of a conditional
expression.

IF Statement
Use IF . . . ELSE to code a choice between two processing actions. (The word THEN is
optional in a COBOL program.) For example:
IF condition-p
statement-1
ELSE
statement-2
END-IF

IF Statement with a Null Branch


There are two ways you can code an IF statement when one of the processing choices
is no action. Because the ELSE clause is optional, you can code the following:
IF condition-q
statement-1
END-IF
This coding is suitable for simple programming cases. However, if the logic in your
program is complex (for example, you have nested IF constructs with action for only
one of the processing choices), you might want to use the ELSE clause and code the
null branch of the IF statement with the CONTINUE statement:
IF condition-q
statement-1
ELSE
CONTINUE
END-IF

Nested IF Statements
When an IF statement has another IF statement as one of its possible processing
branches, these IF statements are said to be nested IFs. Theoretically, there is no limi-
tation on the depth of nested IF statements. However, when the program has to test a

64  Copyright IBM Corp. 1996, 1998


Selecting Program Actions

variable for more than two values, EVALUATE is the better choice. (For more informa-
tion, see “EVALUATE statement” on page 66).

Use nested IF statements sparingly; the logic can be difficult to follow, although proper
indentation helps.

Logic of a Nested IF Statement: The following is pseudocode for a nested IF


statement:
IF condition-p
IF condition-q
statement-1
ELSE
statement-2
END-IF
statement-3
ELSE
statement-4
END-IF

Here an IF is nested, along with a sequential structure, in one branch of another IF.
The structure for this logic is shown in Figure 20 on page 65.

When you code a structure like the one in Figure 20, the END-IF closing the inner
nested IF becomes very important. Use END-IF instead of a period, because a period
would end the outer IF structure as well.

Statement 1 Statement 3
True

condition-q
True

condition-p False Statement 2

False Statement 4

Figure 20. Control Logic Structure for Nested IF Statements

Chapter 5. Selection and Iteration 65


Selecting Program Actions

Good Coding Practice for Nested IFs: When you nest IF statements, readability and
debugging will be easier if each IF statement has its own END-IF scope-terminator and if
you use proper indentation. For example:
IF A = 1
IF B = 2
PERFORM C
ELSE PERFORM D.

The ELSE PERFORM D phrase is interpreted as the ELSE phrase of the last previous IF
which is, IF B = 2. If this is the intent, you can make the logic clearer with the fol-
lowing coding:
IF A = 1
IF B = 2
PERFORM C
ELSE
PERFORM D
END-IF
END-IF

If the intent is to have ELSE PERFORM D depend on IF A = 1, the code would look like
this:
IF A = 1
IF B = 2
PERFORM C
END-IF
ELSE
PERFORM D
END-IF

EVALUATE statement
The EVALUATE statement is an expanded form of the IF statement. An IF statement
allows your program to act on one of two conditions: true or false. If you had three or
more possible conditions instead of just two, and you were limited to using IF state-
ments, you would need to nest or cascade the IF statements. Such nested IF state-
ments are a common source of logic errors and debugging problems.

With the EVALUATE statement, you can test any number of conditions in a single state-
ment and have separate actions for each. In structured programming terms, this is a
case structure. It can also be thought of as a form of decision table.

Conditional Expressions
The IF and EVALUATE statements let you code different program actions that will be
performed depending on the true or false value of a condition expression. COBOL lets
you specify any of these simple conditions:

66 COBOL Set for AIX Programming Guide


Selecting Program Actions

Figure 21. Conditions You Can Test For In COBOL


Condition Type What It Tests Where to Look for Information
Class Whether your data is uppercase “Checking for Incompatible Data
alphabetic, lowercase alphabetic, (Numeric Class Test)” on page 37.
numeric, MBCS Kanji, or con-
sisting entirely of characters listed
in the definition of a user-defined
class-name.
NUMPROC(PFD), which
bypasses invalid sign processing,
might affect the outcome of a test
for numeric data.
User-defined A level-88 condition name, to dis- See “Condition-Names (Switches
cover whether a data item con- and Flags)” on page 67 for details
tains a particular value or range of on how to use level-88 items to
values. define condition-names that you can
test to control the processing of
switches and flags.
Relation Compares two items. IBM COBOL Language Reference.
Sign Whether a numeric operand is IBM COBOL Language Reference.
less than, greater than, or equal
to zero.
Switch-status Whether an UPSI switch is on or IBM COBOL Language Reference.
off.

You can create combined conditions by using logical connectives (AND, OR, or NOT),
and you can combine conditions. Rules for using conditions are given in IBM COBOL
Language Reference.

Condition-Names (Switches and Flags)


Some program decisions are based on whether the value of a data item is true or false,
on or off, yes or no. To control these two-way decisions in your program, define
level-88 items with meaningful names (a condition name) to act as switches.

Some program decisions are based not on an on or off condition of a data item, but
instead, depend on the particular value (or range of values) of a data item. When
condition-names are used to give more than just on or off values to a field, the field is
generally referred to as a flag, not a switch. For details on flags, see the section
“Flags” on page 68, below.

Flags and Switches Make Changing Code Easier: Flags and switches make your
code easier to change. If you need to change the values for a condition, you have to
change only the level-88 condition-name value.

For example, a program that uses a condition-name to test a field for a given numeric
range—a salary range—need not be changed. If the program must be changed to
check for a different salary range, you would need to change only the condition-name

Chapter 5. Selection and Iteration 67


Selecting Program Actions

value in the DATA DIVISION. You do not need to make changes in the PROCEDURE
DIVISION.

Switches: For example, to test for an end-of-file condition for an input file named
Transaction-File, you could use the following data definitions:
Working-Storage Section.
ð1 Switches.
ð5 Transaction-EOF-Switch Pic X value space.
88 Transaction-EOF value "y".
The level-88 description says a condition named Transaction-EOF is turned on when
Transaction-EOF-Switch has a value of "y". Referencing Transaction-EOF in your
PROCEDURE DIVISION expresses the same condition as testing for
Transaction-EOF-Switch = "y". For example, the statement:
If Transaction-EOF Then Perform Print-Report-Summary-Lines
causes the report to be printed only if your program has read through to the end of the
Transaction-File and if the Transaction-EOF-Switch has been set to "y".

Flags: To test for more than two values, assign more than one condition-name to a
field by using multiple level-88 items.

Consider a program that updates a master file. The updates are read from a trans-
action file. The transaction file's records contain a field for the function to be per-
formed: add, change, or delete. In the input file's record description, code a field for the
function code using level-88 items:
ð1 Transaction-Input Record
ð5 Transaction-Type Pic X.
88 Add-Transaction Value "A".
88 Change-Transaction Value "C".
88 Delete-Transaction Value "D".

The code in the PROCEDURE DIVISION for testing these condition-names might look like
this:
Evaluate True
When Add-Transaction
Perform Add-Master-Record-Paragraph
When Change-Transaction
Perform Update-Exisitng-Record-Paragraph
When Delete-Transaction
Perform Delete-Master-Record-Paragraph
End-Evaluate

Resetting Condition-Names (Switches and Flags)


Throughout your program, you might need to reset your switches or change your flags
back to the original values they have in their data descriptions. To do so, you can use
either a SET statement or define your own data item to use.

68 COBOL Set for AIX Programming Guide


Selecting Program Actions

SET condition-name TO TRUE: When you use the SET condition-name TO TRUE
statement, the switch or flag is set back to the original value it was assigned in its data
description.

This method makes it easy for the reader to follow your code if you choose meaningful
condition-names and if the value assigned has some association with a logical value of
True.

The SET statement in the following example does the same thing as Move "y" to
Transaction-EOF-Flag:
ð1 Switches
ð5 Transaction-EOF-Switch Pic X Value space.
88 Transaction-EOF Value "y".
.
.
.
Procedure Division.
ððð-Do-Main-Logic.
Perform 1ðð-Initialize-Paragraph
Read Update-Transaction-File
At End Set Transaction-EOF to True
End-Read

The following example shows how you can assign a value for a field in an output record
based on the transaction code of an input record.
ð1 Input-Record.
ð5 Transaction-Type Pic X(9).
.
.
.
ð1 Data-Record-Out.
ð5 Data-Record-Type Pic X.
88 Record-Is-Active Value "A".
88 Record-Is-Suspended Value "S".
88 Record-Is-Deleted Value "D".
ð5 Key-Field Pic X(5).
.
.
.

Chapter 5. Selection and Iteration 69


Repeating Program Actions

Procedure Division.
.
.
.
Evaluate Transaction-Type of Input-Record
When "ACTIVE"
Set Record-Is-Active to TRUE
When "SUSPENDED"
Set Record-Is-Suspended to TRUE
When "DELETED"
Set Record-Is-Deleted to TRUE
End-Evaluate
Level-88 Note: For a level-88 item with multiple values (such as 88
Record-is-Active Value "A" "O" "S"), SET condition-name TO TRUE assigns the first
value (here, A).

SWITCH-OFF: Establish a data item with this description:


ð1 SWITCH-OFF Pic X Value "n".

Then use SWITCH-OFF throughout your program to set on/off switches to off. With this
method, whoever reads your code can easily see what you are doing to a switch. From
this code:
ð1 Switches
ð5 Transaction-EOF-Switch Pic X Value space.
88 Transaction-EOF Value "y".
ð1 SWITCH-OFF Pic X Value "n".
.
.
.
Procedure Division.
.
.
.
Move SWITCH-OFF to Transaction-EOF-Switch
it is easy to see that you are setting the end-of-file switch to off. In other words, you
have reset the switch to indicate that the end of the file has not been reached.

Iterative Loops (PERFORM Statement)


For looping (repeating the same code), use one of the forms of the PERFORM state-
ment. You can use the PERFORM statement to loop a set number of times or to loop
based on the outcome of a decision.

PERFORM statements can be inline or out-of-line.

Use the PERFORM statement to run a paragraph and then implicitly return control to the
next executable statement. In effect, the PERFORM statement is a way of coding a
closed subroutine that you can enter from many different parts of the program.

70 COBOL Set for AIX Programming Guide


Repeating Program Actions

Coding a Loop to Be Performed a Definite Number of Times


Use the PERFORM . . . TIMES statement to execute a paragraph a certain number of
times:
PERFORM ð1ð-PROCESS-ONE-MONTH 12 TIMES
INSPECT . . .

When control reaches the PERFORM statement, the code for the paragraph
ð1ð-PROCESS-ONE-MONTH is executed 12 times before control is transferred to the
INSPECT statement.

Conditional Looping
Use the PERFORM . . . UNTIL statement to execute a paragraph until a condition you
choose is satisfied. You can use either of the following forms:
PERFORM . . . WITH TEST AFTER . . . UNTIL . . .
PERFORM . . . [WITH TEST BEFORE] . . . UNTIL . . .

In the following example, the implicit WITH TEST BEFORE phrase provides a do-while
structure:
PERFORM ð1ð-PROCESS-ONE-MONTH
UNTIL MONTH EQUAL DECEMBER
INSPECT . . .

When control reaches the PERFORM statement, the condition (MONTH EQUAL DECEMBER)
is tested. If the condition is satisfied, control is transferred to the INSPECT statement. If
the condition is not satisfied, ð1ð-PROCESS-ONE-MONTH is executed, and the condition is
tested again. This cycle continues until the condition tests as true. (To make your
program easier to read, you might want to code the WITH TEST BEFORE clause.)

Use the PERFORM . . . WITH TEST AFTER . . . UNTIL if you want to execute the para-
graph at least once and then test before any subsequent execution. This is equivalent
to the do-until structure.

Looping through a Table


Use the PERFORM statement to control a loop through a table. You can use either of
the following forms:
PERFORM . . . WITH TEST AFTER . . . VARYING . . . UNTIL . . .
PERFORM . . . [WITH TEST BEFORE] . . . VARYING . . . UNTIL . . .

PERFORM. . .WITH TEST AFTER Example


You can use PERFORM . . . VARYING to initialize a table. In this form of the PERFORM
statement, a variable is increased or decreased and tested until a condition is satisfied.
The following code shows an example of looping through a table to check for invalid
data:

Chapter 5. Selection and Iteration 71


Repeating Program Actions

\\\ BLANK FIELDS ARE NOT ALLOWED IN THE INPUT DATA \\\

PERFORM TEST AFTER VARYING WS-DATA-IX


FROM 1 BY 1
UNTIL WS-DATA-IX = 12
IF WS-DATA (WS-DATA-IX) EQUALS SPACES
SET SERIOUS-ERROR TO TRUE
DISPLAY ELEMENT-NUM-MSG5
END-IF
END-PERFORM

INSPECT . . .

In the code above, when control reaches the PERFORM statement, WS-DATA-IX is set
equal to 1 and the PERFORM statement is executed. Then the condition (WS-DATA-IX =
12) is tested. If the condition is true, control drops through to the INSPECT statement.
If it is false, WS-DATA-IX is increased by 1, the PERFORM statement is executed, and the
condition is tested again. This cycle of execution and testing continues until WS-DATA-IX
is equal to 12.

In terms of the application, this loop controls input-checking for the 12 fields of item
WS-DATA. Empty fields are not allowed, and this section of code loops through and
issues error messages, as appropriate.

Executing a Group of Paragraphs or Sections


In structured programming, the paragraph you execute is usually a single paragraph.
However, you can execute a group of paragraphs, a single section, or a group of
sections using the PERFORM . . . THRU. statement.

WHEN YOU USE PERFORM . . . THRU use a paragraph-EXIT statement to clearly indicate
the end point for the series of paragraphs.

Intrinsic functions can make the task of the iterative processing of tables simpler and
easier for you to code. For information on using the ALL subscript with intrinsic func-
tions to reference all the items in a table, see “Processing Table Items (Intrinsic
Functions)” on page 62.

72 COBOL Set for AIX Programming Guide


Joining Data Items

Chapter 6. String Handling


COBOL provides language constructs for performing these operations associated with
string data items:

Figure 22. COBOL Data Constructs for Manipulating Strings


What You Want to Do What to Use Where to Look
Join data items STRING Statement On page 73
Split data items UNSTRING Statement On page 75
Manipulate null-terminated strings Usual string handling statements. On page 78
Reference substrings of data items Reference modifiers On page 79
Tally and replace data items INSPECT statement On page 82
Convert data items Intrinsic functions UPPER-CASE, On page 84
LOWER-CASE, REVERSE,
NUMVAL, and NUMVAL-C
Evaluate data items Intrinsic functions CHAR, ORD, On page 86
MAX, MIN, ORD-MAX, ORD-MIN,
LENGTH, and WHEN-COMPILED

Joining Data Items (STRING Statement)


Use the STRING statement to join all or parts of several data items into one data item.
One STRING statement can save you several MOVE statements.

The STRING statement transfers data into the receiving item in the order you indicate.
In the STRING statement you can also specify:
Ÿ Delimiters that cause a sending field to be ended and another to be started
Ÿ Special actions to be taken when an ON OVERFLOW condition occurs (when the
single receiving field is filled before all of the sending characters have been proc-
essed).

STRING Statement Example


In the following example, an input record is read, and the STRING statement is used to
select and format information as an output line consisting of a line number, customer
name and address, invoice number, next billing date, and balance due, truncated to the
dollar figure shown. (The symbol ␣ indicates a blank space.)

In the FILE SECTION, the following records are defined:

 Copyright IBM Corp. 1996, 1998 73


Joining Data Items

ð1 RCD-ð1.
ð5 CUST-INFO.
1ð CUST-NAME PIC X(15).
1ð CUST-ADDR PIC X(35).
ð5 BILL-INFO.
1ð INV-NO PIC X(6).
1ð INV-AMT PIC $$,$$$.99.
1ð AMT-PAID PIC $$,$$$.99.
1ð DATE-PAID PIC X(8).
1ð BAL-DUE PIC $$,$$$.99.
1ð DATE-DUE PIC X(8).

In the WORKING-STORAGE SECTION, the following fields are defined:


77 RPT-LINE PIC X(12ð).
77 LINE-POS PIC S9(3).
77 LINE-NO PIC 9(5) VALUE 1.
77 DEC-POINT PIC X VALUE ".".

The record, as read, contains the following information:


J.B.␣SMITH␣␣␣␣␣
444␣SPRING␣ST.,␣CHICAGO,␣ILL.␣␣␣␣␣␣
A14275
$4,736.85
$2,4ðð.ðð
ð9/22/76
$2,336.85
1ð/22/76

In the PROCEDURE DIVISION, the programmer initializes RPT-LINE to SPACES and sets
LINE-POS, the data item to be used as the POINTER field, to 4. (By coding the POINTER
phrase of the STRING statement, you can use the explicit pointer field to control place-
ment of data in the receiving field.) Then, the programmer issues this STRING
statement:
STRING
LINE-NO SPACE CUST-INFO INV-NO SPACE DATE-DUE SPACE
DELIMITED BY SIZE
BAL-DUE
DELIMITED BY DEC-POINT
INTO RPT-LINE
WITH POINTER LINE-POS.

STRING Program Results


When the statement is performed, the following steps take place:
1. The field LINE-NO is moved into positions 4 through 8 of RPT-LINE .
2. A space is moved into position 9.
3. The group item CUST-INFO is moved into positions 10 through 59.
4. INV-NO is moved into positions 60 through 65.
5. A space is moved into position 66.
6. DATE-DUE is moved into positions 67 through 74.

74 COBOL Set for AIX Programming Guide


Splitting Data Items

7. A space is moved into position 75.


8. The portion of BAL-DUE that precedes the decimal point is moved into positions 76
through 81.
9. The value of LINE-POS is 82 after the STRING statement is performed.

After the STRING statement is performed, RPT-LINE appears as shown in the following:

Column

4 1ð 6ð 67 76
│ │ │ │ │
│ │ │ │ │
6 6 6 6 6
ðððð1 J.B. SMITH 444 SPRING ST., CHICAGO, ILL A14275 1ð/22/76 $2,336

Splitting Data Items (UNSTRING Statement)


Use the UNSTRING statement to split one sending field into several receiving fields.
One UNSTRING statement can save you several MOVE statements.

You can indicate delimiters that, when encountered in the sending field, cause the
current receiving field to be switched to the next one indicated. You might have the
number of characters placed in each receiving field returned to you, and keep a count
of the total number of characters transferred. You might also specify special actions for
the program to take if all the receiving fields are filled before the end of the sending
item is reached.

UNSTRING Statement Example


In the following example, selected information is taken from the input record; some is
organized for printing and some for further processing.

In the FILE SECTION, the following records are defined:

Chapter 6. String Handling 75


Splitting Data Items

\ Record to be acted on by the UNSTRING statement:


ð1 INV-RCD.
ð5 CONTROL-CHARS PIC XX.
ð5 ITEM-INDENT PIC X(2ð).
ð5 FILLER PIC X.
ð5 INV-CODE PIC X(1ð).
ð5 FILLER PIC X.
ð5 NO-UNITS PIC 9(6).
ð5 FILLER PIC X.
ð5 PRICE-PER-M PIC 99999.
ð5 FILLER PIC X.
ð5 RTL-AMT PIC 9(6).99.
\
\ UNSTRING receiving field for printed output:
ð1 DISPLAY-REC.
ð5 INV-NO PIC X(6).
ð5 FILLER PIC X VALUE SPACE.
ð5 ITEM-NAME PIC X(2ð).
ð5 FILLER PIC X VALUE SPACE.
ð5 DISPLAY-DOLS PIC 9(6).

\
\ UNSTRING receiving field for further processing:
ð1 WORK-REC.
ð5 M-UNITS PIC 9(6).
ð5 FIELD-A PIC 9(6).
ð5 WK-PRICE REDEFINES FIELD-A PIC 9999V99.
ð5 INV-CLASS PIC X(3).
\
\ UNSTRING statement control fields
77 DBY-1 PIC X.
77 CTR-1 PIC S9(3).
77 CTR-2 PIC S9(3).
77 CTR-3 PIC S9(3).
77 CTR-4 PIC S9(3).
77 DLTR-1 PIC X.
77 DLTR-2 PIC X.
77 CHAR-CT PIC S9(3).
77 FLDS-FILLED PIC S9(3).

In the PROCEDURE DIVISION, the programmer writes the following UNSTRING


statement:

76 COBOL Set for AIX Programming Guide


Splitting Data Items

\ Move subfields of INV-RCD to the subfields of DISPLAY-REC


\ and WORK-REC:
UNSTRING INV-RCD
DELIMITED BY ALL SPACES OR "/" OR DBY-1
INTO ITEM-NAME COUNT IN CTR-1
INV-NO DELIMITER IN DLTR-1 COUNT IN CTR-2
INV-CLASS
M-UNITS COUNT IN CTR-3
FIELD A
DISPLAY-DOLS DELIMITER IN DLTR-2 COUNT IN CTR-4
WITH POINTER CHAR-CT
TALLYING IN FLDS-FILLED
ON OVERFLOW GO TO UNSTRING-COMPLETE.

Before issuing the UNSTRING statement, the programmer places the value 3 in CHAR-CT
(the POINTER field) to avoid working with the two control characters in INV-RCD. A
period (.) is placed in DBY-1 for use as a delimiter, and the value 0 (zero) is placed in
FLDS-FILLED (the TALLYING field). The data is then read into INV-RCD, as shown in the
following:

Column

1 1ð 2ð 3ð 4ð 5ð 6ð
│ │ │ │ │ │ │
│ │ │ │ │ │ │
│ │ │ │ │ │ │
6 6 6 6 6 6 6
ZYFOUR─PENNY─NAILS 7ð789ð/BBA 47512ð ðð122 ððð379.5ð

UNSTRING Program Results


When the UNSTRING statement is performed, the following steps take place:
1. Positions 3 through 18 (FOUR-PENNY-NAILS) of INV-RCD are placed in ITEM-NAME,
left-justified in the area, and the unused character positions are padded with
spaces. The value 16 is placed in CTR-1.
2. Because ALL SPACES is coded as a delimiter, the 5 contiguous SPACE characters
are considered to be one occurrence of the delimiter.
3. Positions 24 through 29 (707890) are placed in INV-NO. The delimiter character, /,
is placed in DLTR-1 , and the value 6 is placed in CTR-2.
4. Positions 31 through 33 are placed in INV-CLASS. See Note at end of list.
5. Positions 35 through 40 (475120) are examined and placed in M-UNITS. The value
6 is placed in CTR-3. See Note at end of list.
6. Positions 42 through 46 (00122) are placed in FIELD-A and right-justified in the
area. The high-order digit position is filled with a 0 (zero). See Note at end of list.
7. Positions 48 through 53 (000379) are placed in DISPLAY-DOLS. The period (.)
delimiter character in DBY-1 is placed in DLTR-2, and the value 6 is placed in CTR-4.

Chapter 6. String Handling 77


Manipulating Null-Terminated Strings

8. Because all receiving fields have been acted on and 2 characters of data in
INV-RCD have not been examined, the ON OVERFLOW exit is taken, and execution
of the UNSTRING statement is completed.
SPACE Note: In steps 4, 5, and 6, the delimiter is a SPACE, but because no field has
been defined as a receiving area for delimiters, the SPACE is bypassed.

After the UNSTRING statement is performed, the fields contain:


Ÿ DISPLAY-REC contains:
7ð789ð FOUR-PENNY-NAILS ððð379
Ÿ WORK-REC contains:
47512ðððð122BBA
Ÿ CHAR-CT (the POINTER field) contains the value 55.
Ÿ FLDS-FILLED (the TALLYING field) contains the value 6.

Manipulating Null-Terminated Strings


Null-terminated strings are supported using syntax shown in the IBM COBOL Language
Reference. You can construct and manipulate null-terminated strings passed to or from
a C program, for example, by using string handling mechanisms such as:
Ÿ Using null terminated literal constants (Z" ... ").
Ÿ Using INSPECT statement to count number of characters in a null-terminated string:
MOVE ð TO char-count
INSPECT source-field TALLYING char-count
FOR CHARACTERS
BEFORE X"ðð"
Ÿ Using UNSTRING statement to move characters in a null-terminated string to a
target-field and get the character count:
WORKING-STORAGE SECTION.
...
ð1 source-field PIC X(1ðð1).
ð1 char-count COMP-5 PIC 9(4).
ð1 target-area.
ð2 individual-char OCCURS 1 TO 1ððð TIMES DEPENDING ON char-count
PIC X.
...
PROCEDURE DIVISION.
...
UNSTRING source-field DELIMITED BY X"ðð"
INTO target-area
COUNT IN char-count
ON OVERFLOW
DISPLAY "source not null terminated or target too short"
...
END-UNSTRING
...

78 COBOL Set for AIX Programming Guide


Referencing Substrings

Ÿ Using a SEARCH statement to locate trailing null or space characters (Define the
string being examined as a table of single characters.)
Ÿ Checking each character in a field in a loop (PERFORM) looking at each character
of the field (Each character in the field can be examined using a reference modifier
such as source-field (I:1).)

The following example shows the use of several of these mechanisms:

ð1 L pic X(2ð) value z'ab'.


ð1 M pic X(2ð) value z'cd'.
ð1 N pic X(2ð).
ð1 N-Length pic 99 value zero.
ð1 Y pic X(13) value 'Hello, World!'.

\ Display null-terminated string


Inspect N tallying N-length
for characters before initial x'ðð'
Display 'N: ' N(1:N-length) ' Length: ' N-length

\ Move null-terminated string to alphanumeric, strip null


Unstring N delimited by X'ðð' into X

\ Create null-terminated string


String Y delimited by size
X'ðð' delimited by size
into N.

\ Concatenate two null-terminated strings


String L delimited by x'ðð'
M delimited by x'ðð'
X'ðð' delimited by size
into N.

Figure 23. Handling Null-Terminated Strings

Referencing Substrings of Data Items (Reference Modifiers)


Reference a substring of character-string data item items (including ASCII data items)
with reference modifiers. Intrinsic functions that return character-string values are also
considered alphanumeric data items, and can include a reference modifier.

The following example shows how to use a reference modifier to reference a substring
of a data item:
Move Customer-Record(1:2ð) to Orig-Customer-Name

As this shows, in parentheses immediately following the data item you code the ordinal
position (from the left) of the character you want the substring to start with and the
length of the desired substring, separated by a colon.

Chapter 6. String Handling 79


Referencing Substrings

The length is optional. If you omit the length, the substring created will automatically
extend to the end of the item. Omitting the length, when possible, is recommended as
a simpler, less error-prone coding technique.

These values can be variables or expressions.

Common Reference Modification Mistakes


If the leftmost character position or the length value is a fixed-point non-integer, trun-
cation will occur to create an integer; if it is a floating-point non-integer, rounding will
occur to create an integer.

Both numbers in the reference modifier must be at least 1, and their sum should not
exceed the total length of the data item.

The following options detect out-of-range reference modifiers and flag violations with a
run-time message:
Ÿ SSRANGE compiler option, discussed on page 178.
Ÿ CHECK run-time option, discussed on page “CHECK” on page 193.

For additional information on reference modification, see IBM COBOL Language Refer-
ence.

Benefits of Reference Modification


Assume that you want to retrieve the current time from the system and display its value
in an expanded format. You can retrieve the current time value from the system with
the ACCEPT statement, which returns the hours, minutes, seconds, and hundredths of
seconds in this format:
HHMMSSss
However, you might prefer to view the current time in this format:
HH:MM:SS

Without reference notification you would have to define data items for both formats, the
one from the system and the one you want, and write code to convert from one format
to the other.

With reference modification, you do not need to provide names for the subfields that
describe the TIME elements. The only data definition needed is:
ð1 REFMOD-TIME-ITEM PIC X(8).

The code to retrieve and expand the time value would appear as follows:

80 COBOL Set for AIX Programming Guide


Referencing Substrings

ACCEPT REFMOD-TIME-ITEM FROM TIME.


DISPLAY "CURRENT TIME IS: "
\ Retrieve the portion of the time value that corresponds to
\ the number of hours:
REFMOD-TIME-ITEM (1:2)
":"
\ Retrieve the portion of the time value that corresponds to
\ the number of minutes:
REFMOD-TIME-ITEM (3:2)
":"
\ Retrieve the portion of the time value that corresponds to
\ the number of seconds:
REFMOD-TIME-ITEM (5:2).

Reference Modification of an Intrinsic Function


The simplest solution to our problem would be to reference a substring of the
CURRENT-DATE function, which requires no DATA DIVISION entries and fewer lines of
code.
Display "Current Date is: "
Function Current-Date(9:2)
":"
Function Current-Date(11:2)
":"
Function Current-Date(13:2).

Using Arithmetic Expressions as Reference Modifiers


You can also use an arithmetic expression as either of the integers in a reference modi-
fier. For example:

Suppose that a field contains some characters, right-justified, and you want to move the
characters to another field, but justified to the left instead of the right. Using reference
modification and an INSPECT statement, you could do that.

The program would have the following data:


ð1 LEFTY PIC X(3ð).
ð1 RIGHTY PIC X(3ð) JUSTIFIED RIGHT.
ð1 I PIC 9(9) USAGE BINARY.

The program would count the number of leading spaces and, using arithmetic
expressions in a reference modification expression, move the right-justified characters
into another field, left-justified:
MOVE SPACES TO LEFTY
MOVE ZERO TO I
| INSPECT RIGHTY
TALLYING I FOR LEADING SPACE.
IF I IS LESS THAN LENGTH OF RIGHTY THEN
MOVE RIGHTY ( I + 1 : LENGTH OF RIGHTY - I ) TO LEFTY
END-IF

Chapter 6. String Handling 81


Counting and Replacing Data Items

The MOVE statement transfers characters from RIGHTY, beginning at the position com-
puted in I + 1, for a length that is computed in LENGTH OF RIGHTY - I, into the field
LEFTY.

Using Intrinsic Functions as Reference Modifiers


Because a numeric function-identifier can be used anywhere an arithmetic expression is
allowed, it can be used as the leftmost character position and/or the length in the refer-
ence modifier.

For example:
ð5 WS-name Pic x(2ð).
ð5 Left-posn Pic 99.
ð5 I Pic 99.
.
.
Move Customer-Record(Function Min(Left-posn I):Function Length(WS-name)) to WS-name

When performed, this statement causes a substring of Customer-Record to be moved


into the variable WS-name; the substring is determined at run time.

If you want to use a numeric, non-integer function in a position requiring an integer


function, you can use the INTEGER or INTEGER-PART function to convert the result to an
integer. For example:
Move Customer-Record(Function Integer(Function Sqrt(I)): ) to WS-name

For a list that shows which numeric functions return integer and non-integer results, see
IBM COBOL Language Reference.

Referencing Substrings of Table Items


You can also reference substrings of table entries, including variable-length entries.
This is discussed in Chapter 4, “Handling Tables” on page 46.

Tallying and Replacing Data Items (INSPECT Statement)


The INSPECT statement is useful for:
Ÿ Filling selective portions of a data item with a value.
Ÿ Replacing portions with a corresponding portion of another data item.
Ÿ Counting the number of times a specific character (zero, space, asterisk, for
example) occurs in a data item.

INSPECT Statement Examples


The following examples show some uses of the INSPECT statement. In all instances,
the programmer has initialized the COUNTR field to zero before the INSPECT statement is
performed.

82 COBOL Set for AIX Programming Guide


Counting and Replacing Data Items

Example 1:
77 COUNTR PIC 9 VALUE ZERO.
ð1 DATA-2 PIC X(11).
.
.
INSPECT DATA-2
TALLYING COUNTR FOR LEADING "ð"
REPLACING FIRST "A" BY "2" AFTER INITIAL "C"

DATA-2 Before COUNTR After DATA-2 After


ððACADEMYðð 2 ððAC2DEMYðð
ððððALABAMA 4 ððððALABAMA
CHATHAMðððð 0 CH2THAMðððð

Example 2:
77 COUNTR PIC 9 VALUE ZERO.
ð1 DATA-3 PIC X(8).
.
.
INSPECT DATA-3
REPLACING CHARACTERS BY ZEROS BEFORE INITIAL QUOTE

DATA-3 Before COUNTR After DATA-3 After


456"ABEL 0 ððð"ABEL
ANDES"12 0 ððððð"12
"TWAS BR 0 "TWAS BR

Example 3:
The following example shows the use of INSPECT CONVERTING with AFTER and
BEFORE phrases. The table shows examples of the contents of DATA-4 before and after
the conversion statement is performed.
ð1 DATA-4 PIC X(11).
.
.
INSPECT DATA-4
CONVERTING
"abcdefghijklmnopqrstuvwxyz" TO
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
AFTER INITIAL "/"
BEFORE INITIAL"?"

Chapter 6. String Handling 83


Converting Character Data Items

DATA-4 Before DATA-4 After


a/five/?six a/FIVE/?six
r/Rexx/RRRr r/REXX/RRRR
zfour?inspe zfour?inspe

Converting Data Items (Intrinsic Functions)


Intrinsic functions are available to convert character-string data items to the following:
Ÿ Upper or lower case
Ÿ Reverse order
Ÿ Numbers

Besides using intrinsic functions to convert characters, you can also use the INSPECT
statement. See the examples under “Tallying and Replacing Data Items (INSPECT
Statement)” on page 82.

Converting to Uppercase or Lowercase (UPPER-CASE, LOWER-CASE)


This code:
ð1 Item-1 Pic x(3ð) Value "Hello World!".
ð1 Item-2 Pic x(3ð).
.
.
Display Item-1
Display Function Upper-case(Item-1)
Display Function Lower-case(Item-1)
Move Function Upper-case(Item-1) to Item-2
Display Item-2
would display the following messages on the terminal:
Hello World!
HELLO WORLD!
hello world!
HELLO WORLD!
The DISPLAY statements do not change the actual contents of Item-1 and only affect
how the letters are displayed. However, the MOVE statement causes uppercase letters
to be moved to the actual contents of Item-2.

Converting to Reverse Order (REVERSE)


The following code:
Move Function Reverse(Orig-cust-name) To Orig-cust-name
would reverse the order of the characters in Orig-cust-name. For example, if the
starting value was “JOHNSON␣␣␣,” the value after the statement is performed would be
“␣␣␣NOSNHOJ.”

84 COBOL Set for AIX Programming Guide


Converting Character Data Items

Converting to Numbers (NUMVAL, NUMVAL-C)


The NUMVAL and NUMVAL-C functions convert character strings to numbers. Use these
functions to convert alphanumeric data items that contain free format character repre-
sentation numbers to numeric form and process them numerically. For example:
ð1 R Pic x(2ð) Value "- 1234.5678".
ð1 S Pic x(2ð) Value " $12,345.67CR".
ð1 Total Usage is Comp-1.
.
.
Compute Total = Function Numval(R) + Function Numval-C(S)

The difference between NUMVAL and NUMVAL-C is that NUMVAL-C is used when the
argument includes a currency symbol and/or comma, as shown in the example. You
can also place an algebraic sign in front or in the rear, and it will be processed. The
arguments must not exceed 18 digits (not including the editing symbols). For exact
syntax rules, see IBM COBOL Language Reference.
Numeric Result: Both NUMVAL and NUMVAL-C return long (double-precision) floating-
point values. A reference to either of these functions, therefore, represents a reference
to a numeric data item. For more information on characteristics of numeric data, see
Chapter 3, “Numbers and Arithmetic” on page 29.

Why Use NUMVAL and NUMVAL-C


When you use NUMVAL or NUMVAL-C you don't need to statically declare numeric data
in a fixed format and input data in a precise manner. For example, for this code:
ð1 X Pic S999V99 leading sign is separate.
.
.
Accept X from Console
The user of the application must enter the numbers exactly as defined by the PICTURE
clause. For example:
+ðð1.23
-3ðð.ðð

However, using the NUMVAL function, you could code:


ð1 A Pic x(1ð).
ð1 B Pic S999V99.
.
.
Accept A from Console
Compute B = Function Numval(A)
and the input could be:
1.23
-3ðð

Chapter 6. String Handling 85


Evaluating Data Items

Evaluating Data Items (Intrinsic Functions)


Several intrinsic functions can be used in evaluating data items:
Ÿ CHAR and ORD for evaluating integers and single alphanumeric characters with
respect to the collating sequence used in your program.
Ÿ MAX, MIN, ORD-MAX, and ORD-MIN for finding the largest and smallest items in a
series of data items.
Ÿ LENGTH for finding the length of data items.
Ÿ WHEN-COMPILED for finding the date and time the program was compiled.

Evaluating Single Characters for Collating Sequence (CHAR, ORD)


If you want to know the ordinal position of a certain character in the collating sequence,
reference the ORD function using the character in question as the argument, and ORD
will return an integer representing that ordinal position. One convenient way to do this
is to use the substring of a data item as the argument to ORD:
IF Function Ord(Customer-record(1:1)) Is > 194 THEN ...

On the other hand, if you know what position in the collating sequence you want but
don't know what character it corresponds to, then reference the CHAR function using
the integer ordinal position as the argument, and CHAR will return the desired character:
INITIALIZE Customer-Name REPLACING ALPHABETIC BY Function Char(65)

Finding the Largest or Smallest Data Item (MAX, MIN, ORD-MAX, ORD-MIN)
If you have two or more alphanumeric data items and want to know which data item
contains the largest value (evaluated according to the collating sequence), use the MAX
or ORD-MAX function, supplying the data items in question as arguments. If you want to
know which item contains the smallest value, you would use the MIN or ORD-MIN func-
tion.

MAX and MIN


The MAX and MIN functions simply return the contents of one of the variables you
supply.

For example, with these data definitions:


ð5 Arg1 Pic x(1ð) Value "THOMASSON ".
ð5 Arg2 Pic x(1ð) Value "THOMAS ".
ð5 Arg3 Pic x(1ð) Value "VALLEJO ".
the following statement:
Move Function Max(Arg1 Arg2 Arg3) To Customer-record(1:1ð)
would assign “VALLEJO␣␣␣” to the first ten character positions of Customer-record.

If MIN were used instead, then “THOMAS␣␣␣␣” would be returned.

86 COBOL Set for AIX Programming Guide


Evaluating Data Items

ORD-MAX and ORD-MIN


The functions ORD-MAX and ORD-MIN return an integer that represents the ordinal posi-
tion of the argument with the largest or smallest value in the list of arguments you have
supplied (counting from the left).

If the ORD-MAX function were used in the example above, you would receive a syntax
error message at compile time, because you would be attempting to reference a
numeric function in an invalid place (see IBM COBOL Language Reference). The fol-
lowing is a valid example of the ORD-MAX function:
Compute x = Function Ord-max(Arg1 Arg2 Arg3)
This would assign the integer 3 to x, if the same arguments were used as in the pre-
vious example. If ORD-MIN were used instead, the integer 2 would be returned.

Notes on MAX, MIN, ORD-MAX, ORD-MIN


This group of functions can also be used for numbers, in which case the algebraic
values of the arguments are compared. For more information, see the appropriate
section of Chapter 3, “Numbers and Arithmetic” on page 29.

The above examples would probably be more realistic if Arg1, Arg2 and Arg3 were
instead successive elements of an array (table). For information on using table ele-
ments as function arguments, see the section on “Processing Table Items (Intrinsic
Functions)” on page 62 in Chapter 4, “Handling Tables.”

Returning Variable-Length Results with Alphanumeric Functions


The results of alphanumeric functions might be of varying lengths and values
depending on the function arguments.

In the following example, the amount of data moved to R3 and the results of the
COMPUTE statement depend on the values and sizes of R1 and R2:
ð1 R1 Pic x(1ð) value "e".
ð1 R2 Pic x(ð5) value "f".
ð1 R3 Pic x(2ð) value spaces.
ð1 L Pic 99.
.
.
Move Function Max(R1 R2) to R3
Compute L = Function Length(Function Max(R1 R2))

Here, R2 is evaluated to be larger than R1. Therefore, assuming that the symbol ␣
represents a blank space, the string “f␣␣␣␣” would be moved to R3 (the unfilled char-
acter positions in R3 are padded with spaces), and L evaluates to the value 5. If R1
were the value “g” then R1 would be larger than R2, and the string “g␣␣␣␣␣␣␣␣␣” would
be moved to R3 (the unfilled character positions in R3 would be padded with spaces);
the value 10 would be assigned to L.

You might be dealing with variable-length output from alphanumeric functions. Plan
your program code accordingly. For example, you might need to think about using

Chapter 6. String Handling 87


Evaluating Data Items

variable-length record files when it is possible that the records you will be writing might
be of different lengths:
File Section.
FD Output-File.
ð1 Customer-Record Pic X(8ð).

Working-Storage Section.
ð1 R1 Pic x(5ð).
ð1 R2 Pic x(7ð).
.
.
Write Customer-Record from Function Max(R1 R2)

Finding the Length of Data Items (LENGTH)


The LENGTH function is useful in many programming contexts for determining the
length of string items. The following COBOL statement shows moving a data item such
as a customer name into the particular field in a record that is for customer names:
Move Customer-name To Customer-record(1:Function Length(Customer-name))
Numeric & Table: The LENGTH function can also be used on a numeric data item or
a table entry. Numeric data and tables are discussed in Chapter 3, “Numbers and
Arithmetic” on page 29 and in Chapter 4, “Handling Tables” on page 46.

LENGTH OF Special Register


In addition to the LENGTH function, another technique to find the length of a data item is
to use the LENGTH OF special register. Coding either Function Length(Customer-Name)
or LENGTH OF Customer-Name would return the same result— the length of
Customer-Name in bytes.

Whereas the LENGTH function can only be used where arithmetic expressions are
allowed, the LENGTH OF special register can be used in a greater variety of contexts.
For example, the LENGTH OF special register can be used as an argument to an
intrinsic function that allows integer arguments. (An intrinsic function cannot be used as
an operand to the LENGTH OF special register.) The LENGTH OF special register can
also be used as a parameter in a CALL statement.

Finding the Date of Compilation (WHEN-COMPILED)


If you want to know the date and time the program was compiled as provided by the
system on which the program was compiled, you can use the WHEN-COMPILED func-
tion. The result returned has 21 character positions with the first 16 positions in the
format:
YYYYMMDDhhmmsshh
to show the 4-digit year, month, day, and time (in hours, minutes, seconds, and hun-
dredths of seconds) of compilation.

88 COBOL Set for AIX Programming Guide


Evaluating Data Items

WHEN-COMPILED Special Register


The WHEN-COMPILED special register is another technique you can use to find the date
and time of compilation. It has the format:
MM/DD/YYhh.mm.ss
The WHEN-COMPILED special register supports only a two-digit year and carries the
time out only to seconds. This special register can only be used as the sending field in
a MOVE statement.

Chapter 6. String Handling 89


Processing Files

Chapter 7. Processing Files


Reading and writing data to and from files is an essential part of every program. Your
program retrieves information, processes it as you request, and then produces the
results.

This chapter provides a brief introduction on file organization and access modes,
describes the coding your COBOL programs need to identify and process files, and
explains how files must be defined and identified to the operating system before your
program can process them.

The topics in this chapter are:


“File Input/Output Overview” on page 91
“COBOL Coding for Files” on page 94
“Input/Output Error Handling Techniques” on page 118
“File Sorting and Merging” on page 105
“The STL File System” on page 113

Record-oriented files that are organized as sequential, relative, indexed, or line sequen-
tial (byte stream) files are accessed through a file system. An application can use file-
system functions to create and manipulate the records in any of these types of files.

COBOL Set for AIX supports the following file systems:


Ÿ The STL file system, which provides the basic facilities for local files. It is provided
with COBOL Set for AIX and supports sequential, relative, and indexed files.
Ÿ The VSAM file system, which allows you to read and write files on remote systems
such as OS/390. VSAM also allows you to use COBOL statements to read and
write Encina SFS files. (Encina SFS is the file system used by CICS.) The VSAM
file system is provided with COBOL whereas Encina SFS is either supplied as part
of CICS, or can be ordered independently of CICS.
Most programs will get the same results on all file systems. However, files written
using one file system cannot be read using a different file system.

Two ways you can select a file system are by setting the assignment-name environ-
ment variable or by using the FILESYS run-time option. See “Accessing Files” on
page 96 for futher details. All the file systems allow you to use COBOL statements to
read or write COBOL files.

If you have more complex requirements which are not covered in this book, or are
going to be a frequent user of file systems, you should review publications for the
SMARTdata Utilities for AIX, which are provided as part of the on-line documentation.

90  Copyright IBM Corp. 1996, 1998


File Organization

File Input/Output Overview


This section describes file organization and file access modes. You should decide on
the file types you will use when you design your program. Your file management
system handles the input/output requests and record retrieval from the input/output
devices.

Figure 24 summarizes file organization, access modes, and record lengths for COBOL
files.

Figure 24. File Organizations and Access Modes


Sequential Random Dynamic
File Organization Access Access Access
Sequential Yes No No
Line sequential Yes No No
Indexed Yes Yes Yes
Relative Yes Yes Yes
File I/O Limitations:
Ÿ For line sequential files, the maximum record size is 64K.
Ÿ For VSAM files:
– Minimum record size: 1 byte
– Maximum record size: 64,000 bytes
– Maximum record key length: 255 bytes
– Maximum relative key value: 2**32-2
– Maximum number of bytes allocated for a file: 2**32
Ÿ For STL files:
– Minimum record size: 1 byte
– Maximum record size: 65536 bytes
– Maximum record key length: 255 bytes
– Maximum number or alternate keys: 253 bytes
– Maximum relative key value: 2**32-1
– Maximum number of bytes allocated for a file: 2**32-1
Additional or more restrictive limits might be applicable depending on the platform on which the
target file is located. See the appropriate books for the file system of the target platform for these
limits.

File Organization
You can organize your files as sequential, line sequential, indexed, or relative.

Sequential File Organization


A sequential file contains records organized by the order in which they are entered.
The order of the records is fixed.

Records in sequential files can only be read or written sequentially.

Chapter 7. Processing Files 91


File Organization

After you have placed a record into the file, you cannot shorten, lengthen, or delete it.
However, you can update (REWRITE) a record if the length does not change. New
records are added at the end of the file.

Line Sequential File Organization


Line sequential files are just like sequential files, except that the records can contain
only characters as data. Line sequential files are supported by the native byte stream
files of the operating system.

Line sequential files that are created with WRITE statements with the ADVANCING
phrase can be directed to a printer (as well as a disk).

Indexed File Organization


An indexed file contains records ordered by a record key. Each record contains a field
that contains the record key. The record key uniquely identifies the record and deter-
mines the sequence in which it is accessed with respect to other records. A record key
for a record might be, for example, an employee number or an invoice number.

An indexed file can also use alternate indexes—record keys that let you access the file
using a different logical arrangement of the records. For example, you could access
the file through employee department rather than through employee number.

The record transmission (access) modes allowed for indexed files are sequential,
random, or dynamic. When indexed files are read or written sequentially, the sequence
is that of the key values. For a description of random and dynamic record trans-
mission, see “File Access Modes” on page 93.

Relative File Organization


A relative record file contains records ordered by their relative key—the relative key
being the relative record number representing the record's location relative to where the
file begins. For example, the first record in the file has a relative record number of 1,
the tenth record has a relative record number of 10, and so forth. The relative record
number identifies the fixed-or variable-length record.

The record transmission modes allowed for relative files are sequential, random, or
dynamic. When relative files are read or written sequentially, the sequence is that of
the relative record number. For a description of random and dynamic record trans-
mission, see “File Access Modes” on page 93.

Figure 25 (Page 1 of 2). Comparison of Different Files


Sequential Line Sequential Indexed Relative
Records are in the Records are in the Records are in col- Records are in rela-
order in which they order in which they lating sequence by tive record number
are written. are written. key field. order.

92 COBOL Set for AIX Programming Guide


File Access Modes

Figure 25 (Page 2 of 2). Comparison of Different Files


Sequential Line Sequential Indexed Relative
Access is sequential. Access is sequen- Access is by key Access is by relative
tial. through an index. record number, which
Can have one or is handled like a key.
more alternate
indexes.
A record cannot be A record cannot be Records can be Records can be
deleted, but you can deleted or replaced. deleted or replaced. deleted or replaced.
reuse its space for a
record of the same
length.

File Access Modes


You can access records in sequential and line sequential files sequentially only.

You can access records in indexed and relative files in three ways: sequentially, ran-
domly, or dynamically.

Sequential Access
Code ACCESS IS SEQUENTIAL in the FILE-CONTROL entry.

For indexed files, records are accessed in the order of the key field selected (either
primary or alternate).

For relative files, records are accessed in the order of the relative record numbers.

Random Access
Code ACCESS IS RANDOM in the FILE-CONTROL entry.

For indexed files, records are accessed according to the value you place in a key field.

For relative files, records are accessed according to the value you place in the relative
key.

Dynamic Access
Code ACCESS IS DYNAMIC in the FILE-CONTROL entry.

Dynamic access is a mixed sequential-random access in the same program. Using


dynamic access, you can use one COBOL file definition to perform both sequential and
random processing, accessing some records in sequential order and others by their
keys.

For example, suppose you had an indexed file of employee records, and the employ-
ee's hourly wage formed the record key. Also, suppose your program was interested in
those employees earning between $7.00 and $9.00 per hour and those earning $15.00
per hour and above. To do this, retrieve the first record randomly (with a random-

Chapter 7. Processing Files 93


COBOL Coding for Files

retrieval READ) based on the key of 0700. Next, begin reading sequentially (using
READ NEXT) until the salary field exceeds 0900. You would then switch back to a
random read, this time based on a key of 1500. After this random read, switch back to
reading sequentially until you reach the end of the file.

COBOL Coding for Files


Code your COBOL program according to the types of files you decide to use. The
general format of input/output coding is shown in Figure 26. Explanations of user-
supplied information (lowercase) follow the figure.

IDENTIFICATION DIVISION.
.
.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT filename ASSIGN TO assignment-name .1/ .2/
ORGANIZATION IS org ACCESS MODE IS access .3/ .4/
FILE STATUS IS file-status .5/
.
.
DATA DIVISION.
FILE SECTION.
FD filename
ð1 recordname .6/
nn . . . fieldlength & type .7/ .8/
nn . . . fieldlength & type
.
.
WORKING-STORAGE SECTION
ð1 file-status PICTURE 99.
.
.
PROCEDURE DIVISION.
.
.
OPEN iomode filename .9/
.
.
READ filename
.
.
WRITE recordname
.
.
CLOSE filename
.
.
STOP RUN.

Figure 26. Overview of COBOL Input/Output Coding

The user-supplied information in Figure 26 can be explained as follows:

94 COBOL Set for AIX Programming Guide


COBOL Coding for Files

.1/ filename
Any valid COBOL name. You must use the same filename on the SELECT and the
FD statements, and on the OPEN, READ, START, DELETE, and CLOSE statements.
This name is not necessarily the actual name of the file as known to the system.
Each file requires its own SELECT, FD, and input/output statements. For WRITE
and REWRITE, you specify a record defined for the file.

.2/ assignment-name
You can specify ASSIGN TO assignment-name to specify the target file-system ID
and the file of the name as known to the system directly, or you can set a value
indirectly by using an environment variable.
If you want to have the system file name identified at OPEN time, you can specify
ASSIGN USING data-name. The value of data-name at the time of the execution of
the OPEN statement for the file is used and has the system file identification
optionally preceded by the file-system type identification.
The following example illustrates how inventory-file is dynamically (by way of a
MOVE statement) associated with a file /user/inventory/parts.
SELECT inventory-file ASSIGN USING a-file...
..
.
FILE SECTION.
FD inventory-file ...
..
.
MOVE "/user/inventory/parts" TO a-file
OPEN INPUT inventory-file
The following example illustrates how inventory-file is dynamically (by way of a
MOVE statement) associated with the index file parts and the alternate index files
altpart1 and altpart2, associated with the fully-qualified DCE Cell-Relative name
(/.:/Encina/sfs in this example) for the Encina server.
SELECT inventory-file ASSIGN USING a-file...
ORGANIZATION IS INDEXED
ACCESS MODE IS DYNAMIC
RECORD KEY IS FILESYSFILE-KEY
ALTERNATE RECORD KEY IS ALTKEY1
ALTERNATE RECORD KEY IS ALTKEY2
..
.
FILE SECTION.
FD inventory-file ...
..
.
WORKING-STORAGE SECTION.
ð1 a-file PIC X(8ð) VALUE ' '.
..
.
MOVE "/.:/Encina/sfs/parts(/.:/Encina/sfs/parts;altpart1,/.:/
Encina/sfs/parts;altpart2)" TO a-file
OPEN INPUT inventory-file
For more information, see IBM COBOL Language Reference.

Chapter 7. Processing Files 95


COBOL Coding for Files

.3/ org
Indicates the organization: LINE SEQUENTIAL, SEQUENTIAL, INDEXED, or RELATIVE.
If this clause is omitted, the default is ORGANIZATION SEQUENTIAL.

.4/ access
Indicates the access mode, SEQUENTIAL, RANDOM, or DYNAMIC. If this clause is
omitted, the default is ACCESS SEQUENTIAL.

.5/ file-status
The 2-character COBOL FILE STATUS key.

.6/ recordname
The name of the record used in the WRITE and REWRITE statements. You can
specify more than one record for a file.

.7/ fieldlength
The logical length of the field.

.8/ type
Must match the file's record format. If you break the record description entry
beyond the level-01 description, each element should map accurately against the
record's fields.

.9/ iomode
Specifies the open mode. For example, if you are only reading from a file, code
INPUT. If you are only writing to it, code OUTPUT or EXTEND. If you are doing
both, code I-O.
Line Sequential: I-O is not a valid parameter of OPEN for line sequential files.

Accessing Files
Your programs are able to access STL, VSAM, and Encina SFS files.

Use assignment-name to specify both the file you want to access and the file system to
be used. For a detailed description of assignment-name, see the IBM COBOL Lan-
guage Reference.

The general syntax involved in making an assignment to a file stored in an alternate file
system is:
SELECT file ASSIGN TO FileSystemID-Filename

FileSystemID
Identifies the file system as one of the following:

STL For the STL file system.


VSAM For the VSAM file system. VSAM can be abbreviated to VSA.
Note: Specify the VSAM file system when you want to access SFS files.

If the file-system specification is not provided, then the run-time option FILESYS is
used to select the file system. If a file system is not specified using FILESYS, the
default is VSAM.

96 COBOL Set for AIX Programming Guide


COBOL Coding for Files

Filename
| The file you want to access. Alternatively, you can specify an environment variable
| to allow you to specify the file name at run time. For details, see “Run-Time Envi-
| ronment Variables” on page 130, and the IBM COBOL Language Reference.

Compiling for SFS Files


When you use the SFS file system, use the cob2_r4 command with the -qthread option
to compile your programs. For example:
cob2_r4 -qthread alpha.cbl
The cob2_r4 command is the same as the cob2_r command except that it links the
libraries needed by Encina. You can use the -# option to see which libraries are linked.
For example:
cob2_r4 -# alpha.o
will show which libraries are used.

Example—Accessing Encina SFS Files


Ÿ To use the SFS file system, the following assignment would be valid:
SELECT file1 ASSIGN TO Myfile
Myfile, the COBOL assignment-name, is a run-time environment variable. The fol-
lowing export command will assign its value at run-time:
export Myfile="/.:/myEnc/mySFS/mySFSfil(/.:/myEnc/mySFS/
mySFSfil;myaltfil1,/.:/myEnc/mySFS/mySFSfil;myaltfil2)"
– /.:/myEnc/mySFS/ is the fully-qualified DCE Cell-Related name for the Encina
server.
– mySFSfil is the base index file; myaltfil1 and myaltfil2 are alternate index
files.
– The fully-qualified DCE Cell-Related base index file name is:
/.:/myEnc/mySFS/mySFSfil.
– For an alternate index file, the file name is required to be in the format of its
fully-qualified DCE Cell-Related base index file name followed by a “;” and
then the alternate index file name: /.:/myEnc/mySFS/mySFSfil;myaltfil1.
– A comma is required between specifications of alternate index files in the
export command.

Example—Accessing STL Files


Ÿ To use the STL file system, the following assignment would be valid:
SELECT file1 ASSIGN USING 'STL-MyFile'
Ÿ If the run-time option FILESYS(STL) was in effect, the following assignment would
be valid:
SELECT file1 ASSIGN TO 'MyFile'

Chapter 7. Processing Files 97


COBOL Coding for Files

Ÿ Given that you have defined the environment variable MYFILE , (for example,
export MYFILE=STL-MYFILE), the following assignment would be valid:
SELECT file1 ASSIGN TO MYFILE

Distributed File Access


Using the Distributed File feature of the SMARTdata Utilities, you can access a remote
file (for example, OS/390 VSAM, SAM, or PDS) without any source program change.

In the following example, the SELECT clause is used to associate a file on OS/390 with
a file in your workstation program:
SELECT myfile ASSIGN TO TARGETFILE
You can associate myfile to an OS/390 file called MVSMAST by setting the TARGETFILE
environment variable:
set TARGETFILE=/user/MVSMAST
where the directory USER is set to point to the specific OS/390 node and MVSMAST is
the data set name on the OS/390 system.

See VSAM in a Distributed Environment for more information.

Coding Input/Output Statements for Files


After identifying and describing the files in the ENVIRONMENT DIVISION and DATA DIVI-
SION, process the file records in the PROCEDURE DIVISION of your program.

Figure 27 shows the possible combinations of input/output statements for sequential


files. The 'X' indicates that the statement can be used with the open mode given at
the top of the column.

Figure 27. Valid COBOL Statements for Sequential Files


COBOL OPEN OPEN OPEN OPEN
Access Mode Statement INPUT OUTPUT I-O EXTEND
Sequential OPEN X X X X
WRITE X X
START
READ X X
REWRITE X
DELETE
CLOSE X X X X

Figure 28 shows the possible combinations of input/output statements for line sequen-
tial files. The 'X' indicates that the statement can be used with the open mode given
at the top of the column.

98 COBOL Set for AIX Programming Guide


COBOL Coding for Files

Figure 28. Valid COBOL Statements for Line Sequential Files


OPEN OPEN OPEN OPEN
Access Mode COBOL Statement INPUT OUTPUT I-O EXTEND
Sequential OPEN X X X
WRITE X X
START
READ X
REWRITE
DELETE
CLOSE X X X

Figure 29 shows the possible combinations with indexed and relative files. The 'X'
indicates that the statement can be used with the open mode given at the top of the
column.

Figure 29 (Page 1 of 2). Valid COBOL Statements with Indexed Files and Relative Files
COBOL OPEN OPEN OPEN OPEN
Access Mode Statement INPUT OUTPUT I-O EXTEND
Sequential OPEN X X X X
WRITE X X
START X X
READ X X
REWRITE X
DELETE X
CLOSE X X X X

Random OPEN X X X
WRITE X X
START
READ X X
REWRITE X
DELETE X
CLOSE X X X

Chapter 7. Processing Files 99


COBOL Coding for Files

Figure 29 (Page 2 of 2). Valid COBOL Statements with Indexed Files and Relative Files
COBOL OPEN OPEN OPEN OPEN
Access Mode Statement INPUT OUTPUT I-O EXTEND

Dynamic OPEN X X X
WRITE X X
START X X
READ X X
REWRITE X
DELETE X
CLOSE X X X

File Position Indicator


The file position indicator marks the next record to be accessed for sequential COBOL
requests. You do not set the file position indicator anywhere in your program; it is set
by successful OPEN, START, READ, READ NEXT, and READ PREVIOUS statements. Sub-
sequent READ, READ NEXT, or READ PREVIOUS requests use the established file posi-
tion indicator location and update it.

The file position indicator is not used or affected by the output statements WRITE,
REWRITE, or DELETE. The file position indicator has no meaning for random proc-
essing.

Opening a File
Before your program can use any WRITE, START, READ, REWRITE, or DELETE state-
ments to process records in a file, it must first open the file with an OPEN statement.
The OPEN processing is affected by whether or not the file exists, and whether or not
the OPTIONAL attribute is specified on the file definition.

For example, an OPEN EXTEND of a file that is neither optional nor available results in
file status 35, and the OPEN statement fails. If the file is OPTIONAL, the OPEN EXTEND
will create the file and return file status 05.

Figure 30 shows the COBOL statements used when creating or extending a new or
existing file.

100 COBOL Set for AIX Programming Guide


COBOL Coding for Files

Figure 30. Statements Used when Writing Records to a File


Division Sequential Line Sequential Indexed Relative
Environment SELECT SELECT SELECT SELECT
Division ASSIGN ASSIGN ASSIGN ASSIGN
FILE STATUS ORGANIZATION ORGANIZATION ORGANIZATION
ACCESS MODE IS LINE SEQUENTIAL IS INDEXED IS RELATIVE
FILE STATUS RECORD KEY RELATIVE KEY
ACCESS MODE ALTERNATE FILE STATUS
RECORD KEY ACCESS MODE
FILE STATUS
ACCESS MODE
Data FD entry FD entry FD entry FD entry
Division
Procedure OPEN OUTPUT OPEN OUTPUT OPEN OUTPUT OPEN OUTPUT
Division OPEN EXTEND OPEN EXTEND OPEN EXTEND OPEN EXTEND
WRITE WRITE WRITE WRITE
CLOSE CLOSE CLOSE CLOSE

Opening a File with Records


To open a file that already contains records, use OPEN INPUT, OPEN I-O, or OPEN
EXTEND.

Line Sequential: OPEN I-O is not valid for line sequential files.

If you open a sequential, line sequential, or relative file as EXTEND, the added records
are placed after the last existing records in the file.

If you open an indexed file as EXTEND, each record you add must have a record key
higher than the highest record in the file.

Reading Records from a File


Use the READ statement to retrieve (read) records from a file. To read a record, you
must have opened the file INPUT or I-O. Check the file status key after each READ.
Line Sequential: OPEN I-O is not valid for line sequential

Records in sequential and line sequential files can be retrieved only in the sequence in
which they were written.

Records in indexed and relative record files can be retrieved:

Sequentially
According to the ascending order of the key you are using, the RECORD KEY or the
ALTERNATE RECORD KEY, beginning at the current position of the file position indi-
cator for indexed files, or according to ascending relative record locations for rela-
tive files.

Chapter 7. Processing Files 101


COBOL Coding for Files

Randomly
In any order, depending on how you set the RECORD KEY or ALTERNATE RECORD
KEY or the RELATIVE KEY before your READ request.

Dynamically
Mixed sequential and random.

With dynamic access, you can switch between reading a specific record directly and
reading records sequentially, by using READ NEXT and READ PREVIOUS for sequential
retrieval, and READ for random retrieval (by key).

When you want to read sequentially, beginning at a specific record, use START before
the READ NEXT or the READ PREVIOUS statements to set the file position indicator to
point to a particular record (see “File Position Indicator” on page 100). When you code
START followed by READ NEXT, the next record is read and the file position indicator is
reset to the next record. When you code START followed by READ PREVIOUS, the
previous record is read and the file position indicator is reset to the previous record.
The file position indicator can be moved randomly by using START, but all reading is
done sequentially from that point.

You can continue to read records sequentially, or you can use the START statement to
move the file position indicator. For example:
START file-name KEY IS EQUAL TO ALTERNATE-RECORD-KEY

When a direct READ is performed for an indexed file, based on an alternate index for
which duplicates exist, only the first record in the file (base cluster) with that alternate
key value is retrieved. You need a series of READ NEXT statements to retrieve each of
the data set records with the same alternate key. A FILE STATUS value of '02' is
returned if there are more records with the same alternate key value to be read; a value
of '00' is returned when the last record with that key value has been read.

Updating Records in a File


The COBOL language statements that can be used to update a file in the ENVIRON-
MENT DIVISION and DATA DIVISION are the same as those shown in Figure 30 on
page 100.

Figure 31 shows the statements that you can use in the PROCEDURE DIVISION for
sequential, line sequential, indexed, and relative files.

102 COBOL Set for AIX Programming Guide


COBOL Coding for Files

Figure 31. PROCEDURE DIVISION Statements Used to Update Files


Line Sequen-
Access Method Sequential tial Indexed Relative
ACCESS IS OPEN EXTEND OPEN EXTEND OPEN EXTEND OPEN EXTEND
SEQUENTIAL WRITE WRITE WRITE WRITE
CLOSE CLOSE CLOSE CLOSE
or or or
OPEN I-O OPEN I-O OPEN I-O
READ READ READ
REWRITE REWRITE REWRITE
CLOSE DELETE DELETE
CLOSE CLOSE
ACCESS IS Not Not OPEN I-O OPEN I-O
RANDOM applicable applicable READ READ
WRITE WRITE
REWRITE REWRITE
DELETE DELETE
CLOSE CLOSE
ACCESS IS Not Not OPEN I-O OPEN I-O
DYNAMIC: applicable applicable READ NEXT READ NEXT
Sequential Proc- READ PREVIOUS READ PREVIOUS
essing START START
CLOSE CLOSE
ACCESS IS Not Not OPEN I-O OPEN I-O
DYNAMIC: applicable applicable READ READ
Random Proc- WRITE WRITE
essing REWRITE REWRITE
DELETE DELETE
CLOSE CLOSE

Adding Records to a File


The COBOL WRITE statement adds a record to a file, without replacing any existing
records. The record to be added must not be larger than the maximum record size set
when the file was defined. Check the file status key after each WRITE statement.

Adding Records Sequentially


Use ACCESS IS SEQUENTIAL and code the WRITE statement to add records sequentially
to the end of a file that has been opened with either OUTPUT or EXTEND.

Sequential and line sequential files are always written sequentially.

For indexed files, new records must be written in ascending key sequence. If the file is
opened EXTEND, the record keys of the records to be added must be higher than the
highest primary record key on the file when the file was opened.

Chapter 7. Processing Files 103


COBOL Coding for Files

For relative files, the records must be in sequence. If you include a RELATIVE KEY
data-item in the SELECT clause, the relative record number of the record to be written is
placed in that data item.

Adding Records Randomly or Dynamically


When you write records to an indexed data set and ACCESS IS RANDOM or ACCESS IS
DYNAMIC, the records can be written in any order.

Replacing Records in a File


To replace records in a file, use REWRITE on a file that you have opened for I-O. If you
try to use REWRITE on a file that is not opened I-O, the record is not rewritten and the
status key is set to 49. Check the file status key after each REWRITE statement.
Ÿ For sequential files, the length of the record you rewrite must be the same as the
length of the original record.
Ÿ For indexed files, you can change the length of the record you rewrite.
Ÿ For variable-length relative files, you can change the length of the record you
rewrite.

To replace records randomly or dynamically, the record to be rewritten need not be


read by the COBOL program. Instead, to position the record you want to update:
Ÿ For indexed files, move the record key to the RECORD KEY data item, and then
issue the REWRITE.
Ÿ For relative files, move the relative record number to the RELATIVE KEY data item,
and then issue the REWRITE.

Deleting Records from a File


Open the file I-O and use the DELETE statement to remove an existing record from an
indexed or relative file. You cannot use DELETE on a sequential file or a line sequential
file.

When ACCESS IS SEQUENTIAL, the record to be deleted must first be read by the
COBOL program. The DELETE then removes the record that was just read. If the
DELETE is not preceded by a successful READ, the deletion is not done and the status
key value is set to 92.

When ACCESS IS RANDOM or ACCESS IS DYNAMIC, the record to be deleted need not
be read by the COBOL program. To delete a record, the key of the record to be
deleted is moved to the RECORD KEY data item and the DELETE is issued. Check the
file status key after each DELETE statement.

104 COBOL Set for AIX Programming Guide


Sorting and Merging

File Sorting and Merging


Arranging records in a particular sequence, a common requirement in data processing,
can be done using sort or merge operations:
Sort operation Accepts input that is not in sequence and produces output in a
requested sequence.
Merge operation Compares records from two or more sequenced files and combines
them in order.

COBOL has special language features that assist in sort and merge operations. For
information on the COBOL sort and merge language, see IBM COBOL Language Ref-
erence.

Basics of Sorting and Merging


To sort or merge files, do the following:

Figure 32 (Page 1 of 2). Preparing to Sort or Merge Files


Action Code
Describe sort files and merge SELECT statements in the FILE-CONTROL SECTION of the ENVI-
files. RONMENT DIVISION, and SD entries in the FILE SECTION of the
DATA DIVISION.

SELECT statements and SD entries are always needed for sort


files and merge files, even if you are only sorting or merging
data items from Working-Storage.
The files described in an SD entry is the working file used for a
sort or merge operation. You cannot perform any input/output
operations on this file.
Every SD entry must contain a record description. For
example:
SD SORT-WORK-1
RECORD CONTAINS 1ðð CHARACTERS.
ð1 SORT-WORK-1-AREA.
ð5 SORT-KEY-1 PIC X(1ð).
ð5 SORT-KEY-2 PIC X(1ð).
ð5 FILLER PIC X(8ð).
Describe the input and output SELECT statements in the FILE-CONTROL SECTION of the ENVI-
files, if any, for sorting or RONMENT DIVISION, and FD entries in the FILE SECTION of the
merging. DATA DIVISION.

Chapter 7. Processing Files 105


Sorting and Merging

Figure 32 (Page 2 of 2). Preparing to Sort or Merge Files


Action Code
Request the sort or merge SORT or MERGE statements in the PROCEDURE DIVISION.
operation.
The SORT or MERGE statement specifies the key fields in the
record upon which the sort or merge is to be sequenced. You
can code a key or keys as ascending or descending, or when
you code more than one key, as a mixture of the two.
You can mix SORT and MERGE statements in the same
program. A COBOL program can contain any number of sort
or merge operations.
In your COBOL program, you can perform the same sort or
merge multiple times, or perform multiple sorts or merges.
However, one operation must be completed before another can
begin.
For more information,see “The SORT Statement” on page 107
and “The MERGE Statement” on page 111.

Figure 33 on page 107 is an example of the ENVIRONMENT DIVISION and DATA DIVI-
SION entries needed to describe sort files and an input file.

106 COBOL Set for AIX Programming Guide


SORT Statement

ID Division.
Program-ID. SmplSort.
Environment Division.
Input-Output Section.
File-Control.
\
\ Assign Name For A Sort File Is
\ Treated As Documentation.
\
Select Sort-Work-1 Assign To SortFile.
Select Sort-Work-2 Assign To SortFile.
Select Input-File Assign To InFile.

Data Division.
File Section.
SD Sort-Work-1
Record Contains 1ðð Characters.
ð1 Sort-Work-1-Area.
ð5 Sort-Key-1 Pic X(1ð).
ð5 Sort-Key-2 Pic X(1ð).
ð5 Filler Pic X(8ð).

SD Sort-Work-2
Record Contains 3ð Characters.
ð1 Sort-Work-2-Area.
ð5 Sort-Key Pic X(5).
ð5 Filler Pic X(25).

FD Input-File
ð1 Input-Record Pic X(1ðð).
.
.
.
Working-Storage Section.
ð1 EOS-Sw Pic X.
ð1 Filler.
ð5 Table-Entry Occurs 1ðð Times
Indexed By X1 Pic X(3ð).
.
.
.

Figure 33. ENVIRONMENT DIVISION and DATA DIVISION Entries for a Sort Program

The SORT Statement


You can use the SORT statement to do the following:
Ÿ Use input or output procedures to add, delete, change, edit, or otherwise change
records.
– To request that input procedures be performed on the sort records before they
are sorted, use SORT . . . INPUT PROCEDURE.
See “Coding the Input Procedure” on page 109 for more information on input
procedures.

Chapter 7. Processing Files 107


SORT Statement

– To request that output procedures be performed on the sort records after they
are sorted, use SORT . . . OUTPUT PROCEDURE.
See “Coding the Output Procedure” on page 110 for more information on
output procedures.
Ÿ Sort data items (including tables) in Working-Storage.
Ÿ Read records directly into a new file without any preliminary processing (SORT . . .
USING).

Ÿ Transfer sorted records from the sort program directly to another file without any
further processing (SORT . . . GIVING).

SORT Program Organization


A COBOL program containing a sort operation can be organized so that one or more
input files are read and operated on by an input procedure. In the input procedure, a
RELEASE statement (analogous to the WRITE statement) releases a record to be sorted.
If you do not want to change or process the records in the files before the sorting oper-
ation begins, the SORT statement USING option releases the records in the files
unchanged to the new file.

The sort operation then arranges the entire set of records in the sequence specified by
the key(s).

After the sort, sorted records can be made available one at a time through a RETURN
statement to an output procedure. If you want to put the sorted records in files without
changing or processing these records, the SORT statement GIVING option names the
output files and writes the sorted records to the output files.

Setting the Sort Criteria


To set sort criteria:
1. In the record description of the file to be sorted, define the key or keys on which it
will be sorted.
The key used in the SORT statement cannot be variably located. (For more infor-
mation on variably located data items, see Appendix D, “Complex OCCURS
DEPENDING ON” on page 479.)
2. In the SORT statement, code the key on which the file will be sorted.
To sort on more than one key, list the keys in descending order of importance.

In the example below, SORT-GRID-LOCATION and SORT-SHIFT are defined in the DATA
DIVISION before they are used in the SORT statement.

The example also shows the use of an input and an output procedure. Use an input
procedure if you want to process the records before you sort them, and use an output
procedure if you want to further process the records after you sort them.

108 COBOL Set for AIX Programming Guide


Coding the Input Procedure

DATA DIVISION.
.
.
.
SD SORT-FILE
RECORD CONTAINS 115 CHARACTERS
DATA RECORD SORT-RECORD.

ð1 SORT-RECORD.
ð5 SORT-KEY.
1ð SORT-SHIFT PIC X(1).
1ð SORT-GRID-LOCATION PIC X(2).
1ð SORT-REPORT PIC X(3).
ð5 SORT-EXT-RECORD.
1ð SORT-EXT-EMPLOYEE-NUM PIC X(6).
1ð SORT-EXT-NAME PIC X(3ð).
1ð FILLER PIC X(73).

PROCEDURE DIVISION.
.
.
.
SORT SORT-FILE
ON ASCENDING KEY SORT-GRID-LOCATION SORT-SHIFT
INPUT PROCEDURE 6ðð-SORT3-INPUT
OUTPUT PROCEDURE 7ðð-SORT3-OUTPUT.
.
.
.

Alternate Collating Sequences


You can sort records on a user specified collating sequence for single byte character
keys. The default collating sequence is the collating sequence specified by the locale
setting in effect at compile time. To override the PROGRAM COLLATING SEQUENCE
specified either explicitly or by the default, use the COLLATING SEQUENCE option of the
SORT statement. You can use different collating sequences for multiple sorts in your
program.

For DBCS keys, the collating sequence is that specified by the locale setting in effect at
execution time.

Coding the Input Procedure


If you want to process the records in an input file before they are released to the sort
program, use the INPUT PROCEDURE option of the SORT statement. You might use an
input procedure to:
Ÿ Release data items to the new file from Working-Storage.
Ÿ Release records that have already been read in elsewhere in the program.
Ÿ Read records from an input file, select or process them, and release them to the
new file.

Chapter 7. Processing Files 109


Coding the Output Procedure

Each input procedure must be contained in either paragraphs or sections. For


example, to release records from Working-Storage (a table) to the new file:
SORT SORT-WORK-2
ON ASCENDING KEY SORT-KEY
INPUT PROCEDURE 6ðð-SORT3-INPUT-PROC
.
.
.

6ðð-SORT3-INPUT-PROC SECTION.
PERFORM WITH TEST AFTER
VARYING X1 FROM 1 BY 1 UNTIL X1 = 1ðð
RELEASE SORT-WORK-2-AREA FROM TABLE-ENTRY (X1)
END-PERFORM.

Transferring Records to the Sort Program


To transfer records to the new file, all input procedures must contain at least one
RELEASE or RELEASE FROM statement. To release A from X, for example, you can
enter:
MOVE X TO A.
RELEASE A.
Figure 34 compares the RELEASE and RELEASE FROM statements.

Figure 34. Comparison of RELEASE and RELEASE FROM


RELEASE RELEASE FROM
MOVE EXT-RECORD
TO SORT-EXT-RECORD
PERFORM RELEASE-SORT-RECORD PERFORM RELEASE-SORT-RECORD
. .
. .
. .
RELEASE-SORT-RECORD. RELEASE-SORT-RECORD.
RELEASE SORT-RECORD RELEASE SORT-RECORD FROM SORT-EXT-RECORD

Coding the Output Procedure


If you want to select, edit, or otherwise change sorted records before writing them from
the sort work file into another file, use the OUTPUT PROCEDURE option of the SORT
statement.

Each output procedure must be contained in either a section or a paragraph and must
include:
Ÿ At least one RETURN or RETURN INTO statement.
The RETURN statement makes each sorted record available to your output proce-
dure (the RETURN statement for a sort file is similar to a READ statement for an
input file).

110 COBOL Set for AIX Programming Guide


Success of Sort and Merge

You can use the AT END and END-RETURN phrases with the RETURN statement.
The imperative statements on the AT END phrase will be performed after all the
records have been returned from the sort file. The END-RETURN explicit scope ter-
minator serves to delimit the scope of the RETURN statement.
If you use the RETURN INTO statement, instead of RETURN, your records will be
returned to Working-Storage or to an output area.
Ÿ Any statements necessary to process the records that are made available, one at a
time, by the RETURN statement.

Restrictions on Input and Output Procedures


The following restrictions apply to the procedural statements in input and output
procedures:
Ÿ The input/output procedure must not contain any SORT or MERGE statements.
Ÿ The input/output procedure must not contain any STOP RUN, EXIT PROGRAM, or
GOBACK statements.

Ÿ You can use ALTER, GO TO, and PERFORM statements in the input/output proce-
dure to refer to procedure-names outside the input/output procedure. However,
you must return to the input/output procedure after a GO TO or PERFORM state-
ment.
Ÿ The remainder of the PROCEDURE DIVISION must not contain any transfers of
control to points inside the input/output procedure (with the exception of the return
of control from a Declarative Section).
Ÿ In a SORT or MERGE input or output procedure, calling a program is permitted, but
the called program cannot issue a SORT or MERGE statement and the called
program must return to the caller.

The MERGE Statement


You cannot specify an input procedure in the MERGE statement; use MERGE . . . USING.

The MERGE statement combines the files you name into one sequenced file. The files
to be merged must be already be in the same sorted sequence.

The merge operation compares keys in the records of the input files, and passes the
sequenced records one-by-one to the RETURN statement of an output procedure or to
the file named in the GIVING phrase.

Determining Whether the Sort or Merge Was Successful


The SORT or MERGE statement returns one of the following completion codes after a
sort is finished:
0 Successful completion of sort/merge
16 Unsuccessful completion of sort/merge

The return code or completion code is stored in a SORT-RETURN special register. The
contents of SORT-RETURN change after each SORT or MERGE statement is performed.

Chapter 7. Processing Files 111


SORT Special Registers

You should test for successful completion after each SORT or MERGE statement:
SORT SORT-WORK-2
ON ASCENDING KEY SORT-KEY
INPUT PROCEDURE IS 6ðð-SORT3-INPUT-PROC
OUTPUT PROCEDURE IS 7ðð-SORT3-OUTPUT-PROC.
IF SORT-RETURN NOT=ð
DISPLAY "SORT ENDED ABNORMALLY. SORT-RETURN = "
SORT-RETURN.
.
.
.
6ðð-SORT3-INPUT-PROC SECTION.
.
.
.
7ðð-SORT3-OUTPUT-PROC SECTION.
.
.
.

Prematurely Stopping a Sort or Merge Operation


To stop a sort or merge operation, use the SORT-RETURN special register. Move the
integer 16 into the register in:
Ÿ An input or output procedure.
Sort or merge processing will be stopped immediately after the next RELEASE or
RETURN statement is performed.

Ÿ A Declarative Section entered during processing of a USING or GIVING file.


Sort or merge processing will be stopped on exit from the declarative section.

Control then returns to the statement following the SORT or MERGE statement.

If you do not reference SORT-RETURN anywhere in your program, COBOL will test the
return code. If the code is 16, COBOL issues a run-time diagnostic message and ter-
minates the run unit (or the thread, in a multithread environment). If you test
SORT-RETURN for one or more (but not necessarily all) SORT or MERGE statements,
COBOL will not check the return code.

SORT Special Registers


You can use the SORT-RETURN and SORT-CONTROL special registers to get or test
values related to sort behavior.

The SORT-CONTROL special register is implicitly defined as


ð1 SORT-CONTROL GLOBAL PICTURE X(16ð) VALUE='file name'.
where file name is used as the system file identifier for the options file for the sort
product. You can assign to SORT-CONTROL the file name of a file that contains your

112 COBOL Set for AIX Programming Guide


STL file system

sort control statements. See SMARTsort for OS/2 and AIX for information about the
SMARTsort options file.

The STL File System


The STL file system supports sequential, indexed, and relative files on the local system.
It provides the basic file facilities that you need for accessing local files. It gives con-
formance to ANSI standards, good performance, and the ability to port easily between
AIX, OS/2, and Windows systems.

Line sequential files are the only files not supported.

The file system is safe for use with threads; it is your responsibility to ensure that mul-
tiple threads do not access COBOL buffers at the same time. Multiple threads can
perform operations on the same STL file, but you must use a pthread_cond_wait or its
equivalent to force all but one of them to wait for the file access to complete on the
active thread.

With the STL file system you can easily read and write files to be shared with PL/I
programs.

File Status and the STL File System


In the FILE STATUS clause of the FILE-CONTROL paragraph, you can specify one or two
names:
FILE STATUS data-name-1
or
FILE STATUS data-name-1 data-name-2

After an input/output operation, data-name-1 will contain a status code which is inde-
pendent of the file system used. If you specify data-name-2, it will contain a status
code that is file-system specific. In the case of the STL file system, data-name-2 will
contain one of the STL file system return codes shown in Figure 35.

See IBM COBOL Language Reference for additional information on the FILE STATUS
clause.

Figure 35 (Page 1 of 3). The STL file system Return Codes


Code Meaning Notes
0 Successful completion The input/output operation completed success-
fully.
1 Invalid operation This return code should not occur; it indicates
an error in the file system.
2 I/O error A call to an operating system I/O routine
returned an error code.
3 File not open Attempt to do an operation (other than OPEN)
on a file that is not open.

Chapter 7. Processing Files 113


STL file system

Figure 35 (Page 2 of 3). The STL file system Return Codes


Code Meaning Notes
4 Key value not found Attempt to read a record using key which is
not in the file.
5 Duplicate key value Attempt to use a key a second time for a key
which does not allow duplicates.
6 Invalid key number This return code should not occur; it indicates
an error in the file system.
7 Different key number This return code should not occur; it indicates
an error in the file system.
8 Invalid flag for the operation This return code should not occur; it indicates
an error in the file system.
9 End of file An end of file was detected. This is not an
error.
10 I/O operation must be preceed The operation is looking for the current record
by I/O GET op and the current record has not been defined.
11 Error return from get space The operating system indicates that not
routine enough memory is available.
12 Duplicate key accepted The operation specified a key and the key is a
duplicate. See the description of File Status 2
in IBM COBOL Language Reference.
13 Sequential access and key Sequential access was specified but the
sequence bad records are not in sequential order.
14 Record length < max key The record length does not allow enough
space for the all of the keys.
15 Access to file denied The operation system reported that it cannot
access the file. Either the file does not exist or
the user does not have the proper permission
of the operating system to access the file.
16 File Already exists You appempted to open a new file, but the
operating system reports that the file already
exists.
17 (Reserved)
18 File locked Attempt to open a file which is already open in
exclusive mode.
19 File table full The operating system reports that its file table
is full.
20 Handle table full The operating system reports that it cannot
allocate any more file handles.
21 Title does not say STL. Files opened for reading by the STL file
system must contain a header record that con-
tains “STL” at a certain offset in the file.
22 Bad indexcount arg for create This return code should not occur; it indicates
an error in the file system.

114 COBOL Set for AIX Programming Guide


STL file system

Figure 35 (Page 3 of 3). The STL file system Return Codes


Code Meaning Notes
23 Index or rel record > 64K Index and relative records are limted to a
length of 64K.
24 Error found in file header or STL files begin with a header. The header or
data in open of existing file its associated data has inconsistent values.
25 Indexed open on seq file Attempt to open a sequential file as an
indexed or relative file.
Note: The following are errors detected in the adapter open routines.
1000 Sequential open on indexed/rel Attempt to open an indexed or relative file as a
file sequential file.
1001 Relative open of indexed file Attempt to open a relative file as an indexed
file.
1002 Index open of rel file Attempt to open an indexed file as a sequen-
tial file.
1003 File does not exist The operating system reports that the file does
not exist.
1004 Number of keys differ Attempt to open a file with a different number
of keys.
1005 Record lengths differ Attempt to open a file with a different record
length.
1006 Record types differ Attempt to open a file with a different record
type.
1007 Key position or length differ Attempt to open a file with a different key posi-
tion or length.

Chapter 7. Processing Files 115


STRING and UNSTRING

Chapter 8. Error Handling


Anticipate the possibility of coding or system problems by putting code into your
program to handle them. Error handling code can be thought of as built-in distress
flares or lifeboats. If such code is not in your program, not only could output data and
files be corrupted, but you might not even be aware of the problem.

The action taken by your error-handling code can vary from trying to handle the situ-
ation and continue, to issuing a message, to halting the running of the program. In any
event, coding a warning message is a good idea.

You might be able to create your own error-detection routines for data-entry errors or
for errors as your installation defines them.

COBOL contains special elements to help you anticipate and correct error conditions.
These fall into the following main areas:
Ÿ “STRING and UNSTRING Operations.”
Ÿ “Arithmetic Operations” on page 117.
Ÿ “Input/Output Error Handling Techniques” on page 118.
Ÿ “CALL Statements” on page 126.

STRING and UNSTRING Operations


When stringing or unstringing data, the pointer might fall out of the range of the
receiving field. Here a potential overflow condition exists, but COBOL does not allow
the overflow to happen; the STRING/UNSTRING operation will not be completed and the
receiving field remains unchanged.

If you do not have an ON OVERFLOW clause on the STRING or UNSTRING statement,


control passes to the next sequential statement, and you are not notified of the incom-
plete operation.

Consider the following statement:


String Item-1 space Item-2 delimited by Item-3
into Item-4
with pointer String-ptr
on overflow
Display "A string overflow occurred"
End-String

116  Copyright IBM Corp. 1996, 1998


Arithmetic Operations

Figure 36. Data Values before and after the Statement is Performed
Data Value Value
Item PICTURE Before After
Item-1 X(5) AAAAA AAAAA
Item-2 X(5) EEEAA EEEAA
Item-3 X(2) EA EA
Item-4 X(8) ␣␣␣␣␣␣␣␣ ␣␣␣␣␣␣␣␣
String-ptr 9(2) ð ð
Note: The symbol ␣ represents a blank space.

Because String-ptr has a value of zero that falls short of the receiving field, an over-
flow condition occurs and the STRING operation is not completed (a String-ptr greater
than nine would cause the same result). If ON OVERFLOW had not been specified, you
would not be notified that the contents of Item-4 remain unchanged.

Arithmetic Operations
When your program performs arithmetic operations, the results might be larger than the
fixed-point field that is to hold them, or you might have tried a division by 0. In either
case, the ON SIZE ERROR clause after the ADD, SUBTRACT, MULTIPLY, DIVIDE, or
COMPUTE statement can handle the situation.

For ON SIZE ERROR to work correctly for fixed-point overflow and decimal overflow, you
must specify the TRAP(ON) run-time option.

If you code the ON SIZE ERROR clause, the imperative statement of your clause will be
performed and your result field will not be changed in the following five cases:
Ÿ Fixed-point overflow.
Ÿ Division by 0.
Ÿ Zero raised to the zero power.
Ÿ Zero raised to a negative number.
Ÿ A negative number raised to a fractional power.

Example of Checking for Division by Zero


Code your ON SIZE ERROR imperative statement so that it issues an informative
message. For example:

Chapter 8. Error Handling 117


I/O Error Handling

DIVIDE-TOTAL-COST.
DIVIDE TOTAL-COST BY NUMBER-PURCHASED
GIVING ANSWER
ON SIZE ERROR
DISPLAY "ERROR IN DIVIDE-TOTAL-COST PARAGRAPH"
DISPLAY "SPENT " TOTAL-COST, " FOR " NUMBER-PURCHASED
PERFORM FINISH
END-DIVIDE
.
.
.
FINISH.
STOP RUN.

In this example, if division by 0 occurs, the program will write out a message identifying
the trouble and halt program execution.

Input/Output Error Handling Techniques


When a program encounters an error in processing a file, whether logical errors in the
program or input/output errors on the disk, control returns to your COBOL program,
except in the following cases:
Ÿ There is no file status specified for the file
Ÿ There is no applicable EXCEPTION/ERROR declarative
Ÿ There is no INVALID KEY/AT END phrase specified for the error condition
In these cases, a COBOL run-time message is written and the run unit ends.

When an input/output statement operation fails, COBOL will not perform corrective
action for you. You choose whether your program will continue running after a less-
than-severe input/output error occurs.

COBOL offers five techniques for intercepting and handling certain input/output errors.
End-of-file phrase (AT END)
EXCEPTION/ERROR declarative
FILE STATUS key
File System Return Code
INVALID KEY phrase

The most important thing to remember about input/output errors is that you choose
whether your program will continue running after a less-than-severe input/output error
occurs. COBOL does not perform corrective action. If you choose to have your
program continue (by incorporating error-handling code into your design), you must also
code the appropriate error-recovery procedure; for example, a procedure to check the
file status key value.

Figure 37 on page 119 shows the flow of logic after a file system input/output error
occurs:

118 COBOL Set for AIX Programming Guide


I/O Error Handling

Terminate
Severe yes Issue error
COBOL
error message
Program
?

no

Set Status
Key (if
present)

Evaluate All
End-of-File error type Others

E3
Invalid
Key

User User User file


have EOF no have inv. no have assoc. no status no
imperative Key Imper- Error Declar- specified
? ative ative ?
? ?
yes E3 E3
yes yes yes

Execute Execute Execute Terminate the


EOF Invalid Key Error run unit with
Imperative Imperative Declarative a message

Return to
COBOL Program
at the end of
the I/O statement

Figure 37. Flow of Logic after a File System I/O Error

Chapter 8. Error Handling 119


I/O Error Handling

End-of-File Phrase (AT END)


An end-of-file condition might or might not represent an error. In many designs,
reading sequentially to the end of a file is done intentionally, and the AT END condition
is expected.

For example, suppose you are processing a file containing transactions in order to
update a master file:
PERFORM UNTIL TRANSACTION-EOF = "TRUE"
READ UPDATE-TRANSACTION-FILE INTO WS-TRANSACTION-RECORD
AT END
DISPLAY "END OF TRANSACTION UPDATE FILE REACHED"
MOVE "TRUE" TO TRANSACTION-EOF
END READ
.
.
END-PERFORM

Sometimes, however, the condition will reflect an error. You code the AT END phrase of
the READ statement to handle either case, according to your program design.

If you code an AT END phrase, on end-of-file the phrase is performed. If you do not
code an AT END phrase, the associated ERROR declarative is performed.

Any NOT AT END phrase you code is performed only if the READ statement completes
successfully. If the READ operation fails because of any condition other than end-of-file,
neither the AT END nor the NOT AT END phrase is performed. Instead, control passes
to the end of the READ statement after performing any associated declarative proce-
dure.

If you have coded neither an AT END phrase nor an EXCEPTION declarative procedure,
but have coded a status key clause for the file, control passes to the next sequential
instruction after the input/output statement that detected the end-of-file (where presum-
ably you have some coding to take appropriate action).

EXCEPTION/ERROR Declarative
You can code one or more ERROR declarative procedures in your COBOL program that
will be given control if an input/output error occurs. You can have:
Ÿ A single, common procedure for the entire program.
Ÿ Group procedures for each file open mode (whether INPUT, OUTPUT, I-O, or
EXTEND).

Ÿ Individual procedures for each particular file.

Place each such procedure in the declaratives section of your PROCEDURE DIVISION.
(For the syntax detail, see IBM COBOL Language Reference.

120 COBOL Set for AIX Programming Guide


I/O Error Handling

In your procedure, you can choose to try corrective action, retry the operation, continue,
or end execution. You can use the ERROR declaratives procedure in combination with
the file status key if you want a further analysis of the error.

If you continue processing a blocked file, you might lose the remaining records in a
block after the record that caused the error.

Write an ERROR declarative procedure if you want the system to return control to your
program after an error occurs. If you do not write an ERROR declarative procedure,
your job could be canceled or abnormally terminated after an error occurs.

File Status Key


The system updates the FILE STATUS key after each input/output statement is per-
formed on a file, placing values in the two digits of the file status key. In general, a
zero in the first digit indicates a successful operation, and a zero in both digits means
there is nothing abnormal to report. Possible file status codes are listed in the IBM
COBOL Language Reference. Establish a FILE STATUS key using the FILE STATUS
clause in the FILE-CONTROL paragraph and data definitions in the DATA DIVISION.
FILE STATUS IS data-name-1

data-name-1
Specifies the 2-character COBOL FILE STATUS key that should be defined in the
WORKING-STORAGE SECTION.

Restriction: The data-name in the FILE STATUS clause cannot be variably located.
(For more information on variably located data items, see Appendix D, “Complex
OCCURS DEPENDING ON” on page 479.)

Your program can check the COBOL FILE STATUS key to discover whether an error has
been made and, if so, what general type of error it is. For example, if a FILE STATUS
clause is coded like this:
FILE STATUS IS FS-CODE
FS-CODE is used by COBOL to hold status information like this:

FS─CODE
┌──────────┬──────────┐
│ 2 │ 1 │
└──────────┴──────────┘
& &
│ └────────── Sequence error

└────────── Invalid key

Follow these rules for each file:


Ÿ Define a different FILE STATUS key for each file.

Chapter 8. Error Handling 121


I/O Error Handling

This is especially important since it allows you to determine the cause of a file
input/output exception which might have occurred as a result of, for example, an
application logic error or a disk error.
Ÿ Check the FILE STATUS key after every input/output request.
After an input or output statement is performed, check the contents of the status
key; if it contains a value other than 0, your program can issue an error message,
or can act based on the value of the code placed in the status key.
You do not have to reset the status key code, because it is set following each
input/output attempt.
For VSAM, STL, and Encina SFS files, in addition to the file status key, you can
code a second identifier in the FILE STATUS clause to get more detailed information
on file system input/output requests. For further details, see “File System Return
Code” on page 123.
You can use the status key alone, or in conjunction with the INVALID KEY option, or
to supplement the EXCEPTION/ERROR declarative. Using the status key in this way
gives you precise information about the results of each input/output operation.

File Status Key Example


Figure 38 shows an example of the COBOL coding that performs a simple check on
the status key after opening a file.

IDENTIFICATION DIVISION.
PROGRAM-ID. SIMCHK.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT MASTERFILE ASSIGN TO AS-MASTERA
FILE STATUS IS MASTER-CHECK-KEY
.
.
DATA DIVISION.
.
.
WORKING-STORAGE SECTION.
ð1 MASTER-CHECK-KEY PIC X(2).
.
.
PROCEDURE DIVISION.
.
.
OPEN INPUT MASTERFILE
IF MASTER-CHECK-KEY NOT = "ðð"
DISPLAY "Non-zero file status returned from OPEN " MASTER-CHECK-KEY
.
.

Figure 38. Using the Status Key to Check an OPEN Statement

122 COBOL Set for AIX Programming Guide


I/O Error Handling

File System Return Code


Often the 2-character FILE STATUS code is too general to pinpoint the disposition of a
request. You can get more detailed information about file system input/output requests
by coding a second status area:
FILE STATUS IS data-name-1 data-name-2

data-name-1
Specifies the 2-character COBOL FILE STATUS key.

data-name-2
Specifies a data item that contains the file system return code when the COBOL
FILE STATUS key is not 0. data-name-2 is at least 6 bytes long.

STL File System


If data-name-2 is 6 bytes in length, it will contain the return code. If it
is greater than 6 bytes in length, it will also contain a message with
further information. For example, given the definition
ð1 my-file-status-2.
ð2 exception-return-value PIC 9(6).
ð2 additional-info PIC X(1ðð).
and an attempt to open a file with a different defintion than the one
with which it was created, return code 39 would be returned in
exception-return-value and a message telling you what keys you
need to perform the open would be returned in additional-info.
VSAM File System
data-name-2 must be defined as PICTURE X(n) and USAGE DISPLAY
attributes, where n is 6 or greater. The PICTURE string value repres-
ents the first n bytes of the VSAM reply message structure. If the size
of the reply message structure, m, is less than n, only the first m bytes
contain useful information.
For full details on the VSAM reply message structure, and VSAM file
handling in general, refer to the SMARTdata Utilities documentation for
your operating environment as listed in “Bibliography” on page 562.

See the IBM COBOL Language Reference for the rules for coding data-name-2.

For information about possible return codes from the STL file system, see “File Status
and the STL File System” on page 113.

For information on interpreting the codes for other file systems, refer to the relevant file
system documentation listed in “Bibliography” on page 562.

Checking File System Status Codes Example


Figure 39 on page 124 shows an example of a COBOL program that reads an indexed
file (starting on the fifth record), checks the file status key after each input/output
request, and displays the VSAM codes when the file status key is not zero. Figure 39
on page 124 also illustrates what the output from this program might look like,
assuming that the file being processed contains six records.

Chapter 8. Error Handling 123


I/O Error Handling

IDENTIFICATION DIVISION.
PROGRAM-ID. EXAMPLE.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT FILESYSFILE ASSIGN TO FILESYSFILE
ORGANIZATION IS INDEXED
ACCESS DYNAMIC
RECORD KEY IS FILESYSFILE-KEY
FILE STATUS IS FS-CODE, FILESYS-CODE.

DATA DIVISION.
FILE SECTION.
FD FILESYSFILE
RECORD 3ð.
ð1 FILESYSFILE-REC.
1ð FILESYSFILE-KEY PIC X(6).
1ð FILLER PIC X(24).
WORKING-STORAGE SECTION.
ð1 RETURN-STATUS.
ð5 FS-CODE PIC XX.
ð5 FILESYS-CODE PIC X(6).

PROCEDURE DIVISION.
OPEN INPUT FILESYSFILE.
DISPLAY "OPEN INPUT FILESYSFILE FS-CODE: " FS-CODE.

IF FS-CODE NOT = "ðð"


PERFORM FILESYS-CODE-DISPLAY
STOP RUN
END-IF.

MOVE "ððððð5" TO FILESYSFILE-KEY.


START FILESYSFILE KEY IS EQUAL TO FILESYSFILE-KEY.
DISPLAY "START FILESYSFILE KEY=" FILESYSFILE-KEY
" FS-CODE: " FS-CODE.

IF FS-CODE NOT = "ðð"


PERFORM FILESYS-CODE-DISPLAY
END-IF.

Figure 39 (Part 1 of 2). Getting File System Code Information on Input/Output Requests

124 COBOL Set for AIX Programming Guide


I/O Error Handling

IF FS-CODE = "ðð"
PERFORM READ-NEXT UNTIL FS-CODE NOT = "ðð"
END-IF.

CLOSE FILESYSFILE.
STOP RUN.

READ-NEXT.
READ FILESYSFILE NEXT.
DISPLAY "READ NEXT FILESYSFILE FS-CODE: " FS-CODE.
IF FS-CODE NOT = "ðð"
PERFORM FILESYS-CODE-DISPLAY
END-IF.
DISPLAY FILESYSFILE-REC.

FILESYS-CODE-DISPLAY.
DISPLAY "FILESYS-CODE ==>", FILESYS-CODE.

Figure 39 (Part 2 of 2). Getting File System Code Information on Input/Output Requests

INVALID KEY Phrase


The INVALID KEY phrase will be given control if an input/output error occurs because of
a faulty index key. You can include INVALID KEY phrases on READ, START, WRITE,
REWRITE, and DELETE requests for indexed and relative files.

INVALID KEY and ERROR Declaratives


INVALID KEY phrases differ from ERROR declaratives in these ways:

Ÿ INVALID KEY phrases operate for only limited types of errors, whereas the ERROR
declarative encompasses all forms.
Ÿ INVALID KEY phrases are coded directly onto the input/output verb, whereas ERROR
declaratives are coded separately.
Ÿ INVALID KEY phrases are specific for one single input/output operation, whereas
ERROR declaratives are more general.

If you code INVALID KEY in a statement that causes an INVALID KEY condition, control is
transferred to the INVALID KEY imperative statement. Here, any ERROR declaratives
you have coded are not performed.

NOT INVALID KEY


Any NOT INVALID KEY phrase that you code is performed only if the statement com-
pletes successfully. If the operation fails because of any condition other than INVALID
KEY, neither the INVALID KEY nor the NOT INVALID KEY phrase is performed. Instead
control passes to the end of the statement after performing any associated ERROR
declaratives.

Chapter 8. Error Handling 125


CALL Statements

Using FILE STATUS and INVALID KEY Example


Use the FILE STATUS clause with INVALID KEY to evaluate the status key and determine
the specific INVALID KEY condition.

For example, assume you have a file containing master customer records and need to
update some of these records with information in a transaction update file. You will
read each transaction record, find the corresponding record in the master file, and
make the necessary updates. The records in both files each contain a field for a cus-
tomer number, and each record in the master file has a unique customer number.

The FILE-CONTROL entry for the master file of customer records includes statements
defining indexed organization, random access, MASTER-CUSTOMER-NUMBER as the prime
record key, and CUSTOMER-FILE-STATUS as the file status key. The following example
shows how you can use FILE STATUS with the INVALID KEY to more specifically deter-
mine the cause of an I/O statement failure.
.
. (read the update transaction record)
.
MOVE "TRUE" TO TRANSACTION-MATCH
MOVE UPDATE-CUSTOMER-NUMBER TO MASTER-CUSTOMER-NUMBER
READ MASTER-CUSTOMER-FILE INTO WS-CUSTOMER-RECORD
INVALID KEY
DISPLAY "MASTER CUSTOMER RECORD NOT FOUND"
DISPLAY "FILE STATUS CODE IS: " CUSTOMER-FILE-STATUS
MOVE "FALSE" TO TRANSACTION-MATCH
END-READ

CALL Statements
When dynamically calling a separately compiled program, the program that you call
might be unavailable to the system. For example, the system could run out of storage
or it could be unable to locate the load module. If you do not have an ON EXCEPTION
or ON OVERFLOW clause on the CALL statement, your application might abend.

Use the ON EXCEPTION clause to perform a series of statements and to perform your
own error handling. For example:
MOVE "REPORTA" TO REPORT-PROG
CALL REPORT-PROG
ON EXCEPTION
DISPLAY "Program REPORTA not available, using REPORTB.'
MOVE "REPORTB" TO REPORT-PROG
CALL REPORT-PROG
END-CALL
END-CALL
If program REPORTA is unavailable, control will continue with the ON EXCEPTION clause.
ON EXCEPTION Limitation: The ON EXCEPTION clause applies only to the availability
of the called program. If an error occurs while the called program is running, the ON
EXCEPTION clause will not be performed.

126 COBOL Set for AIX Programming Guide


Part 2. Compiling, Linking, and Running Your Program
This part of the book provides instructions for compiling your program on the personal
workstation.

Chapter 9. Compiling, Linking, and Running Programs . . . . . . . . . . . . 128

Chapter 10. Compiler Options . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Chapter 11. Run-Time Options . . . . . . . . . . . . . . . . . . . . . . . . . 193

Chapter 12. Debugging Techniques . . . . . . . . . . . . . . . . . . . . . . . 197

 Copyright IBM Corp. 1996, 1998 127


Setting Environment Variables

Chapter 9. Compiling, Linking, and Running Programs


This chapter explains how to complete the following tasks:
Ÿ Set compiler and run-time environment variables
Ÿ Modify the default compiler and run-time configuration
Ÿ Compile and link programs
Ÿ Specify compiler options
Ÿ Understand and respond to compiler errors and messages
Ÿ Run compiled programs

Setting Environment Variables


Environmental variables are used to set values which can be read by programs or shell
scripts. For example, the COBOL run-time reads the environment variable COBPATH
when a program does a dynamic load of another program.

To specify environment variables, use the export command. There are two ways to set
environment variables:
Ÿ Temporarily, by defining the environment variable using the export command from
an AIX command prompt
Ÿ Persistently, by defining the environment variable using the export command in
the .profile file in your home directory

To temporarily change an environment variable, use export at the prompt presented in


an AIX command shell3 (for example, an XTERM window). This environment variable
definition applies to programs (on AIX, processes or child processes) run from that par-
ticular shell and any of its descendants (that is, any shells called directly or indirectly
from that shell). For example, the following AIX command syntax sets the COBPATH
environment variable (which defines the locations in which the COBOL run time locates
dynamically-accessed programs) to include two directories:
export COBPATH=/users/me/bin:/mytools/bin

To set an environment variable persistently, add the appropriate export command to


the .profile file in your home directory. If you define environment variables in your
.profile file, the values of these variables are defined automatically whenever you
begin an AIX session and apply to all shell processes.

To compile and run a simple COBOL program, the only environment variables that
need to be set are NLSPATH and LANG. These are usually set at installation.

3 All examples in this chapter assume that you are running the AIX implementation of the Korn shell. If you are running the Bourne
shell, you should separate the definition of your environment variables and the export of those variables into two steps rather than
combine them in a single shell command. The C shell uses setenv().

128  Copyright IBM Corp. 1996, 1998


COBOL Compiler Environment Variables

Definitions of COBOL Environment Variables


If you do not specify environment variables, either a default value is applied or the vari-
able is not defined. Environment variables are used by both the compiler and the run-
time library.

Compiler Environment Variables


The COBOL compiler uses the following environment variables. Note that because
COBOL words are defined to be case insensitive, all letters in COBOL words are
treated as upper cased letters, including text-name and library-name. Thus, environ-
ment variable names corresponding to such names must have upper-case names. For
example, the environment variable name corresponding to COPY MyCopy is MYCOPY.
COBOPT
Is one way of specifying COBOL compiler options. You may specify multiple
options. Separate each option by a space or comma. Surround the list of
options with quotation marks if it contains blanks or characters significant to the
AIX command shell. For example:
export COBOPT="TRUNC(OPT) TERMINAL"
Defaults: Individual compiler option defaults apply (see “Default Values for Com-
piler Options” on page 148).
SYSLIB
Specifies paths to be used for COPY statements with text-names that are unquali-
fied by library names and for DB2 INCLUDE statements. For a description of how
SYSLIB is used for COPY statements, see the description of Library-name and
text-name on page 190. See “SQL INCLUDE Statement” on page 356 for use
with SQL INCLUDE.
Library-name
A user-defined word that specifies the path for the library text.
Defaults: If you do not specify a library-name, the compiler searches the library
path(s) in the following order, the search ending when the file is found:
1. The current directory
2. The path(s) specified by the -Ixxx option, if set (see “Options Supported by
cob2” on page 136)
3. The paths specified by the SYSLIB environment variable
See the COPY statement on page 190 for the search rules for copy files.
Text-name
A user-defined word that specifies the path for the copybook text.
Defaults: If you do not set text-name as an environment variable, the compiler
uses the default search described on page COPY statement on page 190.

Chapter 9. Compiling, Linking, and Running Programs 129


COBOL Run-time Environment Variables

DB2DBDFT
Is one way of specifying the database for compiling your programs with
embedded SQL statements. See “Compiling with the DB2 Co-Processor” on
page 354 for more information on connecting to the target database.

Object-Oriented Programming Environment Variables


When you create object-oriented programs, there are different environment variables
you need to set. System Object Model (SOM) requires you to set SOM-specific envi-
ronment variables. For more information on environment variables needed when using
SOM to create object-oriented COBOL programs, see Chapter 14, “Using System
Object Model (SOM)” on page 269.

Run-Time Environment Variables


The COBOL run-time library uses the following environment variables:
assignment-name
The assignment-name can be any COBOL file that you want to specify in an
ASSIGN clause. This use of assignment-name follows the rules for a COBOL
word. For example:
export OUTPUTFILE=january.car_results
You can then use the environment variable as a COBOL user-defined word in an
ASSIGN clause. For example, based on the previous export statement, your
COBOL source program could include the following:
SELECT CARPOOL ASSIGN TO OUTPUTFILE
Because OUTPUTFILE was defined in the environment, this statement would result
in data being written to the file january.car_results.
Alternate File System: The general syntax involved in making an assignment
to a file stored in an alternate file system is:
ASSIGN TO FileSystemID-Filename

FileSystemID
Identifies the file system as one of the following:

STL For the STL file system.


VSAM For the VSAM file system. VSAM can be abbreviated to
VSA.

Note: Specify the VSAM file system when you want to access SFS
files.
If the file system specification is not provided, the run-time option
FILESYS is used to select the file system. If FILESYS is not set, the
default is VSAM.

130 COBOL Set for AIX Programming Guide


COBOL Run-time Environment Variables

Filename
The file you want to access.

Alternatively, you can specify an environment variable (for details, see the
IBM COBOL Language Reference).
Defaults: None. You must set all assignment-names. If you make an assign-
ment to a user-defined word that was not set as an environment variable, the
assignment is made to a file with the literal name of the user-defined word
(OUTPUTFILE in our earlier example). If the assignment is valid, this file is written
to the current directory.
COBMSGS
Specifies the name of a file to which run-time error messages will be written. To
capture run-time error messages into a file, use the export command to set
COBMSGS to a file name. If your program has a run-time error that terminates
the application, the file that COBMSGS is set to will contain the error message
indicating the reason for termination.
Defaults: None. If COBMSGS is not set, error messages are written to the ter-
minal.
COBPATH
Specifies directory path(s) to be used by the COBOL run time to locate dynam-
ically called programs. This variable must be set to run programs that require
dynamic loading. For example:
export COBPATH=/pgmpath/pgmdll
Defaults: None. You must define COBPATH if you have dynamically called pro-
grams.
COBRTOPT
Specifies the COBOL run-time options. The run-time options are separated by a
comma or a colon. Use parentheses or equal signs (=) as the delimiters for sub-
options. Options are not case sensitive.
For example:
export COBRTOPT="check(ON),UPSI(ðððððððð)"
is the equivalent of:
export COBRTOPT="CHECK=on,UPSI=ðððððððð"
Defaults: Individual run-time option defaults apply (see Chapter 11, “Run-Time
Options” on page 193).
EBCDIC_CODEPAGE
Specifies an EBCDIC code set applicable to the EBCDIC data being processed
by programs compiled with the CHAR(EBCDIC) or CHAR(S390) compiler option.
To set the EBCDIC code set, issue the command:
export EBCDIC_CODEPAGE=codepage
where codepage is the name of the code set to be used.

Chapter 9. Compiling, Linking, and Running Programs 131


COBOL Run-time Environment Variables

If EBCDIC_CODEPAGE is not set, it will default to the EBCDIC code page of the
current locale. If multiple code pages are available for the current locale the
CHAR(EBCDIC) compiler option must be set, “CHAR” on page 151 discusses this
option.
Refer to “Locales and Code Sets Supported on AIX” on page 408 for the sup-
ported code set translations.
LANG
Specifies the national language locale name in effect for message catalogs and
help files. LANG must always be set and is given an initial value during installa-
tion. The run-time library uses LANG to access the message catalog. For
example, the following command sets the language locale name to U.S. English:
export LANG=en_US
If LANG is not set correctly, run-time messages appear in an abbreviated form.
Therefore, if your messages appear incorrect, consult your installation documen-
tation to ensure that LANG is correctly defined.
Defaults: Set at installation of the operating system.
LC_COLLATE
Determines the locale to be used to define the behaviour of ranges, equivalence
classes, and multicharacter collating elements.
Defaults: The locale specified by the LANG environment variable is used.
LC_MESSAGES
Determines the locale which defines the language in which messages are written.
Defaults: The locale specified by the LANG environment variable is used.
LC_TIME
Determines the locale for date and time formatting information.
Defaults: The locale specified by the LANG environment variable is used.
LIBPATH
Specifies the full path name for the COBOL run-time library.
Defaults: Set at installation.
LOCPATH
Specifies the search path where the locale information database exists. It is a
colon-separated list of directory names. It is used at the time of setting up the
locale for a process.
NLSPATH
Specifies the full path name of message catalogs and help files. NLSPATH must
always be set and is given an initial value during installation. The run-time library
uses NLSPATH to access the message catalog.
You can set NLSPATH with the following commands:
DIR=xxxx
NLSPATH=$DIR/%L/%N:$NLSPATH
export NLSPATH

132 COBOL Set for AIX Programming Guide


COBOL Run-time Environment Variables

Where xxxx denotes the directory where COBOL was installed. The directory
xxxx must contain a directory xxxx/en_US (in the case of an U.S. English-
language setup) that contains the COBOL message catalog.
When you set NLSPATH, be sure to add to the NLSPATH, not replace it. Other
programs might use this environment variable.
If NLSPATH is not set correctly, run-time messages appear in an abbreviated
form. Therefore, if your messages appear incorrect, consult your installation doc-
umentation to ensure that NLSPATH is correctly defined.
Defaults: At COBOL Set for AIX installation, NLSPATH is set to
usr/lib/nls/msg/%L/%N:/usr/lib/nls/msg/prime/%N. COBOL Set for AIX instal-
lation puts the messages in usr/lib/nls/msg/xx, where xx is any language that
COBOL Set for AIX supports. The default is en_US.
SYSIN, SYSIPT, SYSOUT, SYSLIST, SYSLST, CONSOLE, SYSPUNCH, SYSPCH
These COBOL environment names are used as the environment variable names
corresponding to the mnemonic names used on ACCEPT and DISPLAY state-
ments. For example, the following command defines CONSOLE:
export CONSOLE=/users/mypath/myfile
CONSOLE could then be used in conjunction with the following COBOL source
code:
SPECIAL-NAMES.
CONSOLE IS terminal
...
DISPLAY 'Hello World' UPON terminal
Defaults: SYSIN and SYSIPT are directed to the logical input device (keyboard).
SYSOUT, SYSLIST, SYSLST, and CONSOLE are directed to the system logical
output device (screen). SYSPUNCH and SYSPCH are not assigned a value by
default and are not valid unless you explicitly define them.
TEMP
Specifies the location of temporary work files (if needed) for SORT and MERGE
functions. For example:
export TEMP=/tmp
Defaults: Vary. Set by the sort utility installation program.
TZ
This variable is used to describe the time zone information to be used by the
locale and has the following format:
export TZ=SSS[+|-]nDDD[,sm,sw,sd,st,em,ew,ed,et,shift]
The values for the TZ variable are defined below.

Chapter 9. Compiling, Linking, and Running Programs 133


COBOL Run-time Environment Variables

Figure 40. TZ Environment Variable Parameters


Variable Description Default Value
SSS Standard time zone identifier. This must be three EST
characters, must begin with a letter, and can contain
spaces.
n Difference (in hours) between the standard time zone 5
and coordinated universal time (UTC), formerly
Greenwich mean time (GMT). A positive number
denotes time zones west of the Greenwich meridian, a
negative number denotes time zones east of the
Greenwich meridian.
DDD Daylight saving time (DST) zone identifier. This must EDT
be three characters, must begin with a letter, and can
contain spaces.
sm Starting month (1 to 12) of DST. 4
sw Starting week (-4 to 4) of DST. 1
sd Starting day of DST: 0 to 6 if sw is not zero; 1 to 31 if 0
sw is zero.
st Starting time (in seconds) of DST. 3600
em Ending month (1 to 12) of DST. 10
ew Ending week (-4 to 4) of DST. -1
ed Ending day of DST: 0 to 6 if ew is not zero; 1 to 31 if 0
ew is zero.
et Ending time (in seconds) of DST. 7200
shift Amount of time change (in seconds). 3600

For example:
export TZ=CST6CDT
sets the standard time zone to CST, the daylight saving time to CDT, and sets a
difference of 6 hours between CST and UTC. It does not set any values for the
start and end of daylight saving time.
Other possible values are PST8PDT for Pacific United States and MST7MDT for
Mountain United States.
When TZ is not present, the default is EST5EDT, the default locale value. When
only the standard time zone is specified, the default value of n (difference in
hours from GMT) is 0 instead of 5.
If you give values for any of sm, sw, sd, st, em, ew, ed, et, or shift, you must give
values for all of them. If any of these values is not valid, the entire statement is
considered not valid, and the time zone information is not changed.

134 COBOL Set for AIX Programming Guide


Compiling and Linking Programs

Environment Variable Precedence: Some environment variables (such as COBPATH


and NLSPATH) define directories in which to search for files. If multiple directory paths
are listed, they are delimited by colons. Paths defined by environment variables are
evaluated in order, from the first path to the last in the SET statement. Therefore, if you
have multiple files with the same name that are defined in the paths of an environment
variable, be aware that the first located copy of the file is used.

For example, in the following COBPATH definition:


export COBPATH=/abc/def:/ghi

Directory /abc/def would be searched before /ghi.

Compiling and Linking Programs


The command cob2 invokes the COBOL compiler and linker.4 cob2 accepts options to
control the compilation and link-edit in any order on the command line. If you want to
compile multiple files, the filenames can be specified at any position in the command
syntax. However, all options and filenames should be separated by spaces.

If you compile with the THREAD option, use cob2_r rather than cob2. If you use the
SFS file system, use cob2_r4 rather than cob2. All the rules for cob2 apply equally to
cob2_r and cob2_r4.

The general syntax for cob2 is:

55──cob2──┬─────────┬──filenames──────────────────────────────────────5%
└─options─┘

For example, the following command:


cob2 -g -qlib filea.cbl fileb.cbl -qflag(w)

Is equivalent to:
cob2 filea.cbl -g -qflag(w) fileb.cbl -qlib

Usage Notes
1. Any options specified apply to all files on the command line.
2. Only files with the .cbl extension are passed to the compiler—cob2 passes all
other files to the linker. The linker accepts .o files, but does not accept .c files. If
you want to link C and COBOL files, first produce .o files using xlc -c.
3. The default location for compiler input and output is the current directory.
4. The linker causes execution to begin at the first main program. For example:

4 For information on ld, the AIX linker command, see the AIX Commands Reference.

Chapter 9. Compiling, Linking, and Running Programs 135


Compiling and Linking Programs

cob2 alpha.cbl beta.cbl


causes execution to begin with alpha. If x.c contains a C main program, then
xlc -c x.c
cobx x.o alpha.cbl
causes the C main program to be generated as the executable.

See also Chapter 23, “Building Shared Libraries” on page 386 for descriptions of Static
Linking and Shared Libraries, and how to create shared object code libraries.

Options Supported by cob2


-c Compile programs but do not link them.

| -cmain Make a C or PL/I object file containing a main routine5 the main entry
| point in the executable file.
| Warning: If a C or PL/I object file containing a main routine is linked
| with one or more COBOL object files, -cmain must be used to desig-
| nate the C or PL/I routine as the main entry point in the executable
| file; a COBOL program cannot be the main entry point in an execut-
| able file containing a C or PL/I main. Unpredictable execution
| behavior will occur if this is attempted and no diagnostics are issued.
| Note: -cmain is only required if -host is also specified.

-comprc_ok=n Controls the cob2 behavior on the return code from the compiler. If
the return code returned by the compiler is less than or equal to n,
cob2 continues to the link step, or, in the compile only case, exits with
a zero return code. If the return code returned by the compiler is
greater than n, cob2 exits with the same return code returned by the
compiler.
The default is: -comprc_ok=4.

-Fxxx Use xxx as a configuration file and a stanza rather than the defaults
specified in the /etc/cob2.cfg configuration file. xxx is one of:

Ÿ config_file:stanza,
Ÿ config_file, or
Ÿ :stanza

See “Modifying the Default Compiler Configuration” on page 139 for


information on creating your own configuration file.

-g Produce symbolic information used by the debugger.

| 5 In C, a main routine is identified by the function name main(). In PL/I, a main routine is identified by the PROC OPTIONS(MAIN)
| statement.

136 COBOL Set for AIX Programming Guide


Compiling and Linking Programs

-host Set all host data compiler options:

BINARY(S390)
CHAR(EBCDIC)
COLLSEQ(EBCDIC)
FLOAT(S390)

Convert COBOL program command line arguments to host format.


Note: The -host option will change the format of run-time command
line arguments from an array of pointers to an EBCDIC character
string. See “Command Line Arguments” on page 351.

-Ixxx Add a path xxx to the directories to be searched for COPYfiles if a


library-name or SYSLIB is not specified. Only a single path is allowed
per -I option. To add multiple paths, use multiple -I options. There
should be no spaces between -I and xxx. (This is upper-case “eye,”
not lower-case “el.”)
Use LIB: If you use the COPY statement, you must ensure that the
LIB compiler option is in effect.

For a description of the manner in which the compiler evaluates


paths for COPY files, see the description of the Library-name environ-
ment variable in “Run-Time Environment Variables” on page 130.

-main:xxx Make xxx the first file in the files list passed to the linker. The usage
of this option is to make the specified file the main program in the
executable file. xxx must uniquely identify the object file or the
archive library, and the extension must be either .o or .a respec-
tively.
If -main is not specified, the first object, archive library, or source file
specified on the cob2 command will be the first file in the files list
passed to the linker.
If the syntax of -main:xxx is invalid, or xxx is not the filename of an
object or source file processed by cob2, cob2 will terminate.

-o xxx Name the object module xxx (where xxx is any name). If the -o
option is not used, then the name of the object module defaults to
a.out.

-p Instructs the linker to set up the object file produced by the compiler
for AIX profiling6 (command used to evaluate program performance)
with minimum profiling information.

-pg Instructs the linker to set up the object file produced by the compiler

6 For information on prof, the AIX profiling command, see the AIX Commands Reference.

Chapter 9. Compiling, Linking, and Running Programs 137


Compiling and Linking Programs

for AIX graph profiling7 (command used to evaluate program perform-


ance) with maximum profiling information.

-qxxx Use the option xxx (where xxx is any compiler option) when calling
the compiler. If parentheses are part of the compiler (sub)option, or
several options are specified, they should be included in quotes. For
multiple options, each option should be delimited by a blank or
comma. There should be no spaces between -q and xxx.
For example,
-qoptiona,optionb
or
-q"optiona optionb"
Special Syntax
If you plan to use a shell script to automate your cob2 tasks, a
special syntax is provided for the -qxxx option. Use the following
syntax to prevent the command shell from passing invalid syntax to
cob2:

Ÿ Use “=” (equal sign) and “:” (colon) rather than “( )” (paren-
theses) to specify compiler suboptions. For example, use
-qBINARY=NATIVE:,ENTRYINT=OPTLINK:
rather than
-qBINARY(NATIVE),ENTRYINT(OPTLINK)
Ÿ Use “_” (underscore) rather than “ ' ” (apostrophe) where a com-
piler option requires a suboption to be delimited by apostrophes.
For example, use
-qEXIT=INEXIT=_String_,MYMODULE::
rather than
-qEXIT(INEXIT('String',MYMODULE))
Ÿ Do not use any blanks in the option string.

-v Display compile and link steps, and execute them.

-# Display compile and link steps, but do not execute them.

Examples using cob2


The following examples illustrate the use of cob2:
Ÿ To compile the file alpha.cbl, enter:
cob2 -c alpha.cbl

7 For information on gprof, the AIX graph profiling command, see the AIX Commands Reference.

138 COBOL Set for AIX Programming Guide


Compiling and Linking Programs

The compiled file is named alpha.o.


Ÿ To compile alpha.cbl and beta.cbl, enter:
cob2 -c alpha.cbl beta.cbl
The compiled files are named alpha.o and beta.o.
Ÿ To link two files together, compile them without the -c option. For example, to
compile and link alpha.cbl and beta.cbl and generate gamma, enter:
cob2 alpha.cbl beta.cbl -o gamma
This command creates alpha.o and beta.o, then links alpha.o, beta.o, and the
COBOL libraries. If the link step is successful, it produces an executable program
named gamma.
Ÿ In the following example:
cob2 alpha.o beta.cbl mylib.a -lmydir -lmylib2
beta.cbl is compiled, and:
alpha.o beta.o mylib.a -lmydir -lmylib2
is passed to the linker. If linking is successful, the executable a.out is produced
(a.out is the default output file if the cob2 -o option is not used).
Ÿ To compile with the LIST and NOADATA options, enter:
cob2 -qlist,noadata alpha.cbl
Note: There is no space between the -q and the options list.
Options should be delimited by commas or blanks if enclosed in quotes:
cob2 -q"list noadata" alpha.cbl

Modifying the Default Compiler Configuration


The default options used by cob2 are obtained from the configuration file, by default
/etc/cob2.cfg.

You can display the options used by cob2 by specifying the -# option. If you are using
the default configuration file, the command cob2 -# abc.cbl displays:
exec: /usr/lpp/cobol/bin/IGYCCOB2 abc.cbl
exec: /usr/bin/ld -bpT:ðx1ððððððð -bpD:ðx2ððððððð -bhalt:5 /lib/crtð.o abc.o
-lcob2s -l/usr/lpp/cobol/lib -lsmrtlite -l/usr/lpp/som/lib -lsomtk -liconv -lc
-lm

The cob2.cfg configuration file allows you to specify a number of items, such as default
options and the location of the compiler and library. If you edit or display (using the cat
command) /etc/cob2.cfg, you will see:
DEFLT: compiler1 = /usr/lpp/cobol/bin/IGYCCOB2
This is the line that specifies the COBOL compiler to use. Other lines in the file specify
the linker and various options.

Chapter 9. Compiling, Linking, and Running Programs 139


Compiling and Linking Programs

Tailoring a Configuration File


You can tailor your compilation by making a copy of /etc/cob2.cfg and changing the
copy to support specific compilation requirements or other COBOL compilation environ-
ments. To use your copy, specify the cob2 command with the -F option. For example:
cob2 myfile.cbl -F/u/myhome/myconfig.cfg
would use /u/myhome/myconfig.cfg instead of /etc/cob2.cfg as the configuration file.
See “Options Supported by cob2” on page 136 for a description of the -F option.

If you tailor the configuration file, you should check your modifications by issuing the
cob2 command with the -# option to display the effect of your changes.

In /etc/cob2.cfg are sections beginning cob2:, cob2_r:, and so on. These sections
are referred to as stanzas. You can list the supplied configuration files with the
command ls /usr/bin/cob2\. You will see /usr/bin/cob2, /usr/bin/cob2_r, and so
on. The file /usr/bin/cob2_r is linked to /usr/bin/cob2. Commands cob2 and cob2_r
execute the same module, but cob2 uses the cob2 stanza and cob2_r uses the cob2_r
stanza. You can add your own stanza, for example mycob2, and use it by specifying it
with the -F option:
cob2 myfile.cbl -F/u/myhome/myconfig.cfg:mycob2
Or you can define a mycob2 command:
ln -s /usr/bin/cob2 /u/myhome/mycob2
mycob2 myfile.cbl -F/u/myhome/myconfig
Or you can add mystanza to /etc/cob2.cfg and:
ln -s /usr/bin/cob2 mycob2
mycob2 myfile.cbl

Note that whatever directory you name in the ln command (such as /u/myhome above)
must be in your PATH.

The items in each stanza are listed in “Stanzas in the Configuration File.” You can
change any of them. For example, to add a library to the list of libraries used by the
linker, change the runlib2 option.

Stanzas in the Configuration File


A stanza in the configuration file can contain the following attributes:

Figure 41 (Page 1 of 2). Stanza Attributes


Attribute Description
compiler1 The path name of the COBOL compiler component. The default for cob2 is
/usr/lpp/cobol/bin/IGYCCOB2
crt Path name of the object file passed as the first parameter to the linker. If
you do not specify either the -p or -pg option, the value of crt is used. The
default is /lib/crtO.o

140 COBOL Set for AIX Programming Guide


Compiling and Linking Programs

Figure 41 (Page 2 of 2). Stanza Attributes


Attribute Description
qcrt Path name of the object file passed as the first parameter to the linker. If
you specify the -pg option, the value of gcrt is used. The default is
/lib/grtO.o.
ld Path name to be used to link COBOL programs. The default is
/usr/bin/ld.
ldflags A string of option flags, separated by commas, to be passed to the linker.
mcrt Path name of the object file passed as the first parameter to the linker, if
you have specified the -p option. The default is /lib/mcrtð.o.
proflibs Profiling libraries used by the linker, separated by commas. The default is
-l/lib/profiled, -l/usr/lib/profiled .
runlib1 A library option, followed by runlib2, that the compiler passes as a param-
eter to the linker to specify the COBOL main library for linking for both pro-
filing and non-profiling. The default is -lcob2s.
runlib2 Libraries used by the linker, separated by commas; used for both profiling
and nonprofiling. The default is -lsmrtlite, -l/usr/lpp/som/lib,
-lsomtk, -lionv, -lc_r, -lm
use Stanza from which attributes are taken, in addition to the local stanza. For
single-valued attributes, values in the use stanza apply if no value is pro-
vided in the local, or default, stanza. For comma-separated lists, the values
from the use stanza are added to the values from the local stanza.

Alternative Ways to Specify Compiler Options


“Compiling and Linking Programs” on page 135 explains how to specify compiler
options using the cob2 command. There are other ways to select the options used to
compile your programs. Here are three additional methods:
1. Specification by way of \control or PROCESS (CBL) statements.
2. Specifying compiler options as options to the cob2 command. The cob2 command
can be used on the command line, in a shell script, or in a makefile.
3. The COBOPT environment variable (See “Definitions of COBOL Environment
Variables” on page 129).

These means of specification are listed in order of precedence. For example, an option
specified using PROCESS overrides every other option specification except for non-
overridable options selected during product installation.

Specifying Compiler Options with the PROCESS (CBL) Statement


You can code compiler options on the PROCESS statement in your COBOL source pro-
grams. The PROCESS statement is placed before the IDENTIFICATION DIVISION header
and has the following format:

Chapter 9. Compiling, Linking, and Running Programs 141


Compiler-Detected Errors and Messages

55──┬─CBL─────┬──┬──────────────┬─────────────────────────────────────5%
└─PROCESS─┘ └─options-list─┘

PROCESS Statement Rules


Ÿ Your programming organization can inhibit the use of PROCESS statements with the
default options module of the COBOL compiler. When PROCESS statements are
found in a COBOL program where not allowed by the organization, the COBOL
compiler generates error diagnostics.
Ÿ One or more blanks must separate PROCESS and the first option in options-list.
Separate options with a comma or a blank. Do not imbed spaces in options.
Ÿ The PROCESS statement must be placed before any comment lines or compiler-
directing statements.
Ÿ PROCESS can start in columns 1 through 66. A sequence field is allowed in
columns 1 through 6. When used with a sequence field, PROCESS can start in
columns 8 through 66. If used, the sequence field must contain six characters, and
the first character must be numeric.
You can use CBL as a synonym for PROCESS. CBL can start in columns 1 through
70. When used with a sequence field, CBL can start in columns 8 through 70.
Ÿ You can use more than one PROCESS statement. If multiple PROCESS statements
are used, they must follow one another with no intervening statement of any other
type.
Ÿ Options cannot be continued across multiple PROCESS statements.

Compiler-Detected Errors and Messages


As the compiler processes your source program, it checks for COBOL language errors
you might have made. For each error discovered, the compiler issues a message.
These messages are included in the compilation listing (subject to the FLAG option).
The compiler listing file has the same name as the compiler source file, with the file
extension .lst. For example, the compiler listing for myfile.cbl would be myfile.lst.
The listing is written to the directory from which cob2 was run.

Each message does the following:


Ÿ Explains the nature of your error
Ÿ Identifies the compiler phase that detected the error
Ÿ Identifies the severity level of the error

Wherever possible, the message provides specific instructions for correcting the error.

Compiler Error Messages


The messages for errors found during processing of compiler options, CBL and
PROCESS statements, or BASIS, COPY, and REPLACE statements are displayed near the
top of your listing.

142 COBOL Set for AIX Programming Guide


Compiler-Detected Errors and Messages

The messages for compilation errors found in your program (ordered by line number)
are displayed near the end of the listing for each program.

A summary of all errors found during compilation is displayed near the bottom of your
listing. Each message issued by the compiler is of the following form:

Format
nnnnnn IGYppxxxx-l message-text

nnnnnn
The number of the source statement of the last line the compiler was processing.
Source statement numbers are listed on the source printout of your program. If
you specified the NUMBER option at compile time, these are your original source
program numbers. If you specified NONUMBER, the numbers are those generated
by the compiler.

IGY
The prefix that identifies this message as coming from the COBOL compiler.

pp Two characters that identify which phase of the compiler discovered the error. As
an application programmer, you can ignore this information, unless you are diag-
nosing a suspected compiler error. In that case, contact IBM for support.

xxxx
A 4-digit number that identifies the error message.

l A character that indicates the severity level of the error: I, W, E, S, or U (see


“Compiler Error Message Codes”).

message-text
The message text itself which, in the case of an error message, is a short explana-
tion of the condition that caused the error.

Remember, if you used the FLAG option to suppress messages, there might be addi-
tional errors in your program.

Compiler Error Message Codes


Errors the compiler can detect fall into five categories of severity:

I Informational An informational-level message is an aid to you. No action is


(Return Code=0) required and the program executes correctly as it stands.
W Warning A warning-level message calls attention to a possible error. It
(Return Code=4) is probable that the program executes correctly as written.
E Error An error-level message indicates a condition that is definitely
(Return Code=8) an error. The compiler has attempted to correct the error but
the results of program execution might not be what you expect.
You should correct the error.

Chapter 9. Compiling, Linking, and Running Programs 143


Compiler-Detected Errors and Messages

S Severe A severe-level message indicates a condition that is a serious


(Return Code=12) error. The compiler was unable to correct the error. The
program does not execute correctly, and execution should not
be attempted.
U Unrecoverable An unrecoverable-level message indicates an error condition of
(Return Code=16) such magnitude that the compilation was terminated.

In the following example, the part of the statement that caused the message to be
issued is enclosed in quotes.

..
.
LineID Message code Message text

2 IGYDSððð9-E "PROGRAM" should not begin in area "A". It was processed as if found in area "B".

2 IGYDS1ð89-S "PROGRAM" was invalid. Scanning was resumed at the next area "A" item, level-number,
or the start of the next clause.

2 IGYDSðð17-E "ID" should begin in area "A". It was processed as if found in area "A".

2 IGYDS1ðð3-E A "PROGRAM-ID" paragraph was not found. Program name "CBLPGMð1" was assumed.

2 IGYSC1ð82-E A period was required. A period was assumed before "ID".

2 IGYDS11ð2-E Expected "DIVISION", but found "ALONGPRO". "DIVISION" was assumed before "ALONGPRO".

2 IGYDS1ð82-E A period was required. A period was assumed before "ALONGPRO".

2 IGYDS1ð89-S "ALONGPRO" was invalid. Scanning was resumed at the next area "A" item, level-number,
or the start of the next clause.

2 IGYDS1ðð3-E A "PROGRAM-ID" paragraph was not found. Program name "CBLPGMð2" was assumed.

3 IGYPSðð17-E "PROCEDURE" should begin in area "A". It was processed as if found in area "A".

34 IGYSCð137-E Program-name "ALONGPRO" did not match the name of any open program. The "END PROGRAM" statement
was assumed to have ended program "CBLPGMð2".

34 IGYSCð136-E Program "CBLPGMð1" required an "END PROGRAM" statement at this point in the program.
An "END PROGRAM" statement was assumed.
Messages Total Informational Warning Error Severe Terminating

Printed: 12 1ð 2
..
.

Correcting Mistakes in Your Source Program


Messages about source coding errors indicate where the error happened (LINEID) and
the text of the message tells you what the problem is. With this information, you can
correct the source program and re-compile.

Although you should try to correct errors, it is not necessary to fix all of them. A
W-level or I-level message can be left in a program without much risk, and you might
decide that the recoding and compilation needed to remove the error are not worth the
effort. On the other hand, S-level and E-level errors indicate probable program failure
and should be corrected.

U-level errors are in a class by themselves. Here, you have no choice but to correct
the error, because the compiler is forced to end early and does not produce complete

144 COBOL Set for AIX Programming Guide


Running COBOL Programs

object code and listing. In contrast with the four lower levels of errors, a U-level error
might not result from a mistake in the source program. It could come from a flaw in the
compiler itself, or in the operating system.

After correcting the errors in your source program, re-compile the program. If this
second compilation is successful, go on to the link-editing step. If the compiler still
finds problems, repeat the above procedure until only informational messages are
returned.

Generating a List of All Compiler Error Messages


You can generate a complete listing of compiler diagnostic messages, with their expla-
nations, by compiling a program with a program-name of ERRMSG specified in the
PROGRAM-ID paragraph. The rest of the program can be omitted. For example:
Identification Division.
Program-ID. ErrMsg.

The listing that is produced includes messages from other IBM COBOL platforms, such
as OS/2, Windows, OS/390, and VM. Some messages do not apply to AIX.

Running COBOL Programs


To run a COBOL program, first make sure that any needed environment variables are
set (see “Setting Environment Variables” on page 128). Then type the name of the
executable module on the command line or execute a command file which invokes the
module. For example, if
cob2 alpha.cbl beta.cbl -o gamma
is successful, you can execute the program by typing:
gamma

If your program uses an environment variable name to assign a value to a system file
name, set the environment variable before typing the command which executes the
program.

If the run-time routines detect an error, they send a message to the error unit. Error
messages show what routine caused the error.

If run-time messages are abbreviated or incomplete, one or both of the following envi-
ronment variables might be incorrectly set:
Ÿ LANG
Ÿ NLSPATH

If a run-time error is severe, AIX creates a core file (that is, a file named core in the
current directory). You can use the COBOL Set for AIX debugger to examine the state
of the program at the time of the error. If the program was compiled with the -g option,
then the debugger will show symbolic and line number information. To use the
debugger to examine a core file, type the command xldb -co xxx, where xxx is the

Chapter 9. Compiling, Linking, and Running Programs 145


Running COBOL Programs

name of your program. For more information, click on the word “help” when the xldb
screen appears.

146 COBOL Set for AIX Programming Guide


Compiler Options Summary

Chapter 10. Compiler Options


You can direct and control compilation with the following:
Ÿ Compiler options
Ÿ Compiler-directing statements (compile directives)

Compiler options are listed and described in alphabetical order in “Compiler Option
Descriptions” on page 149. Compiler-directing statements are listed at the end of this
chapter, on page 187.

Compiler Options Summary


Compiler options affect the aspects of your program listed in Figure 42.

Figure 42 (Page 1 of 2). List of Compiler Options


Compiler Found on
Aspect of Your Program Option Abbreviations Page
Source language APOST None 173
CURRENCY CURR|NOCURR 154
LIB None 167
NUMBER NUM|NONUM 170
QUOTE Q 173
SEQUENCE SEQ|NOSEQ 175
SQL None 177
WORD WD|NOWD 184
| Date processing DATEPROC DP 155
| YEARWINDOW YW 186
Maps and listings LINECOUNT LC 168
LIST None 168
MAP None 169
SOURCE S|NOS 176
SPACE None 177
TERMINAL TERM|NOTERM 178
VBREF None 184
XREF X|NOX 185
Object module generation COMPILE C|NOC 153
OPTIMIZE OPT|NOOPT 171
PGMNAME PGMN(U|M) 172
SEPOBJ None 174

 Copyright IBM Corp. 1996, 1998 147


Compiler Options Summary

Figure 42 (Page 2 of 2). List of Compiler Options


Compiler Found on
Aspect of Your Program Option Abbreviations Page
Object code control BINARY None 150
CHAR None 151
FLOAT None 165
TRUNC None 180
ZWB None 187
CALL statement behaviour DYNAM DYN|NODYN 156
Debugging and diagnostics FLAG F|NOF 162
FLAGSTD None 163
TEST None 179
SSRANGE SSR|NOSSR 178
Other ADATA None 149
ANALYZE None 149
CALLINT None 150
COLLSEQ None 153
ENTRYINT None 157
EXIT EX(INX,LIBX,PRTX,ADX) 157
IDLGEN IDL|NOIDL 165
| MAXMEM None 169
PROFILE None 173
SIZE SZ 176
SPILL None 177
THREAD None 179
TYPECHK TC|NOTC 183
| WSCLEAR None 185

Default Values for Compiler Options


The default options that were set up when your compiler was installed are in effect for
your program unless you override them with other options. To find out the default com-
piler options in effect, run a test compilation without specifying any options; the output
listing lists the default options specified by your installation.
Non-overridable Options: In some installations, certain compiler options are set up
so that you cannot override them. If you have problems, see your system adminis-
trator.

Performance Considerations
The CHAR, DYNAM, FLOAT, OPTIMIZE, SSRANGE, TEST, and TRUNC compiler options
can all affect run-time performance.

148 COBOL Set for AIX Programming Guide


ANALYZE Compiler Option

Compiler Option Descriptions


The compiler option descriptions that follow are given in alphabetical order. For a list of
compiler options by effect, refer to Figure 42 on page 147.
Installation Defaults: The defaults listed with the options below are the defaults
shipped with the product. They might have been changed by your installation.

ADATA
55──┬─ADATA───┬───────────────────────────────────────────────────────5%
└─NOADATA─┘

Default is: NOADATA

Abbreviations are: None

Use ADATA when you want the compiler to create a SYSADATA file, which contains
records of additional compilation information. This information is used by other tools,
which will set ADATA ON for their use. The size of this file generally grows with the size
of the associated program.

You cannot specify ADATA in a PROCESS (CBL) statement; it can be specified only:
Ÿ On invocation of the compiler using an option list
Ÿ As a command option
Ÿ As an installation default

See “EXIT” on page 157 for information on using SYSADATA with your compiler-exit
module.

ANALYZE
55──┬─ANALYZE───┬─────────────────────────────────────────────────────5%
└─NOANALYZE─┘

Default is: NOANALYZE

Abbreviations are: None

Use ANALYZE when you want the compiler to check the syntax of embedded SQL and
CICS statements in addition to native COBOL statements.

No executable code is generated when this compiler option is specified, regardless of


the COMPILE|NOCOMPILE setting. The ANALYZE option also enables
COPY/BASIS/REPLACE processing, regardless of the LIB|NOLIB setting.

Chapter 10. Compiler Options 149


CALLINT Compiler Option

You can specify the ADATA option with this option to create a SYSADATA file for later
analysis by program understanding tools, such as the Year 2000 tool included with the
Professional Edition of IBM VisualAge COBOL.

This option may be set as the installation default option or as a compiler invocation
option, but may not be set on a CBL or PROCESS statement.

The specification of the ANALYZE option forces the handling of the following character
strings as reserved words:
CICS
EXEC
END-EXEC
SQL

APOST
See “QUOTE/APOST” on page 173.

BINARY
55──BINARY(─┬─NATIVE─┬─)──────────────────────────────────────────────5%
├─S37ð───┤
└─S39ð───┘

Default is: NATIVE

Abbreviations are: None

This option is treated as a comment.

CALLINT
55──CALLINT(─┬─SYSTEM───┬──┬─────────────────────┬─)──────────────────5%
├─OPTLINK──┤ └─,──┬─DESC─────────┬─┘
├─FAR16────┤ ├─DESCRIPTOR───┤
├─PASCAL16─┤ ├─NODESC───────┤
└─CDECL────┘ └─NODESCRIPTOR─┘

Default is: CALLINT(SYSTEM,NODESC)

Abbreviations are: None

This option is treated as a comment.

150 COBOL Set for AIX Programming Guide


CHAR Compiler Option

CHAR
55──CHAR(─┬─NATIVE─┬─)────────────────────────────────────────────────5%
├─EBCDIC─┤
└─S39ð───┘

Default is: CHAR(NATIVE)

Abbreviations are: None

Specify CHAR(NATIVE) to use the native character representation format of the platform.
For COBOL Set for AIX, this is ASCII.

CHAR(EBCDIC) and CHAR(S390) are synonymous and indicate that DISPLAY data items
are in the data representation of System/390 (EBCDIC).

The following are affected by the CHAR(EBCDIC) compiler option:


Ÿ USAGE DISPLAY items
– Single byte characters with USAGE DISPLAY, and double byte characters with
USAGE DISPLAY-1, are treated as EBCDIC:
- ASCII data is converted to EBCDIC on ACCEPT from the terminal.
- EBCDIC data is converted to ASCII on DISPLAY to the terminal.
- The EBCDIC equivalent of an ASCII literal is used for assignment to
EBCDIC character data. See Figure 43 on page 152 for the rules on the
compares of character data with the CHAR(EBCDIC) option in effect.
- Editing is also done with EBCDIC characters.
- Any padding is done using EBCDIC spaces. This includes alphanumeric
operations (For example, assignments and compares) on group items
regardless of the definition of the elementary items in the group items.
- Figurative constant SPACE/SPACES used in a VALUE clause for, an assign-
ment to, or in a relational condition with a DISPLAY item is treated as
single byte EBCDIC spaces (that is, X'40').
- CLASS tests are performed based on EBCDIC value ranges.
- The program name in CALL identifier, CANCEL identifier, or in the Format
6 SET statement is converted to ASCII characters if the identifier is
EBCDIC.
- The file name in the data name in ASSIGN USING data-name is con-
verted to ASCII characters if the data name is EBCDIC.
- The file name in SORT-CONTROL is converted to ASCII characters
before being passed to the Sort/Merge function.
Note that the SORT-CONTROL special register has the implicit USAGE
DISPLAY definition.

Chapter 10. Compiler Options 151


CHAR Compiler Option

– Zoned decimal data (numeric picture with USAGE DISPLAY) and external
floating point data. For example, zoned decimal PIC S9 value “1” is treated as
X'C1' instead of X'31'.
Ÿ Group items
Group items are treated similar to USAGE DISPLAY items. Note that any USAGE
clause on a group item applies to the elementary items within the group and not to
the group itself.

Hexadecimal literals are assumed to represent EBCDIC characters if the literals are
assigned to, or compared with, character data. For example, X'C1' will compare equal
to an alphanumeric item with the value “A.”

Figurative constants, HIGH-VALUE, LOW-VALUE, SPACE/SPACES, ZERO/ZEROS,


and QUOTE/QUOTES are treated logically as their EBCDIC character representations
for assignments and/or comparisons with EBCDIC characters.

In comparisons between non-numeric DISPLAY items, the collating sequence is the


ordinal sequence of the characters based on their binary (hexadecimal) values (as
modified by the alternate collating sequence for the single byte characters, if specified).
The collating sequence for EBCDIC characters is not affected by the locale setting or
the COLLSEQ compiler option.

Figure 43 summarizes the conversion and the collating sequence applicable based on
the types of data (ASCII, EBCDIC) and the COLLSEQ option in effect when PROGRAM
COLLATING SEQUENCE is not specified. If it is specified, the source specification has
precedence over the compiler option specification.

Figure 43. Collating Sequence Summary


Comparands COLLSEQ(BIN) COLLSEQ(NATIVE) COLLSEQ(EBCDIC)
Both ASCII No conversion is performed. No conversion is performed. Both comparands are con-
The comparison is based on The comparison is based on verted to EBCDIC. The com-
the binary value (ASCII). the current locale. parison is based on the binary
value (EBCDIC).
Mixed ASCII The EBCDIC comparand is The EBCDIC comparand is The ASCII comparand is con-
and EBCDIC converted to ASCII. The converted to ASCII. The verted to EBCDIC. The com-
comparison is based on the comparison is based on the parison is based on the binary
binary value (ASCII). current locale. value (EBCDIC).
Both EBCDIC No conversion is performed. The comparands are con- No conversion is performed.
The comparison is based on verted to ASCII. The com- The comparison is based on
the binary value (EBCDIC). parison is based on the the binary value (EBCDIC).
current locale.

| Object-oriented programs: Do not specify CHAR(EBCDIC) in object-oriented pro-


| grams.

For additional information about the CHAR compiler option, see Appendix B,
“System/390 Host Data Type Considerations” on page 469.

152 COBOL Set for AIX Programming Guide


COMPILE Compiler Option

COLLSEQ
55──COLLSEQ(─┬─NATIVE─┬─)─────────────────────────────────────────────5%
├─EBCDIC─┤
└─BIN────┘

Default is: COLLSEQ(BIN)

Abbreviations are: None

Specify COLLSEQ(EBCDIC) to use the EBCDIC collating sequence rather than the ASCII
collating sequence.

Specify COLLSEQ(BIN) to use the hex values of the characters; the locale setting has no
effect. This setting will give better execution-time performance.

If you use the PROGRAM-COLLATING-SEQUENCE clause in your source with an


alphabet-name of STANDARD-1, STANDARD-2, or EBCDIC, the COLLSEQ option will be
ignored. If you specify PROGRAM COLLATING SEQUENCE IS NATIVE, the value of
NATIVE is taken from the COLLSEQ option.

Otherwise, when the alphabet-name specified on the PROGRAM-COLLATING-SEQUENCE


clause is defined with literals, the collating sequence used is that given by the COLLSEQ
option, modified by the user-defined sequence given by alphabet-name.

COMPILE
55──┬─COMPILE────────────┬────────────────────────────────────────────5%
├─NOCOMPILE──────────┤
└─NOCOMPILE(─┬─W─┬─)─┘
├─E─┤
└─S─┘

Default is: NOCOMPILE(S)

Abbreviations are: C|NOC

Use the COMPILE option only if you want to force full compilation even in the presence
of serious errors. All diagnostics and object code will be generated. Do not try to run
the object code generated if the compilation resulted in serious errors—the results
could be unpredictable or an abnormal termination could occur.

Use NOCOMPILE without any suboption to request a syntax check (only diagnostics
produced, no object code).

Use NOCOMPILE with W, E, or S for conditional full compilation. For meanings of error
codes, see “Compiler-Detected Errors and Messages” on page 142. Full compilation
(diagnosis and object code) will stop when the compiler finds an error of the level you
specify (or higher), and only syntax checking will continue.

Chapter 10. Compiler Options 153


CURRENCY Compiler Option

If you request an unconditional NOCOMPILE, the following options have no effect


because no object code will be produced:
LIST
SSRANGE
OPTIMIZE
TEST

CURRENCY
55──┬─CURRENCY(literal)─┬─────────────────────────────────────────────5%
└─NOCURRENCY────────┘

Default is: NOCURRENCY

The default currency symbol is the dollar sign ($). You can use the CURRENCY option
to provide an alternate default currency symbol to be used for the COBOL program.

NOCURRENCY specifies that no alternate default currency symbol will be used.

To change the default currency symbol, use the CURRENCY(literal) option where literal
is a valid COBOL non-numeric literal (including a hex literal) representing a one-byte,
printable ASCII character that must not be any of the following:
Ÿ Digits zero (0) through nine (9)
Ÿ Uppercase alphabetic characters A B C D P R S V X Z
Ÿ Lowercase alphabetic characters a through z
Ÿ The space
Ÿ Special characters * + - / , . ; ( ) " =
Ÿ A figurative constant
Ÿ The uppercase alphabetic character G, if the COBOL program defines an MBCS
item with the PICTURE symbol G; the PICTURE clause will be invalid for that MBCS
item because the symbol G is considered to be a currency symbol in the PICTURE
clause.
Ÿ The uppercase alphabetic character N, if the COBOL program defines an MBCS
item with the PICTURE symbol N; the PICTURE clause will be invalid for that MBCS
item because the symbol N is considered to be a currency symbol in the PICTURE
clause.
Ÿ The uppercase alphabetic character E, if the COBOL program defines an external
floating-point item; the PICTURE clause will be invalid for the external floating-point
item because the symbol E is considered to be a currency symbol in the PICTURE
clause.

You can use the CURRENCY option as an alternative to the CURRENCY SIGN clause for
selecting the currency symbol you will use in the PICTURE clause of a COBOL program.

154 COBOL Set for AIX Programming Guide


DATEPROC Compiler Option

When both the CURRENCY option and the CURRENCY SIGN clause are used in a
program, the symbol coded in the CURRENCY SIGN clause will be considered the cur-
rency symbol in a PICTURE clause when that symbol is used.

When the NOCURRENCY option is in effect and you omit the CURRENCY SIGN clause,
the dollar sign ($) is used as the PICTURE symbol for the currency sign.
Delimiter Note: The CURRENCY option literal can be delimited by either the quote or
the apostrophe, regardless of the QUOTE|APOST compiler setting.

| DATEPROC
|
| 55──┬─DATEPROC─┬────────────────┬──┬──────────────────────────────────5%
| │ └─(─┬─FLAG───┬─)─┘ │
| │ └─NOFLAG─┘ │
| └─NODATEPROC───────────────────┘

| Default is: NODATEPROC, or DATEPROC(FLAG) if only DATEPROC is specified

| Abbreviations are: DP|NODP

| Use the DATEPROC option to enable the millennium language extensions of the COBOL
| compiler. For information on using these extensions, see Chapter 29, “Using the
| Millennium Language Extensions” on page 446.

| DATEPROC(FLAG)
| With DATEPROC(FLAG), the millennium language extensions are enabled, and the
| compiler will produce a diagnostic message wherever a language element uses or
| is affected by the extensions. The message will usually be an information-level or
| warning-level message that identifies statements that involve date-sensitive proc-
| essing. Additional messages may be generated that identify errors or possible
| inconsistencies in the date constructs. For information on how to reduce these
| diagnostic messages, see “Eliminating Warning-Level Messages” on page 460.
| Production of diagnostic messges, and their appearance in or after the source
| listing, is subject to the setting of the FLAG compiler option.

| DATEPROC(NOFLAG)
| With DATEPROC(NOFLAG), the millennium language extensions are in effect, but
| the compiler will not produce any related messages unless there are errors or
| inconsistencies in the COBOL source.

| NODATEPROC
| NODATEPROC indicates that the extensions are not enabled for this compilation
| unit. This affects date-related program constructs as follows:

| Ÿ The DATE FORMAT clause is syntax-checked, but has no effect on the exe-
| cution of the program.
| Ÿ The DATEVAL and UNDATE intrinsic functions have no effect. That is, the
| value returned by the intrinsic function is exactly the same as the value of the
| argument.

Chapter 10. Compiler Options 155


DYNAM Compiler Option

| Ÿ The YEARWINDOW intrinsic function returns a value of zero.

| Notes:
| 1. Specification of the DATEPROC option requires that the NOCMPR2 option is also
| used.
| 2. NODATEPROC conforms to the COBOL 85 Standard.

DYNAM
55──┬─DYNAM───┬───────────────────────────────────────────────────────5%
└─NODYNAM─┘

Default is: NODYNAM

| Abbreviations are: DYN|NODYN

Use DYNAM to cause non-nested, separately compiled programs invoked through the
CALL literal statement to be loaded (for CALL) and deleted (for CANCEL) dynamically at
run time. CALL identifier statements always result in a run-time load of the target
program and are not impacted by this option.

The condition for the ON EXCEPTION phrase can occur for a CALL statement using the
literal name only when the DYNAM option is in effect.

With NODYNAM, the target program name is resolved through the linker.

With the DYNAM option, this statement


CALL "myprogram" ...
has the identical behavior to these statements:
MOVE "myprogram" to id-1
CALL id-1 ...
See “Static, Dynamic, and Run-time Linking” on page 327 for information on subpro-
gram calls.

DYNAM conforms to the COBOL 85 Standard.

156 COBOL Set for AIX Programming Guide


EXIT Compiler Option

ENTRYINT
55──ENTRYINT(─┬─SYSTEM──┬─)───────────────────────────────────────────5%
├─OPTLINK─┤
└─CDECL───┘

Default is: ENTRYINT(SYSTEM)

Abbreviations are: None

This option is treated as a comment.

EXIT
┌──
────────────────────────────┐
55──┬─EXIT(──6┬─INEXIT(─┬───────┬─mod1)──┬┴─)─┬────────────────────────5%
│ │ └─str1,─┘ │ │
│ ├─NOINEXIT─────────────────┤ │
│ ├─LIBEXIT(─┬───────┬─mod2)─┤ │
│ │ └─str2,─┘ │ │
│ ├─NOLIBEXIT────────────────┤ │
│ ├─PRTEXIT(─┬───────┬─mod3)─┤ │
│ │ └─str3,─┘ │ │
│ ├─NOPRTEXIT────────────────┤ │
│ ├─ADEXIT(─┬───────┬─mod4)──┤ │
│ │ └─str4,─┘ │ │
│ └─NOADEXIT─────────────────┘ │
└─NOEXIT─────────────────────────────────┘

Default is: NOEXIT

Abbreviations are: EX(INX|NOINX,LIBX|NOLIBX,PRTX|NOPRTX,ADX|NOADX)

If you specify the EXIT option without providing at least one suboption, NOEXIT will be in
effect. The suboptions can be specified in any order, separated by either commas or
spaces. If you specify both the positive and negative form of a suboption
(INEXIT|NOINEXT, LIBEXIT|NOLIBEXIT, PRTEXIT|NOPRTEXIT, OR ADEXIT|NOADEXIT), the
form specified last takes effect. If you specify the same suboption more than one time,
the one specified last takes effect.

Use the EXIT option to allow the compiler to accept user-supplied modules in place of
SYSIN, SYSLIB (or copy library), and SYSPRINT. When creating your EXIT module,
ensure that the module is linked as a DLL module before you run it with the COBOL
compiler. EXIT modules are invoked with the system linkage convention of the platform.

For SYSADATA, the ADEXIT suboption provides a module that will be called for each
SYSADATA record immediately after the record has been written out to the file.

No PROCESS: The EXIT option cannot be specified in a PROCESS(CBL) statement; it


can be specified only via the environment variable COBOPT, via the cob2 command
option, or at installation time.

Chapter 10. Compiler Options 157


EXIT Compiler Option

INEXIT(['str1',]mod1)
The compiler reads source code from a user-supplied load module (where mod1 is
the module name), instead of SYSIN.

LIBEXIT(['str2',]mod2)
The compiler obtains copy code from a user-supplied load module (where mod2 is
the module name), instead of library-name or SYSLIB. For use with either COPY or
BASIS statements.

PRTEXIT(['str3',]mod3)
The compiler passes printer-destined output to the user-supplied load module
(where mod3 is the module name), instead of SYSPRINT.

ADEXIT(['str4',]mod4)
The compiler passes the SYSADATA output to the user-supplied load module
(where mod4 is the module name).

The module names mod1, mod2, mod3, and mod4, can refer to the same module.

The suboptions 'str1', 'str2', 'str3', and 'str4', are character strings that are passed to the
load module. These strings are optional; if you use them, they can be up to 64 charac-
ters in length and must be enclosed in apostrophes. Any character is allowed, but
included apostrophes must be doubled, and lowercase characters are folded to upper-
case.

Character String Formats


If 'str1', 'str2', 'str3', or 'str4', is specified, the string is passed to the appropriate user-
exit module with the following format:

LL string

where LL is a halfword (on a halfword boundary) containing the length of the string.
See Figure 44 on page 159 for the location of the character string in the parameter list.

User-Exit Work Area


When an exit is used, the compiler provides a user-exit work area that can be used to
save the address of storage allocated by the exit module. This allows the module to be
reentrant.

The user-exit work area is four fullwords, residing on a fullword boundary, that is initial-
ized to binary zeroes before the first exit routine is invoked. The address of the work
area is passed to the exit module in a parameter list. After initialization, the compiler
makes no further reference to the work area. So, you will need to establish your own
conventions for using the work area if more than one exit is active during the compila-
tion. For example, the INEXIT module uses the first word in the work area, the LIBEXIT
module uses the second word, and the PRTEXIT module uses the third word.

158 COBOL Set for AIX Programming Guide


EXIT Compiler Option

Parameter List for Exit Modules


The following table shows the format of the parameter list used by the compiler to com-
municate with the exit module.

Figure 44. Parameter List for LIBEXIT


Contains
Offset Address of Description of Item
00 User-exit type Halfword identifying which user exit is to perform the
operation.
1=INEXIT; 2=LIBEXIT; 3=PRTEXIT; 4=ADEXIT
02 Operation code Halfword indicating the type of operation.
0=OPEN; 1=CLOSE; 2=GET; 4=FIND
04 Return code Fullword, placed by the exit module, indicating status
of the requested operation.
0=Successful; 4=End-of-data; 12=Failed
08 Data length Fullword, placed by the exit module, specifying the
length of the record being returned by the GET opera-
tion.
12 Data Fullword, placed by the exit module, containing the
address of the record in a user-owned buffer, for the
GET operation.
or 'str2' 'str2' applies only to OPEN. The first halfword (on a
halfword boundary) contains the length of the string;
the string follows.
16 User-exit work area Four-fullword work area provided by the compiler for
use by user-exit module.
32 Text-name Fullword containing the address of a a null-terminated
string containing the fully qualified text-name. Applies
only to FIND.
36 User exit parameter Fullword containing the address of a four-element
string array, each element of which is a structure that
contain a two-byte length field followed by a 64 char-
acters string that contain the exit parameter string.
Note: Only the second element of the parameter string array is used for LIBEXIT, to store the
length of the LIBEXIT parameter string followed by the parameter string.

Using INEXIT
When INEXIT is specified, the compiler loads the exit module (mod1) during initializa-
tion, and invokes the module using the OPEN operation code (op code). This allows the
module to prepare its source for processing and then pass the status of the OPEN
request back to the compiler. Subsequently, each time the compiler requires a source
statement, the exit module is invoked with the GET op code. The exit module then
returns either the address and length of the next statement or the end-of-data indication
(if no more source statements exist). When end-of-data is presented, the compiler

Chapter 10. Compiler Options 159


EXIT Compiler Option

invokes the exit module with the CLOSE op code so that the module can release any
resources that are related to its input.

The compiler uses a parameter list to communicate with the exit module. The param-
eter list consists of 10 fullwords. The return code, data length, and data parameters
are placed by the exit module for return to the compiler; and the other items are passed
from the compiler to the exit module.

Figure 44 on page 159 shows the contents of the parameter list and a description of
each item.

Using LIBEXIT
When LIBEXIT is specified, the compiler loads the exit module (mod2) during initializa-
tion. Calls are made to the module by the compiler to obtain copy text whenever
COPY or BASIS statements are encountered.
Use LIB: If LIBEXIT is specified, the LIB compiler option must be in effect.

The first call invokes the module with an OPEN op code. This allows the module to
prepare the specified library-name for processing. The OPEN op code is also issued
the first time a new library-name is specified. The exit module returns the status of the
OPEN request to the compiler by passing a return code.

Once the exit invoked with the OPEN op code returns, the exit module is then invoked
with a FIND op code. The exit module establishes positioning at the requested text-
name (or basis-name) in the specified library-name. This becomes the “active copy
source”. When positioning is complete, the exit module passes an appropriate return
code to the compiler.

The compiler then invokes the exit module with a GET op code, and the exit module
passes the compiler the length and address of the record to be copied from the active
copy source. The GET operation is repeated until the end-of-data indicator is passed to
the compiler.

When end-of-data is presented, the compiler will issue a CLOSE request so that the exit
module can release any resources related to its input.

Nested COPY Statements: Any record from the active copy source can contain a
COPY statement. (However, nested COPY statements cannot contain the REPLACING
phrase, and a COPY statement with the REPLACING phrase cannot contain nested copy
statements.) When a valid nested COPY statement is encountered, the compiler issues
a request based on the following:
Ÿ If the requested library-name from the nested COPY statement was not previously
opened, the compiler invokes the exit module with an OPEN op code, followed by a
FIND for the new text-name.

Ÿ If the requested library-name is already open, the compiler issues the FIND op
code for the new requested text-name (an OPEN is not issued here).

160 COBOL Set for AIX Programming Guide


Using ADEXIT

The compiler does not allow recursive calls to text-name. That is, a COPY member can
be named only once in a set of nested COPY statements until the end-of-data for that
copy member is reached.

When the exit module receives the OPEN or FIND request, it should push its control
information concerning the active copy source onto a stack and then complete the
requested action (OPEN or FIND). The newly requested text-name (or basis-name) now
becomes the active copy source.

Processing continues in the normal manner with a series of GET requests until the end-
of-data indicator is passed to the compiler.

At end-of-data for the nested active copy source, the exit module should pop its control
information from the stack. The next request from the compiler will be a FIND, so that
the exit module can reestablish positioning at the previous active copy source.

The compiler now invokes the exit module with a GET request, and the exit module
must pass the same record that was passed previously from this copy source. The
compiler verifies that the same record was passed, and then the processing continues
with GET requests until the end-of-data indicator is passed.

Figure 44 on page 159 shows the contents of the parameter list used for LIBEXIT and a
description of each item.

Using PRTEXIT
When PRTEXIT is specified, the compiler loads the exit module (mod3) during initializa-
tion. The exit module is used in place of the SYSPRINT data set.

The compiler invokes the module using the OPEN operation code (op code). This
allows the module to prepare its output destination for processing and then pass the
status of the OPEN request back to the compiler. Subsequently, each time the compiler
has a line to be printed, the exit module is invoked with the PUT op code. The compiler
supplies the address and length of the record that is to be printed, and the exit module
returns the status of the PUT request to the compiler by a return code. The first byte of
the record to be printed contains an ANSI printer control character.

Before the compilation is ended, the compiler invokes the exit module with the CLOSE
op code so that the module can release any resources that are related to its output
destination.

Figure 44 on page 159 shows the contents of the parameter list used for PRTEXIT and
a description of each item.

Using ADEXIT
When ADEXIT is specified, the compiler loads the exit module (mod4) during initialization.
The exit module is called for each record written to the SYSADATA data set.

The compiler invokes the module using the OPEN operation code (op code). This
allows the module to prepare for processing and then pass the status of the OPEN

Chapter 10. Compiler Options 161


FLAG Compiler Option

request back to the compiler. Subsequently, each time the compiler has written a
SYSADATA record, the exit module is invoked with the PUT op code. The compiler sup-
plies the address and length of the SYSADATA record, and the exit module returns the
status of the PUT request to the compiler by a return code.

Before the compilation is ended, the compiler invokes the exit module with the CLOSE
op code so that the module can release any resources.

Figure 44 on page 159 shows the contents of the parameter list used for ADEXIT and a
description of each item.

FLAG
55──┬─FLAG(x─┬────┬─)─┬───────────────────────────────────────────────5%
│ └─,y─┘ │
└─NOFLAG──────────┘

Default is: FLAG(I)

Abbreviations are: F|NOF

x and y can be either I, W, E, S, or U. (See “Compiler Error Message Codes” on


page 143 for descriptions of error codes.)

Use FLAG(x) to produce diagnostic messages for errors of a severity level x or above at
the end of the source listing.

Use FLAG(x,y) to produce diagnostic messages for errors of severity level x or above at
the end of the source listing, with error messages of severity y and above to be
embedded directly in the source listing. The severity coded for y must not be lower
than the severity coded for x. To use FLAG(x,y), you must also specify the SOURCE
compiler option.

Error messages in the source listing are set off by embedding the statement number in
an arrow that points to the message code. The message code is then followed by the
message text. For example:

ððð413 MOVE CORR WS-DATE TO HEADER-DATE

==ððð413==> IGYPS2121-S " WS-DATE " was not defined as a data-name. ...

With FLAG(x,y) selected, messages of severity y and above will be embedded in the
listing following the line that caused the message. (Refer to the notes below for
exceptions.)

Use NOFLAG to suppress error flagging. NOFLAG will not suppress error messages for
compiler options.

162 COBOL Set for AIX Programming Guide


FLAGSTD Compiler Option

Embedded Messages:
1. Specifying embedded level-U messages is accepted, but will not produce any mes-
sages in the source. Embedding a level-U message is not recommended.
2. The FLAG option does not affect diagnostic messages produced before the com-
piler options are processed.
3. Diagnostic messages produced during processing of compiler options, CBL and
PROCESS statements, or BASIS, COPY, and REPLACE statements, are never
embedded in the source listing. All such messages appear at the beginning of the
compiler output.
4. Messages produced during processing of the *CONTROL (*CBL) statement are not
embedded in the source listing.

FLAGSTD
55──┬─FLAGSTD(x─┬────┬──┬────┬─)─┬────────────────────────────────────5%
│ └─yy─┘ └─,O─┘ │
└─NOFLAGSTD──────────────────┘

Default is: NOFLAGSTD

x specifies the level or subset of COBOL 85 Standard to be regarded as conforming:


M Language elements that are not from the minimum subset are to be flagged as
“nonconforming standard”.

I Language elements that are not from the minimum or the intermediate subset are
to be flagged as “nonconforming standard”.

H The high subset is being used and elements will not be flagged by subset. And,
elements in the IBM extension category will be flagged as “non-conforming
Standard, IBM extension”.

yy specifies, by a single character or combination of any two, the optional modules to


be included in the subset:

D Elements from Debug module level 1 are not flagged as “non-conforming


standard”.

N Elements from Segmentation module level 1 are not flagged as “non-conforming


standard”.

S Elements from Segmentation module level 2 are not flagged as “non-conforming


standard”.

If S is specified, N is included (N is a subset of S).

O specifies that obsolete language elements are flagged as “obsolete”.

Chapter 10. Compiler Options 163


FLAGSTD Compiler Option

Use FLAGSTD to get informational messages about the COBOL 85 Standard elements
included in your program. You can specify any of the following items for flagging:
Ÿ A selected Federal Information Processing Standard (FIPS) COBOL subset
Ÿ Any of the optional modules
Ÿ Obsolete language elements
Ÿ Any combination of subset and optional modules
Ÿ Any combination of subset and obsolete elements
Ÿ IBM extensions (these are flagged any time FLAGSTD is specified and are identified
as “non-conforming non-standard”)
This includes the new language syntax for object-oriented COBOL and for
| improved interoperability, the PGMNAME(MIXED) compiler option, and the
| Millennium Language Extensions.

The informational messages appear in the source program listing and contain the fol-
lowing information:
Ÿ Identify the element as “obsolete”, “non-conforming standard”, or “non-conforming
non-standard” (a language element that is both obsolete and non-conforming is
flagged as obsolete only).
Ÿ Identify the clause, statement, or header that contains the element.
Ÿ Identify the source program line and beginning location of the clause, statement, or
header that contains the element.
Ÿ Identify the subset or optional module to which the element belongs.

FLAGSTD requires the standard set of reserved words.

In the following example, the line number and column where a flagged clause, state-
ment, or header occurred are shown, as well as the message code and text. At the
bottom is a summary of the total of the flagged items and their type.

LINE.COL CODE FIPS MESSAGE TEXT

IGYDS8211 Comment lines before "IDENTIFICATION DIVISION":


nonconforming nonstandard, IBM extension to
ANS/ISO 1985.

11.14 IGYDS8111 "GLOBAL clause": nonconforming standard, ANS/ISO


1985 high subset.

59.12 IGYPS8169 "USE FOR DEBUGGING statement": obsolete element


in ANS/ISO 1985.

FIPS MESSAGES TOTAL STANDARD NONSTANDARD OBSOLETE

3 1 1 1

164 COBOL Set for AIX Programming Guide


IDLGEN Compiler Option

FLOAT
55──FLOAT(─┬─NATIVE─┬─)───────────────────────────────────────────────5%
├─HEX────┤
└─S39ð───┘

Default is: FLOAT(NATIVE)

Abbreviations are: None

Specify FLOAT(NATIVE) to use the native floating point data representation format of the
platform. For COBOL Set for AIX, this is the IEEE format.

FLOAT(HEX) and FLOAT(S390) are synonymous and indicate that COMP-1 and COMP-2
data items are represented consistently with System/390 (that is, in the hex floating
point format):
Ÿ Hex floating point values are converted to IEEE format prior to any arithmetic oper-
ations (computations or comparisons).
Ÿ IEEE floating point values are converted to hex format prior to being stored in
floating point data fields.
Ÿ Assignment to a floating point item is done by converting the source floating point
data (for example, external floating point) to hex floating point as necessary.
| Object-oriented programs: Do not specify FLOAT(S390) in object-oriented programs.

For additional information about the FLOAT compiler option, see Appendix B,
“System/390 Host Data Type Considerations” on page 469.

IDLGEN
55──┬─IDLGEN───┬──────────────────────────────────────────────────────5%
└─NOIDLGEN─┘

Default is: NOIDLGEN

Abbreviations are: IDL|NOIDL

Use the IDLGEN option to indicate whether SOM Interface Definition Language (IDL)
should be generated for COBOL class definitions contained in the COBOL source file.

Use IDLGEN to request that in addition to the normal compile of the COBOL source file,
IDL definitions for classes defined in the file are generated.

Use NOIDLGEN to request that no IDL definitions are generated.

Chapter 10. Compiler Options 165


IDLGEN Compiler Option

The IDL file has the same name as the compiler source file, with the file extension IDL.
For example, IDL file generated for myfile.cbl would be myfile.idl. The IDL file is
written to the directory from which cob2 was run.

When a class definition includes references to other classes (such as on the INHERITS
or METACLASS IS phrases, or typed object references as method parameters) that are
defined in separate source files, the generated IDL will contain include statements for
the IDL files of the referenced classes. The COBOL compiler will attempt to obtain the
file name (referred to as the filestem in the SOM documentation) for a referenced class
from the SOM interface repository (IR). If the referenced class does not have an IR
entry, then the external class-name of the referenced class is assumed as the filestem.
An include is then generated of the form: #include <filestem..idl> This may be
adequate for classes where external class-names are the same as the original source
file name. However, in many cases this include statement will need to either be
updated to reflect the correct filestem or preferably, the entire IDL file should be re-
generated after the missing definition has been added to the IR.

When a COBOL source file contains more than one class definition (batch compile) and
the IDLGEN option is used, the COBOL class definitions must be sequenced in an
appropriate order within the source file. The generated IDL for such a batch compile
will contain multiple class interfaces with the IDL interfaces in the same order as the
COBOL classes were defined in the COBOL source file. The SOM IDL compiler
requires that interfaces be defined before they are referenced, so if there are refer-
ences between the classes in the COBOL batch compile, the referenced classes must
precede the referencing classes in the COBOL source file.

The mapping of COBOL to IDL is designed to balance two (conflicting) objectives,


namely enablement of object-oriented COBOL type checking and enabling COBOL
classes to operate with other SOM-based programming languages. At a high level:
Ÿ COBOL classes map to IDL interfaces.
Ÿ COBOL methods map to IDL operation declarations.
Ÿ Where possible, the data types of COBOL method parameters are mapped to cor-
responding native IDL types. These cases include binary integer, floating point,
pointer, object reference, and character types.
All elementary USAGE DISPLAY types and fixed-length COBOL groups are mapped
to IDL as array of character.
Remaining COBOL types that do not naturally map to any native IDL data type are
mapped to COBOL-specific “foreign” IDL types. These cases include packed-
decimal, scaled binary, DBCS, and variable-length groups.
Ÿ Method formal-parameters that specify BY REFERENCE on the method PROCEDURE
DIVISION header are given the IDL parameter attribute inout and parameters that
specify BY VALUE are given the IDL parameter attribute in.

The IDL generated for the same COBOL class by the IBM COBOL compiler on OS/390,
OS/2, Windows, and AIX might differ; hence, the IDL should be regenerated for the
target platform rather than ported between platforms. For example, the procedure-

166 COBOL Set for AIX Programming Guide


LIB Compiler Option

pointer data type in COBOL for OS/390 & VM is an 8-byte data item that does not map
to any native IDL type, hence a COBOL specific mapping is used. On OS/2, Windows,
and AIX, procedure-pointers are 4-byte data items that map to IDL pointers. Another
example is that on OS/390 or AIX, a PIC S9(8) BINARY data item maps naturally to an
IDL “long” type, while on OS/2 and Windows, the same data item may map either to an
IDL long or to a COBOL-specific data type that emulates System/390 binary format,
depending on the compilation options used.
No PROCESS: The IDLGEN options cannot be specified on the PROCESS(CBL) state-
ment.

See Chapter 13, “Writing Object-Oriented Programs” on page 222 and Chapter 15,
“Using SOM IDL-Based Class Libraries” on page 275 for more information on IDL and
SOM.

LIB
55──┬─LIB───┬─────────────────────────────────────────────────────────5%
└─NOLIB─┘

Default is: LIB

Abbreviations are: None

If your program uses COPY, BASIS, or REPLACE statements, the LIB compiler option
must be in effect.

For more information, see the discussion of the library-name user-defined variable on
page 129.

In addition, for COPY and BASIS statements, you need to define the library or libraries
from which the compiler can take the copied code:
Ÿ If the library-name is specified with a user-defined word (not a literal), you must set
the corresponding environment variable to point to the desired directory/path for the
copy file.
Ÿ If the library-name is omitted for a COPY statement, the path to be searched can be
specified via the -Ixxx option on the cob2 command.
Ÿ If the library-name is specified with a literal, the literal value is treated as the actual
path name.

LIB conforms to the COBOL 85 Standard.

Chapter 10. Compiler Options 167


LIST Compiler Option

LINECOUNT
55──LINECOUNT(nnn)────────────────────────────────────────────────────5%

Default is: LINECOUNT(60)

Abbreviations are: LC

nnn must be an integer between 10 and 255, or 0.

Use LINECOUNT(nnn) to specify the number of lines to be printed on each page of the
compilation listing, or use LINECOUNT(0) to suppress pagination.

If you specify LINECOUNT(0), no page ejects are generated in the compilation listing.

The compiler uses three lines of nnn for titles. For example, if you specify
LINECOUNT(60), 57 lines of source code are printed on each page of the output listing.

LIST
55──┬─LIST───┬────────────────────────────────────────────────────────5%
└─NOLIST─┘

Default is: NOLIST

Abbreviations are: None

Use LIST to produce a listing of the assembler-language expansion of your source


code.

You will also get these in your output listing:


Ÿ Global tables
Ÿ Literal pools
Ÿ Information about Working-Storage
Ÿ Size of the program's Working-Storage

If you want to limit the assembler listing output, use *CONTROL LIST or NOLIST state-
ments in your PROCEDURE DIVISION. Your source statements following a *CONTROL
NOLIST are not included in the listing until a *CONTROL LIST statement switches the
output back to normal LIST format. For a description of the *CONTROL (*CBL) statement,
see IBM COBOL Language Reference.

For information on using LIST output, see “Data Map Listing” on page 211.

168 COBOL Set for AIX Programming Guide


MAXMEM Compiler Option

MAP
55──┬─MAP───┬─────────────────────────────────────────────────────────5%
└─NOMAP─┘

Default is: NOMAP

Abbreviations are: None

Use MAP to produce a listing of the items you defined in the DATA DIVISION. Map
output includes:
Ÿ DATA DIVISION map
Ÿ Global tables
Ÿ Literal pools
Ÿ Nested program structure map, and program attributes
Ÿ Size of the program's Working-Storage

If you want to limit the MAP output, use *CONTROL MAP or NOMAP statements in the
PROCEDURE DIVISION. Source statements following a *CONTROL NOMAP are not
included in the listing until a *CONTROL MAP statement switches the output back to
normal MAP format. For a description of the *CONTROL (*CBL) statement, see the IBM
COBOL Language Reference.

For information on using LIST output, see “Data Map Listing” on page 211.

By selecting the MAP option, you can also print an embedded MAP report in the source
code listing. The condensed MAP information is printed to the right of data-name defi-
nitions in the FILE SECTION, WORKING-STORAGE SECTION, and LINKAGE SECTION of
the DATA DIVISION.

| MAXMEM
|
| 55──MAXMEM(size)──────────────────────────────────────────────────────5%

| Default is: MAXMEM(2000)

| Abbreviations are: None

| Use MAXMEM in conjunction with OPTIMIZE to limit the amount of memory used by the
| compiler for local tables of specific, memory-intensive optimizations to size kilobytes. If
| that memory is insufficient for a particular optimization, the scope of the optimization is
| reduced.

| A value of -1 permits each optimization to take as much memory as it needs without


| checking for limits. Depending on the source file being compiled, the size of subpro-
| grams in the source, the machine configuration, and the workload on the system, this
| might exceed available system resources.

Chapter 10. Compiler Options 169


NUMBER Compiler Option

| Notes:
| 1. The limit set by MAXMEM is the amount of memory for specific optimizations, and
| not for the compiler as a whole. Tables required during the entire compilation
| process are not affected or included in this limit.
| 2. Setting a large limit has no negative effect on the compilation of source files where
| the compiler needs less memory.
| 3. Limiting the scope of optimization does not necessarily mean that the resulting
| program will be slower, only that the compiler may finish before finding all opportu-
| nities to increase performance.
| 4. Increasing the limit does not necessarily mean that the resulting program will be
| faster, only that the compiler is better able to find opportunities to increase perform-
| ance if they exist.

| Depending on the source file being compiled, the size of the subprograms in the
| source, the machine configuration, and the workload on the system, setting the limit too
| high might lead to page space exhaustion. In particular, specifying MAXMEM(-1) allows
| the compiler to try and use an unlimited amount of storage, which in the worst case can
| exhaust the resources of even the most well-equipped machine.

NUMBER
55──┬─NUMBER───┬──────────────────────────────────────────────────────5%
└─NONUMBER─┘

Default is: NONUMBER

Abbreviations are: NUM|NONUM

Use NUMBER if you have line numbers in your source code and want those numbers to
be used in error messages and MAP, LIST, and XREF listings.

If you request NUMBER, columns 1 through 6 are checked to make sure that they
contain only numbers, and the sequence is checked according to numeric collating
sequence. (In contrast, SEQUENCE checks them according to ASCII collating
sequence.) When a line number is found to be out of sequence, the compiler assigns
to it a line number with a value one number higher than the line number of the pre-
ceding statement. Sequence-checking continues with the next statement, based on the
newly assigned value of the previous line.

If you use COPY statements and NUMBER is in effect, be sure that your source program
line numbers and the COPY member line numbers are coordinated.

Use NONUMBER if you do not have line numbers in your source code, or if you want the
compiler to ignore the line numbers you do have in your source code. With NONUMBER
in effect, the compiler generates line numbers for your source statements and uses
those numbers as references in listings.

170 COBOL Set for AIX Programming Guide


OPTIMIZE Compiler Option

NONUMBER conforms to the COBOL 85 Standard.

OPTIMIZE
55──┬─OPTIMIZE─┬──────────────┬──┬────────────────────────────────────5%
│ └─(─┬─STD──┬─)─┘ │
│ └─FULL─┘ │
└─NOOPTIMIZE─────────────────┘

Default is: NOOPTIMIZE

Abbreviations are: OPT|NOOPT

Use OPTIMIZE to reduce the run time of your object program; optimization might also
reduce the amount of storage your object program uses. Optimizations performed
include the propagation of constants, instruction scheduling, and the elimination of com-
putations whose results are never used. Because OPTIMIZE increases compile time,
and can change the order of statements in your program, it should not be used when
debugging.

If OPTIMIZE is specified without any suboptions, OPTIMIZE(STD) will be in effect.

The FULL suboption requests that in addition to the optimizations performed under
OPT(STD), that the compiler discard unreferenced data items from the DATA DIVISION,
and suppress generation of code to initialize these data items to their VALUE clauses. If
the OPT(FULL) and MAP options are specified, then a BL number of XXXX in the data
map information indicates that the data item was discarded.
Recomendation: Use OPTIMIZE(FULL) for database applications; it can make a huge
performace improvement, because unused constants included by the associated COPY
statements will be eliminated.

However:
Do not use OPT(FULL) if your programs depend on making use of unused data
items. Two common ways this has been done in the past are:
1. A technique sometimes used in OS/VS COBOL programs is to place an unrefer-
enced table after a referenced table and use out-of-range subscripts on the first
table to access the second table. To see if your programs have this problem, use
the SSRANGE compiler option with the CHECK(ON) run-time option. To work around
this problem, use the ability of COBOL to code large tables and use just one table.
2. The second technique utilizing unused data items is to place eyecatcher data items
in the WORKING-STORAGE section to identify the beginning and end of the program
data, or to mark a copy of a program for a library tool that uses the data to identify
a version of a program. To solve this problem, initialize these items with PROCE-
DURE DIVISION statements rather than VALUE clauses. With this method, the com-
piler will consider these items as used, and will not delete them.

Chapter 10. Compiler Options 171


PGMNAME Compiler Option

The OPTIMIZE option is turned off in the case of a severe-level error or higher. The
OPTIMIZE and TEST options are mutually exclusive; if you use both, OPTIMIZE will be
ignored.

PGMNAME
55──PGMNAME(─┬─MIXED─┬─)──────────────────────────────────────────────5%
└─UPPER─┘

Default is: PGMNAME(UPPER)

Abbreviations are: PGMN(LU|LM)

For compatibility with IBM COBOL for OS/390 & VM, LONGMIXED and LONGUPPER are
also supported.

LONGUPPER can be abbreviated as UPPER, LU, or U. LONGMIXED can be abbreviated


as MIXED, LM, or M.
COMPAT: If you specify PGMNAME(COMPAT), PGMNAME(UPPER) will be set, and you
will receive a warning message.

The PGMNAME option controls the handling of names used in the following contexts:
Ÿ Program names defined in the PROGRAM-ID paragraph.
Ÿ Program entry point names on the ENTRY statement.
Ÿ Program name references in:
– CALL statements
– CANCEL statements
– SET procedure-pointer TO ENTRY statements

PGMNAME(UPPER)
With PGMNAME(UPPER), program names that are specified in the PROGRAM-ID para-
graph as COBOL user-defined words must follow the normal COBOL rules for forming
a user-defined word:
Ÿ The program name can be up to 30 characters in length.
Ÿ All the characters used in the name must be alphabetic, digits, or the hyphen.
Ÿ At least one character must be alphabetic.
Ÿ The hyphen cannot be used as the first or last character.

When a program or method name is specified as a literal, in either a definition or a


reference, then:
Ÿ The program name can be up to 160 characters in length.
Ÿ All the characters used in the name must be alphabetic, digits, or the hyphen.
Ÿ At least one character must be alphabetic.
Ÿ The hyphen cannot be used as the first or last character.

172 COBOL Set for AIX Programming Guide


QUOTE/APOST Compiler Option

External program names are processed with alphabetic characters folded to upper
case.

PGMNAME(MIXED)
With PGMNAME(MIXED), program names are processed as is, without truncation, trans-
lation, or folding to upper case.

With PGMNAME(MIXED), all program name definitions must be specified using the literal
format of the program name in the PROGRAM-ID paragraph or ENTRY statement.

PROFILE
55──┬─PROFILE───┬─────────────────────────────────────────────────────5%
└─NOPROFILE─┘

Default is: PROFILE

Abbreviations are: None

PROFILE instructs the compiler to prepare the object file for AIX profiling (prof utility,
used for performance analysis). This option should be used with the -p option of the
cob2 command (see “Compiling and Linking Programs” on page 135).

QUOTE/APOST
55──┬─QUOTE─┬─────────────────────────────────────────────────────────5%
└─APOST─┘

Default is: QUOTE

Abbreviations are: Q|APOST

Use QUOTE if you want the figurative constant [ALL] QUOTE or [ALL] QUOTES to repre-
sent one or more quotation mark (") characters. QUOTE conforms to the COBOL 85
Standard.

Use APOST if you want the figurative constant [ALL] QUOTE or [ALL] QUOTES to repre-
sent one or more apostrophe (') characters.
Delimiters: Either quotes or apostrophes can be used as literal delimiters, regardless
of whether the APOST or QUOTE option is in effect. The delimiter character used as the
opening delimiter for a literal must be used as the closing delimiter for that literal.

Chapter 10. Compiler Options 173


Batch Compilation

SEPOBJ
55──┬─SEPOBJ───┬──────────────────────────────────────────────────────5%
└─NOSEPOBJ─┘

Default is: SEPOBJ

Abbreviations are: None

The option specifies whether or not each of the outermost COBOL programs in a batch
compilation is to be generated as a separate object file rather than a single object file.

Batch Compilation
When multiple outer-most programs (non-nested programs) are compiled with a single
invocation of the compiler (batch compiled), how many separate files are produced for
the object program output of the batch compilation varies on the compiler option
SEPOBJ.

Assume that the COBOL source file, pgm.cbl, contains three outer-most COBOL pro-
grams named pgm1, pgm2, and pgm3. The following figures illustrate whether the object
program output is generated as one (with NOSEPOBJ) or three (with SEPOBJ) files.

pgm.cbl
┌───────────────────┐
│ │
│ PROGRAM-ID. pgm1. │ pgm.o
│ ... │ ┌───────┐
│ END PROGRAM pgm1. │ │ │
├───────────────────┤ │ pgm1 │
│ │ │ │
│ PROGRAM-ID. pgm2. │ ├───────┤
│ ... │ ────────────5 │ pgm2 │
│ END PROGRAM pgm2. │ │ │
├───────────────────┤ ├───────┤
│ │ │ pgm3 │
│ PROGRAM-ID. pgm3. │ │ │
│ ... │ └───────┘
│ END PROGRAM pgm3. │
└───────────────────┘

Figure 45. Batch Compilation with NOSEPOBJ

174 COBOL Set for AIX Programming Guide


SEQUENCE Compiler Option

pgm.cbl pgm.o
┌───────────────────┐ ┌──────┐
│ │ ┌───────5 │ pgm1 │
│ PROGRAM-ID. pgm1. │ │ │ │
│ ... │ │ └──────┘
│ END PROGRAM pgm1. │ │
├───────────────────┤ │ pgm2.o
│ │ │ ┌──────┐
│ PROGRAM-ID. pgm2. │ ─────┼───────5 │ pgm2 │
│ ... │ │ │ │
│ END PROGRAM pgm2. │ │ └──────┘
├───────────────────┤ │
│ │ │ pgm3.o
│ PROGRAM-ID. pgm3. │ │ ┌──────┐
│ ... │ └───────5 │ pgm3 │
│ END PROGRAM pgm3. │ │ │
└───────────────────┘ └──────┘

Figure 46. Batch Compilation with SEPOBJ

Considerations:
1. The SEPOBJ option is required to conform to the ANSI COBOL standard where
pgm2 or pgm3 in the above example is called via CALL identifier from another
program.
2. If the NOSEPOBJ option is in effect, the name(s) of object module file(s) are named
with the name of the source file with .o, .OBJ, and/or .LIB extensions. If the
SEPOBJ option is in effect, the names of the object files (except for the first one)
are based on the PROGRAM-ID name with the .o or .OBJ extension.
3. The programs called via CALL identifier must be referred to by the names of the
object files (rather than the PROGRAM ID names) where PROGRAM ID and the
object file name do not match.

You are responsible for giving the object file a valid file name for the platform and the
file system.

SEQUENCE
55──┬─SEQUENCE───┬────────────────────────────────────────────────────5%
└─NOSEQUENCE─┘

Default is: SEQUENCE

Abbreviations are: SEQ|NOSEQ

When you use SEQUENCE, the compiler examines columns 1 through 6 of your source
statements to check that the statements are arranged in ascending order according to
their ASCII collating sequence. The compiler issues a diagnostic message if any state-
ments are not in ascending sequence (source statements with blanks in columns 1
through 6 do not participate in this sequence check and do not result in messages).

Chapter 10. Compiler Options 175


SOURCE Compiler Option

If you use COPY statements and SEQUENCE is in effect, be sure that your source
program sequence fields and the copy member sequence fields are coordinated.

If you use NUMBER and SEQUENCE, the sequence is checked according to numeric,
rather than ASCII, collating sequence.

Use NOSEQUENCE to suppress this checking and the diagnostic messages.

NOSEQUENCE conforms to the COBOL 85 Standard.

SIZE
55──SIZE(─┬─nnnnn─┬─)─────────────────────────────────────────────────5%
└─nnnK──┘

Default is: 2097152 bytes (approximately 2 Meg)

Abbreviations are: SZ

nnnnn specifies a decimal number that must be at least 778240.

nnnK specifies a decimal number in 1K increments. The minimum acceptable value is


782K.

Use SIZE to indicate the amount of main storage available for compilation (where 1K =
1024 bytes decimal).

SOURCE
55──┬─SOURCE───┬──────────────────────────────────────────────────────5%
└─NOSOURCE─┘

Default is: SOURCE

Abbreviations are: S|NOS

Use SOURCE to get a listing of your source program. This listing will include any state-
ments embedded by PROCESS or COPY statements.

SOURCE must be specified if you want embedded messages in the source listing.

Use NOSOURCE to suppress the source code from the compiler output listing.

If you want to limit the SOURCE output, use *CONTROL SOURCE or NOSOURCE state-
ments in your PROCEDURE DIVISION. Your source statements following a *CONTROL
NOSOURCE are not included in the listing at all, unless a *CONTROL SOURCE statement
switches the output back to normal SOURCE format. For a description of the *CONTROL
(*CBL) statement, see IBM COBOL Language Reference.

176 COBOL Set for AIX Programming Guide


SQL Compiler Option

For information on using LIST output, see “Data Map Listing” on page 211.

SPACE
55──SPACE(─┬─1─┬─)────────────────────────────────────────────────────5%
├─2─┤
└─3─┘

Default is: SPACE(1)

Abbreviations are: None

Use SPACE to select single, double, or triple spacing in your source code listing.

SPACE has meaning only when the SOURCE compiler option is in effect.

SPILL
55────SPILL(n)────────────────────────────────────────────────────────5%

Default is: SPILL(512)

Abbreviations are: None

This option specifies the register spill area size. If the program being compiled is very
complex or large, this option may be required. The spill size, n, is any integer between
96 and 32704 and designates the number of kilobytes set aside for the register spill
area.

SQL
55──SQL(─┬─"─┬─suboptions for DB2 SQL─┬─"─┬─)─────────────────────────5%
└─'─┘ └─'─┘

Default is: SQL("")

Abbreviations are: None

Use this option when you have SQL statements embedded in your COBOL source. It
allows you to specify options to be used in handling the SQL statements in your
program and is required if the suboption string, which gives SQL options, is to be speci-
fied explicitly to DB2.

The syntax shown can be used on either the CBL or PROCESS statements. If the SQL
option is given on the cob2 command, only ' is allowed for the string delimiter:
-q"SQL('options')".

Chapter 10. Compiler Options 177


TERMINAL Compiler Option

See Chapter 20, “Programming for a DB2 Environment” on page 354 for more informa-
tion.

SSRANGE
55──┬─SSRANGE───┬─────────────────────────────────────────────────────5%
└─NOSSRANGE─┘

Default is: NOSSRANGE

Abbreviations are: SSR|NOSSR

Use SSRANGE to generate code that checks if subscripts (including ALL subscripts) or
indexes try to reference an area outside the region of the table. Each subscript or
index is not individually checked for validity; rather, the effective address is checked to
ensure that it does not cause a reference outside the region of the table. Variable-
length items will also be checked to ensure that the reference is within their maximum
defined length.

Reference modification expressions will be checked to ensure that:


Ÿ The reference modification starting position is greater than or equal to 1.
Ÿ The reference modification starting position is not greater than the current length of
the subject data item.
Ÿ The reference modification length value (if specified) is greater than or equal to 1.
Ÿ The reference modification starting position and length value (if specified) do not
reference an area beyond the end of the subject data item.

If SSRANGE is in effect at compile time, the range-checking code is generated; range


checking can be inhibited at run time by specifying CHECK(OFF) as a run-time option.
This leaves range-checking code dormant in the object code. The range-checking code
can then be optionally used to aid in resolving any unexpected errors without recompi-
lation.

If an out-of-range condition is detected, an error message will be displayed and the


program will be terminated.
Remember: You will get range-checking only if you compile your program with the
SSRANGE option and run it with the CHECK(ON) run-time option.

TERMINAL
55──┬─TERMINAL───┬────────────────────────────────────────────────────5%
└─NOTERMINAL─┘

Default is: NOTERMINAL

178 COBOL Set for AIX Programming Guide


THREAD Compiler Option

Abbreviations are: TERM|NOTERM

Use TERMINAL to send progress and diagnostic messages to the terminal.

Use NOTERMINAL if this additional output is not desired.

TEST
55──┬─TEST───┬────────────────────────────────────────────────────────5%
└─NOTEST─┘

Default is: NOTEST

Abbreviations are: None

Use TEST to produce object code that contains symbol and statement information that
enables the debugger to perform symbolic source-level debugging.

Use NOTEST if you do not want to generate object code with debugging information.

Programs compiled with NOTEST execute with the debugger, but there is limited debug-
ging support.

The TEST option will be turned off if you use the WITH DEBUGGING MODE clause. The
TEST option will appear in the list of options, but a diagnostic message will be issued to
advise you that because of the conflict, TEST will not be in effect.

THREAD
55──┬─THREAD───┬──────────────────────────────────────────────────────5%
└─NOTHREAD─┘

Default is: NOTHREAD

Abbreviations are: None

THREAD indicates if the COBOL application is to be enabled for execution in a run unit
with multiple threads. All programs within a run unit must be compiled with either the
THREAD or NOTHREAD option.

When the THREAD option is in effect, the following language elements are not sup-
ported. If encountered, they are diagnosed as errors:
Ÿ STOP RUN
Ÿ ALTER statement
Ÿ DEBUG-ITEM special register
Ÿ GO TO statement without procedure-name
Ÿ RERUN
Ÿ STOP literal statement

Chapter 10. Compiler Options 179


TRUNC Compiler Option

Ÿ Segmentation module
Ÿ USE FOR DEBUGGING statement
Ÿ WITH DEBUGGING MODE clause
Ÿ INITIAL phrase in PROGRAM-ID paragraph

Notes:
1. RERUN is flagged as an error with THREAD, but is accepted as a comment with
NOTHREAD.

| 2. With THREAD, you must use the cob2_r command to compile your program. See
| “Compiling and Linking Programs” on page 135 for details.

See Chapter 24, “Preparing COBOL Programs for Multithreading” on page 397 for a
discussion of COBOL support for multithreading.

TRUNC
55──TRUNC(─┬─STD─┬─)──────────────────────────────────────────────────5%
├─OPT─┤
└─BIN─┘

Default is: TRUNC(STD)

Abbreviations are: None

TRUNC(STD) conforms to the COBOL 85 Standard, while TRUNC(OPT) and TRUNC(BIN)


are IBM extensions.

TRUNC has no effect on COMP-5 data items; COMP-5 items are handled as if
TRUNC(BIN) were in effect, regardless of the TRUNC option specified.

TRUNC(STD)
Use TRUNC(STD) to control the way arithmetic fields are truncated during MOVE
and arithmetic operations. TRUNC(STD) applies only to USAGE BINARY receiving
fields in MOVE statements and arithmetic expressions. When TRUNC(STD) is in
effect, the final result of an arithmetic expression, or the sending field in the MOVE
statement, is truncated to the number of digits in the PICTURE clause of the BINARY
receiving field.

TRUNC(OPT)
TRUNC(OPT) is a performance option. When TRUNC(OPT) is specified, the compiler
assumes that the data conforms to PICTURE and USAGE specifications of the
USAGE BINARY receiving fields in MOVE statements and arithmetic expressions.
The results are manipulated in the most optimal way, either truncating to the
number of digits in the PICTURE clause, or to the size of the binary field in storage
(halfword, fullword, or doubleword).
Caution: You should use the TRUNC(OPT) option only if you are sure that the data
being moved into the binary areas will not have a value with larger precision than
that defined by the PICTURE clause for the binary item. Otherwise, unpredictable

180 COBOL Set for AIX Programming Guide


TRUNC Compiler Option

results might occur. This truncation is performed in the most efficient manner pos-
sible; therefore, the results will be dependent on the particular code sequence gen-
erated. It is not possible to predict the truncation without seeing the code
sequence generated for a particular statement.

TRUNC(BIN)
The TRUNC(BIN) option applies to all COBOL language that processes USAGE
BINARY data. When TRUNC(BIN) is in effect:

Ÿ BINARY receiving fields are truncated only at halfword, fullword, or doubleword


boundaries.
Ÿ BINARY sending fields are handled as halfwords, fullwords, or doublewords
when the receiver is numeric; TRUNC(BIN) has no effect when the receiver is
not numeric.
Ÿ The full binary content of the field is significant.
Ÿ DISPLAY will convert the entire content of the binary field, with no truncation.

Recommendation: TRUNC(BIN) is the recommended option for programs that use


| binary values set by other products. These other products, such as C/C++,
| FORTRAN, and PL/I, might place values in COBOL binary data items that do not
conform to the PICTURE clause of the data item. For CICS considerations, see
“Selecting Compiler Options” on page 360.
TRUNC(BIN) should never be used as an install default, only for specific programs,
due to the performance cost. A better approach is to use COMP-5 for binary data
items passed to non-COBOL programs or other products and subsystems. The
use of COMP-5 is not affected by the TRUNC option in effect.

TRUNC Example 1
ð1 BIN-VAR PIC 99 USAGE BINARY.
.
.
MOVE 123451 to BIN-VAR

Figure 47. Values of the Data Items after the MOVE


Decimal Hex Display
Sender 123451 00|01|E2|3B 123451
Receiver 51 00|33 51
TRUNC(STD)
Receiver -7621 E2|3B 2J
TRUNC(OPT)
Receiver TRUNC(BIN) -7621 E2|3B 762J

A halfword of storage is allocated for BIN-VAR. The result of this MOVE statement if the
program is compiled with the TRUNC(STD) option is 51; the field is truncated to conform
to the PICTURE clause.

Chapter 10. Compiler Options 181


TRUNC Compiler Option

If the program is compiled with the TRUNC(BIN) option, the result of the MOVE statement
is -7621. The reason for the unusual looking answer is that nonzero high-order digits
were truncated. Here, the generated code sequence would merely move the lower
halfword quantity X'E23B' to the receiver. Because the new truncated value over-
flowed into the sign bit of the binary halfword, the value becomes a negative number.

This MOVE statement should not be compiled with the TRUNC(OPT) option because
123451 has greater precision than the PICTURE clause for BIN-VAR. If TRUNC(OPT) was
used, however, the results again would be -7621. This is because the best perform-
ance was gained by not doing a decimal truncation.
Assumption: The preceding example assumes that the BINARY(S390) option is in
effect.

TRUNC Example 2
ð1 BIN-VAR PIC 9(6) USAGE BINARY
.
.
MOVE 1234567891 to BIN-VAR

Figure 48. Values of the Data Items after the MOVE


Decimal Hex Display
Sender 1234567891 49|96|02|D3 1234567891
Receiver 567891 00|08|AA|53 567891
TRUNC(STD)
Receiver 567891 53|AA|08|00 567891
TRUNC(OPT)
Receiver TRUNC(BIN) 1234567891 49|96|02|D3 1234567891

When TRUNC(STD) is specified, the sending data is truncated to six integer digits to
conform to the PICTURE clause of the BINARY receiver.

When TRUNC(OPT) is specified, the compiler assumes the sending data is not larger
than the PICTURE clause precision of the BINARY receiver. The most efficient code
sequence in this case performed truncation as if TRUNC(STD) had been specified.

When TRUNC(BIN) is specified, no truncation occurs because all of the sending data will
fit into the binary fullword allocated for BIN-VAR.
Assumption: The preceding example assumes that the BINARY(S390) option is in
effect.

182 COBOL Set for AIX Programming Guide


TYPECHK Compiler Option

TYPECHK
55──┬─TYPECHK───┬─────────────────────────────────────────────────────5%
└─NOTYPECHK─┘

Default is: NOTYPECHK

Abbreviations are: TC|NOTC

Use TYPECHK to have the compiler enforce the rules for object-oriented type checking,
and generate diagnostics for any violations.

Use NOTYPECHK to turn off the checking for typing violations.

The type conformance requirements are covered in the IBM COBOL Language Refer-
ence under the appropriate language elements. Type checking requirements include:
Ÿ The method being invoked on an INVOKE statement must be supported by the
class of the referenced object.
Ÿ Method parameters on an INVOKE and the corresponding method PROCEDURE
DIVISION USING must conform.

Ÿ The SET object-reference-1 TO object-reference-2 statement requires that the


classes of the objects be of appropriate derivation relationships.
Ÿ A method override must have a conforming interface to the corresponding method
in the parent class.

When TYPECHK is specified, there must be entries in the SOM Interface Repository (IR)
for each class that is referenced in the COBOL source being compiled.

For COBOL classes, these IR entries can be created by using the COBOL IDLGEN
option (see “IDLGEN” on page 165) when compiling the class definitions, to create an
IDL file that describes the interface of the COBOL class. Compile the IDL using the
SOM compiler with its "ir" emitter.

Note that if the COBOL program references classes that are provided by the SOM
product itself (such as the SOMObject class), then the pre-generated IR for these
classes that is provided as part of the OS/390 SOMobjects product may be used to
verify that the COBOL usage conforms to the class interfaces.

See Chapter 14, “Using System Object Model (SOM)” on page 269, SOMobjects
Developer's Toolkit User's Guide, and SOMobjects Developer's Toolkit Programmer's
Reference Manual (available online) for further details on interface repositories, SOM,
and type checking.

Chapter 10. Compiler Options 183


WORD Compiler Option

VBREF
55──┬─VBREF───┬───────────────────────────────────────────────────────5%
└─NOVBREF─┘

Default is: NOVBREF

Abbreviations are: None

Use VBREF to get a cross-reference among all verb types used in the source program
and the line numbers in which they are used. VBREF also produces a summary of how
many times each verb was used in the program.

Use NOVBREF for more efficient compilation.

WORD
55──┬─WORD(xxxx)─┬────────────────────────────────────────────────────5%
└─NOWORD─────┘

Default is: NOWORD

Abbreviations are: WD|NOWD

xxxx specifies the ending characters of the name of the reserved-word table (IGYCxxxx)
to be used in your compilation. IGYC are the first 4 standard characters of the name,
and xxxx can be 1 to 4 characters in length.

Use WORD(xxxx) to specify that an alternate reserved-word table is to be used during


compilation.

IBM COBOL provides an alternate reserved-word table (IGYCCICS) specifically for CICS
applications. It is set up to flag COBOL words not supported under CICS with an error
message. If you want to use this CICS reserved-word table during your compilation,
specify the compiler option WORD(CICS). For information on the CICS reserved-word
table, refer to “CICS has a Special Reserved Word Table” on page 359.

IBM COBOL provides an alternate reserved-word table (IGYCNOOO) specifically for


existing applications you might have that use object-oriented reserved words (OBJECT,
METHOD, and others) as user-defined words. IGYCNOOO does not reserve the new
words used for object-orientation so your applications will still work if you refer to the
new words:

CLASS-ID METACLASS RECURSIVE


END-INVOKE METHOD RETURNING
INHERITS METHOD-ID REPOSITORY
INVOKE OBJECT SELF
LOCAL-STORAGE OVERRIDE SUPER

184 COBOL Set for AIX Programming Guide


XREF Compiler Option

If you want to use this NOOO reserved-word table during your compilation, specify the
compiler option WORD(NOOO).

NOWORD conforms to the COBOL 85 Standard.

| WSCLEAR
|
| 55──┬─WSCLEAR───┬─────────────────────────────────────────────────────5%
| └─NOWSCLEAR─┘

| Default is: NOWSCLEAR

| Abbreviations are: None

| Use WSCLEAR to clear your program's working storage to binary zeros when the
| program is initialized. The storage is cleared before any VALUE clauses are applied.

| Use NOWSCLEAR to bypass the storage clearing process.

| If you use WSCLEAR and you are concerned about the size or performance of the
| object program, then you should also use OPTIMIZE(FULL). This instructs the compiler
| to eliminate all unreferenced data items from the DATA DIVISION, which will speed up
| the initialization process.

XREF
55──┬─XREF─┬───────────────┬──┬───────────────────────────────────────5%
│ └─(─┬─SHORT─┬─)─┘ │
│ └─FULL──┘ │
└─NOXREF──────────────────┘

Default is: NOXREF

Abbreviations are: X|NOX

You can choose XREF, XREF(FULL), or XREF(SHORT).

Use XREF to get a sorted cross-reference listing. Names are listed in the order of the
collating sequence indicated by the locale setting. This applies whether the names are
in single-byte characters or contain multi-byte characters (such as DBCS).

Also included is a section listing all the program names that are referenced in your
program, and the line number where they are defined. External program names are
identified as such.

If you use XREF and SOURCE, cross-reference information will also be printed on the
same line as the original source in the listing. Line number references or other informa-
tion, will appear on the right hand side of the listing page. On the right of source lines

Chapter 10. Compiler Options 185


YEARWINDOW Compiler Option

that reference intrinsic functions, the letters 'IFN' will appear with the line numbers of
the location where the function's arguments are defined. Information included in the
embedded references lets you know if an identifier is undefined or defined more than
once (UND or DUP will be printed); if an item is implicitly defined (IMP), such as special
registers or figurative constants; and if a program name is external (EXT).

If you use XREF and NOSOURCE, you'll get only the sorted cross-reference listing.

XREF(SHORT) will print only the explicitly referenced variables in the cross-reference
listing. XREF(SHORT) applies to MBCS data names and procedure-names as well as
ASCII names.

NOXREF suppresses this listing.

Observe:
1. Group names used in a MOVE CORRESPONDING statement are in the XREF listing.
In addition, the elementary names in those groups are also listed.
2. In the data-name XREF listing, line numbers preceded by the letter “M” indicate that
the data item is explicitly modified by a statement on that line.
3. XREF listings take additional storage.

See Chapter 12, “Debugging Techniques” on page 197 for sample listings.

| YEARWINDOW
|
| 55──YEARWINDOW──(base-year)───────────────────────────────────────────5%

| Default is: YEARWINDOW(1900)

| Abbreviation is: YW

| Use the YEARWINDOW option to specify the first year of the 100-year window (the
| century window) to be applied to windowed date field processing by the COBOL com-
| piler. For information on using windowed date fields, see Chapter 29, “Using the
| Millennium Language Extensions” on page 446.

| base-year represents the first year of the 100-year window, and must be specified as
| one of the following:
| Ÿ An unsigned decimal number between 1900 and 1999.
| This specifies the starting year of a fixed window. For example,
| YEARWINDOW(1930) indicates a century window of 1930-2029.

| Ÿ A negative integer from -1 through -99.


| This indicates a sliding window, where the first year of the window is calculated
| from the current run-time date. The number is subtracted from the current year to
| give the starting year of the century window. For example, YEARWINDOW(-80) indi-

186 COBOL Set for AIX Programming Guide


Compiler-Directing Statements

| cates that the first year of the century window is 80 years before the current year
| at the time the program is run.

| Notes:
| 1. The YEARWINDOW option has no effect unless the DATEPROC option is also in
| effect.
| 2. At run time, two conditions must be true:
| Ÿ The century window must have its beginning year in the 1900s
| Ÿ The current year must lie within the century window for the compilation unit
| For example, running a program in 1998 with YEARWINDOW(-99) violates the first
| condition, and would result in a run-time error.

ZWB
55──┬─ZWB───┬─────────────────────────────────────────────────────────5%
└─NOZWB─┘

Default is: ZWB

Abbreviations are: None

With ZWB, the compiler removes the sign from a signed external decimal (DISPLAY)
field when comparing this field to an alphanumeric elementary field during execution.

If the external decimal item is a scaled item (contains the symbol 'P' in its PICTURE
character-string), its use in comparisons is not affected by ZWB. Such items always
have their sign removed before the comparison is made to the alphanumeric field.

ZWB affects how the program runs; the same COBOL source program can give different
results, depending on the option setting.

ZWB conforms to the COBOL 85 Standard.

Use NOZWB if you want to test input numeric fields for SPACES.

Compiler-Directing Statements
Several statements help you to direct the compilation of your program. For the defi-
nition of these statements, see IBM COBOL Language Reference.

BASIS statement
This extended source program library statement provides a complete COBOL
program as the source for a compilation.

Chapter 10. Compiler Options 187


Compiler-Directing Statements

*CONTROL (*CBL) statement


This compiler-directing statement selectively suppresses or allows output to be
produced. The names *CONTROL and *CBL are synonymous. This statement is
described in the IBM COBOL Language Reference.

>>CALLINTERFACE statement
This compiler directing statement specifies the interface convention for calls,
including whether argument descriptors are to be generated. The convention spec-
ified using >>CALLINT is in effect until another >>CALLINT specification is made.
>>CALLINT can be used only in the PROCEDURE DIVISION.

The syntax and usage of the >>CALLINT statement is similar to the CALLINT com-
piler option. Exceptions are:

Ÿ CALLINT is a valid abbreviation in the statement syntax


Ÿ The statement syntax does not include parentheses
Ÿ The statement form can be used to apply to selective calls as described
below.
Ÿ The statement syntax includes the keyword DESCRIPTOR and its variants.

See the IBM COBOL Language Reference for the full syntax. See “CALLINT” on
page 150 for details of the option form.
If you specify >>CALLINT with no suboptions, the call convention used is determined
by the CALLINT compiler option. For example, if PROG1 is an IBM C program
whose default call interface convention is _OPTLINK, or it is a COBOL program
compiled with the ENTRYINT(OPTLINK) option, use the >>CALLINT directive to
change the interface for this call only:
>>CALLINT OPTLINK DESC
CALL "PROG1" USING PARM1 PARM2.
>>CALLINT
CALL "PROG2" USING PARM1.
Descriptor Only: The >>CALLINT statement is treated as a comment except for
the forms:
>>CALLINT SYSTEM DESCRIPTOR
>>CALLINT DESCRIPTOR
The >>CALLINT statement can be specified anywhere that a COBOL procedure
statement can be specified. For example, the following is valid COBOL syntax:
MOVE 3 TO
>>CALLINTERFACE SYSTEM
RETURN-CODE.
The effect of >>CALLINT is limited to the current program. A nested program or a
program compiled in the same batch inherits the calling convention specified with
the CALLINT compiler option, not the >>CALLINT compiler directive.
If you are writing a routine that is to be called with >>CALLINT SYSTEM,
DESCRIPTOR, this is the argument-passing mechanism:

188 COBOL Set for AIX Programming Guide


Compiler-Directing Statements

CALL "PROGRAM1" USING arg-1, arg-2, ... arg-n

descriptor for arg-1


┌─5 ð ┌─────────┬──────────┬──────────┬──────────┐
│ │descType │ dataType │ descInf1 │ descInf2 │
│ 4 ├─────────┴──────────┴──────────┴──────────┤
│ │length-1 │
│ 8 ├──────────────────────────────────────────┤
│ │length-2 │
│ └──────────────────────────────────────────┘

┌───────────────┐ └──────────────────────┐
│ arg-1 │ │
├───────────────┤ -8 ┌────────────────────┐ │
│ arg-2 │ │ descriptor-ID │ │
├───────────────┤ ┌─5 ð │────────────────────│ │
│ ... │ │ │ pointer to descr-1─┼──┘
├───────────────┤ │ 4 ├────────────────────┤
│ arg-n │ │ │ pointer to descr-2─┼──5 descriptor for arg-2
├───────────────┤ │ 8 ├────────────────────┤
│ pointer to │ │ │ ... │ ...
│ descriptor ─┼─┘ ├────────────────────┤
│ pointer array │ │ pointer to descr-n─┼──5 descriptor for arg-n
└───────────────┘ └────────────────────┘

Figure 49. Argument Passing with SYSTEM(DESC)

pointer to descr-n Points to the descriptor for the specific argument; 0 if no


descriptor exists for the argument.
descriptor-ID Set to COBDESC0 to identify this version of the descriptor,
allowing for a possible change to the descriptor entry format
in the future.
descType Set to X'02' (descElmt) for an elementary data item of
USAGE DISPLAY with PICTURE X(n) or USAGE DISPLAY-1 with
PICTURE G(n) or N(n). For all others (numeric fields, struc-
tures, tables), set to X'00'.
dataType Set as follows:
Ÿ descType = X'00': dataType = X'00'
Ÿ descType = X'02' and the USAGE is DISPLAY: dataType
= X'02' (typeChar)
Ÿ descType = X'02' and the USAGE is DISPLAY-1:
dataType = X'09' (typeGChar)
descInf1 Always set to X'00'
descInf2 Set as follows:
Ÿ If descType = X'00'; descInf2 = X'00'
Ÿ If descType = X'02':
– If the CHAR(EBCDIC) option is in effect and the argu-
ment is not defined with the NATIVE option in the
USAGE clause: descInf2 = X'40'

– Else: descInf2 = X'00'

Chapter 10. Compiler Options 189


Compiler-Directing Statements

length-1 In the argument descriptor is the length of the argument for a


fixed length argument or the current length for a variable
length item.
length-2 The maximum length of the argument, if the argument is a
variable length item.
For a fixed length argument length-2 is equal to length-1.

COPY statement

55──COPY─┬─text-name─┬──┬──────────────┬──────────────────────────5%
└─literal-1─┘ ├─library-name─┤
└─literal-2────┘

This library statement places pre-written text into a COBOL program.


The uniqueness of text-name and library-name is determined after the formation
and conversion rules for a system-dependent name have been applied. A user-
defined word can be the same as a text-name or a library-name. If more than one
COBOL library is available during compilation, text-name need not be qualified. If
text-name is not qualified, a library-name of SYSLIB is assumed. The following
affects library-name and text-name:

library-name
If you specify library-name as a literal (literal-2), it is treated as the actual path.
If you specify library-name with a user-defined word, the name is used as an
environment variable and the value of the environment variable is used for the
path to locate the COPY text. To specify multiple path names, delimit them by
using a colon (:) or a semicolon (;).
If you don't specify library-name, the path used is as described under text-
name.

text-name
The processing of text-name as a user-defined word depends on whether the
environment variable corresponding to the text-name is set. If the the environ-
ment variable is set, the value of the environment variable is used as the file
name, and possibly the path name, for the copybook.
A text-name is treated as both the path and file name if:

Ÿ library-name (or literal-2) is not given, and


Ÿ text-name is a literal (literal-1) or an environment variable, and
Ÿ The first character is '/'

For example,
COPY "/mycpylib/..."
If the environment variable corresponding to the text-name is not set, the copy
text is searched for as the following names:

1. The text-name with the extension of .cpy

190 COBOL Set for AIX Programming Guide


Compiler-Directing Statements

2. The text-name with the extension of .cbl


3. The text-name with the extension of .cob
4. The text-name without an extension

For example, COPY MyCopy searches in the following order:

Ÿ MyCopy.cpy (in all the specified paths, as described above)


Ÿ MyCopy.cbl (in all the specified paths, as described above)
Ÿ MyCopy.cob (in all the specified paths, as described above)
Ÿ MyCopy (in all the specified paths, as described above)

-I option
For other cases (when neither a library-name nor text-name indicates the
path), the path searched is dependent on the -I option. For details, see
“Options Supported by cob2” on page 136.
To have COPY A be equivalent to COPY A OF MYLIB specify -I$MYLIB.
Based on the above rules, COPY "/X/Y" will be searched in the root directory,
while COPY "X/Y" will be searched in the current directory.
COPY A OF SYSLIB is equivalent to COPY A. The -I option does not impact
COPY statements with explicit library-name qualifications besides those with
the library name of SYSLIB.

Environment Variable Notes If both library-name and text-name are environment


variables the compiler will insert a path separator (/) between the two values. For
example, COPY MYCOPY OF MYLIB with the settings of
export MYCOPY=MYPDS(MYMEMBER)
export MYLIB=MYFILE
results in MYFILE/MYPDS(MYMEMBER)
Using a user-defined word as text-name enables you not only to access local files
but to access PDS members on OS/390 without changing your mainframe source.
For example:
COPY mycopybook
In this example, when the environment variable mycopybook is set to
h/mypds(mycopy), where:

h is assigned to the specific host


mypds is the OS/390 PDS data set name
mycopy is the PDS member name

You can access OS/390 files from AIX using NFS (Network File System), which
allows OS/390 files to be accessed using an AIX pathname. However, note that it
converts the path separator to “.” to follow OS/390 naming conventions. You
should keep this in mind when assigning values to your environment variables to
ensure proper name formation. For example, these settings
export MYCOPY=(MYMEMBER)
export MYLIB=M/MYFILE/MYPDS

Chapter 10. Compiler Options 191


Compiler-Directing Statements

do not work because what is created is


M/MYFILE/MYPDS/(MYMEMBER)
which becomes
M.MYFILE.MYPDS.(MYMEMBER)

See the AIX System Management Guide: Communications and Networks for
details on associating a local directory with a remote target.
For more information on the COPY statement, see the discussion of the COPY
statement in the IBM COBOL Language Reference.

DELETE statement
This extended source library statement removes COBOL statements from the
BASIS source program.

EJECT statement
This compiler-directing statement specifies that the next source statement is to be
printed at the top of the next page.

ENTER statement
The compiler handles this statement as a comment.

INSERT statement
This library statement adds COBOL statements to the BASIS source program.

PROCESS (CBL) statement


This statement, which is placed before the IDENTIFICATION DIVISION header of an
outermost program, indicates which compiler options are to be used during compi-
lation of the program. (See page 141 for the format of this statement).
For details on specifying compiler options with the PROCESS (CBL) statement and
with other methods, see the discussion under “Compiling and Linking Programs” on
page 135.

REPLACE statement
This statement is used to replace source program text.

SKIP1/2/3 statement
These statements indicate lines to be skipped in the source listing.

TITLE statement
This statement specifies that a title (header) be printed at the top of each page of
the source listing. (See “Changing Header of Source Listing” on page 13.)

USE statement
The USE statement provides declaratives to specify the following:

Error-handling procedures—EXCEPTION/ERROR
Debugging lines and sections—DEBUGGING

192 COBOL Set for AIX Programming Guide


Syntax of Run-time Options

Chapter 11. Run-Time Options


The following run-time options are supported:
Ÿ CHECK
Ÿ DEBUG
Ÿ ERRCOUNT
Ÿ FILESYS
Ÿ TRAP
Ÿ UPSI

Syntax
Syntax of the run-time options follows. See “Definitions of COBOL Environment
Variables” on page 129 to see where to specify them.

CHECK
CHECK flags checking errors in an application. In COBOL, index, subscript, and refer-
ence modification ranges are checking errors.

┌─ON──┐
55──CHECK──(──┼─────┼──)──────────────────────────────────────────────5%
└─OFF─┘

Default is: CHECK(ON).

Abbreviation is: CH

ON
Specifies that run-time checking is performed.

OFF
Specifies that run-time checking is not performed.

Usage Note
CHECK(ON) has no effect if NOSSRANGE was in effect at compile time.

Performance Consideration
If your COBOL program was compiled with SSRANGE, and you are not testing or
debugging an application, performance improves when you specify CHECK(OFF).

DEBUG
DEBUG specifies whether the COBOL debugging sections specified by the USE FOR
DEBUGGING declarative are active.

 Copyright IBM Corp. 1996, 1998 193


Syntax of Run-time Options

┌─DEBUG───┐
55──┴─NODEBUG─┴───────────────────────────────────────────────────────5%

Default is: NODEBUG.

DEBUG
Activates the debugging sections.

NODEBUG
Suppresses the debugging sections.

Performance Consideration
To improve performance, use this option only while debugging.

ERRCOUNT
ERRCOUNT specifies how many conditions of severity 1 (W-level) can occur before the
run-unit terminates abnormally. Any severity 2 (E-level) or higher will result in termi-
nation of the run-unit independent of the ERRCOUNT option.

55──ERRCOUNT──(──┬────────┬──)────────────────────────────────────────5%
└─number─┘

Default: ERRCOUNT(20).

number
The number of severity 1 conditions that can occur while this run-unit is running. If
the number of conditions exceeds number, the run-unit terminates abnormally.

FILESYS
FILESYS specifies the file system used for files for which no explicit file system
selections are made, either through an ASSIGN or an evironment variable. The option
applies to sequential, relative, and indexed files. For details about using FILESYS for
access to CICS files, see “Accessing SFS Data” on page 363.

┌─VSA─┐
55──FILESYS──(──┴─STL─┴──)────────────────────────────────────────────5%

Default is : FILESYS(VSA).

VSA The file system is VSAM.

194 COBOL Set for AIX Programming Guide


Syntax of Run-time Options

STL The file system is STL.

Only the first three characters of the file system identifier are used and the identifier is
case insensitive. For example, the following examples are all valid specifications for
VSAM:
Ÿ FILESYS(VSA)
Ÿ FILESYS(vSAM)
Ÿ FILESYS(vsa)

TRAP
TRAP indicates whether COBOL intercepts exceptions.

┌─ON──┐
55──TRAP──(──┼─────┼──)───────────────────────────────────────────────5%
└─OFF─┘

Default is : TRAP(ON).

Note: If TRAP(OFF) is in effect and you do not supply your own trap handler to handle
exceptional conditions, the conditions will result in a default action by the operating
system. For example, if your program attempts to store into an illegal location, the
default system action is to issue a message and terminate the process.

ON
Activates COBOL interception of exceptions.

OFF
Deactivates COBOL interception of exceptions.

Usage Notes
Ÿ Use TRAP(OFF) only when you need to analyze a program exception before
COBOL handles it.
Ÿ When you specify TRAP(OFF) in a non-CICS environment, no exception handlers
are established.
Ÿ Running with TRAP(OFF) (for exception diagnosis purposes) can cause many side
effects, because COBOL requires TRAP(ON). When you run with TRAP(OFF), you
can get side effects even if you do not encounter a software-raised condition,
program check, or abend. If you do encounter a program check or an abend with
TRAP(OFF) in effect, the following side effects can occur:

– Resources obtained by COBOL are not freed.


– Files opened by COBOL are not closed, so records might be lost.
– No messages or dump output are generated.
The run-unit terminates abnormally if such conditions are raised.

Chapter 11. Run-Time Options 195


Syntax of Run-time Options

UPSI
UPSI sets the eight UPSI switches on or off for applications that use COBOL routines.

55──UPSI──(──┬──────────┬──)──────────────────────────────────────────5%
└─nnnnnnnn─┘

Default is : UPSI(00000000).

nnnnnnnn
n represents one UPSI switch between 0 and 7, the leftmost n representing the
first switch. Each n can either be 0 (off) or 1 (on).

196 COBOL Set for AIX Programming Guide


Using Source Language to Debug

Chapter 12. Debugging Techniques


COBOL provides several language elements and facilities to help you determine the
cause of problems in program behavior. This chapter focuses on how to use source
language for debugging and describes the compiler options that make debugging
easier.

This chapter describes only COBOL source language debugging techniques. The
XLDB Debugger is a graphical debugging tool you will find useful for debugging pro-
grams. For help with the debugger, refer to its online help and information.

Using Source Language to Debug


You can use several COBOL language features to pinpoint the cause of a failure in
your program. If the program is part of a large application already in production, you
will not want to re-compile and run the program again to debug. Instead, you can write
a small test case to simulate the part of the program that failed and code some of these
debugging features of the COBOL language in the test case to help detect the exact
cause of the problem:
Ÿ DISPLAY statements.
Ÿ USE EXCEPTION/ERROR declaratives.
Ÿ Class test.
Ÿ INITIALIZE or SET verbs.
Ÿ Scope terminators.
Ÿ File status keys.
Ÿ USE FOR DEBUGGING declaratives.

The rules for using each of these language features are explained in IBM COBOL Lan-
guage Reference.

Tracing Program Logic (DISPLAY Statements)


You can use the interactive debugger available on your platform to step through your
program (compiled with the TEST option), or adding DISPLAY statements can help you
trace through the logic of the program. If, for example, you determine that the problem
appears in an EVALUATE statement or in a set of nested IF statements, DISPLAY state-
ments in each path will show you how the logic flow is working. If you determine that
the problem is being caused by the way a numeric value is calculated, you can use
DISPLAY statements to check the value of some of the interim results.

For example, to determine whether a particular routine started and finished you might
insert code like this into your program:
DISPLAY "ENTER CHECK PROCEDURE"
.
. (checking procedure routine)
.
DISPLAY "FINISHED CHECK PROCEDURE"

 Copyright IBM Corp. 1996, 1998 197


Using Source Language to Debug

After you are sure that the routine works correctly, you can put asterisks in column 7 of
the DISPLAY statement lines, which converts them to comment lines. Alternatively, you
might put a 'D' in column 7 of your DISPLAY (or any other debugging) statements. If
you include the WITH DEBUGGING MODE clause in the ENVIRONMENT DIVISION, the 'D'
in column 7 will be ignored and the DISPLAY statements will be implemented. Without
the DEBUGGING MODE clause, the 'D' in column 7 makes the statement a comment.

Before you put the program into production, delete all the debugging aids you used and
re-compile the program. The program will run more efficiently and use less storage.
CICS: The DISPLAY statement cannot be used in programs running under CICS.

Handling Input/Output Errors (USE EXCEPTION/ERROR Declaratives)


If you have determined that the problem lies in one of the I/O procedures in your
program, you can include the USE EXCEPTION/ERROR declarative to help debug the
problem.

If the file fails to open for some reason, the appropriate EXCEPTION/ERROR declarative
will be performed. The appropriate declarative might be a specific one for the file or
one provided for the different open attributes—INPUT, OUTPUT, I/O, or EXTEND.

Each USE AFTER STANDARD ERROR statement must be coded in a separate section.
This section(s) must be coded immediately after the DECLARATIVE SECTION keyword of
the PROCEDURE DIVISION. The rules for coding these statements are provided in IBM
COBOL Language Reference.

Validating Data (Class Test)


If you suspect that your program is trying to perform arithmetic on non-numeric data or
is somehow receiving the wrong type of data on an input record, you can use the class
test to validate the type of data. The class test checks whether data is alphabetic,
alphabetic-lower, alphabetic-upper, MBCS, KANJI, or numeric.

Assessing Switch Problems (INITIALIZE or SET Statements)


Using INITIALIZE or SET statements to initialize a table or variable is useful when you
suspect that the problem might be caused by residual data left in those fields. If the
problem you are having happens intermittently and not always with the same data, the
problem could be that a switch is not initialized but generally is set to the right value (0
or 1) by accident. By including a SET statement to ensure that the switch is initialized,
you can either determine that the uninitialized switch is the problem or remove that as a
possible cause.

Improving Program Readability (Explicit Scope Terminators)


Scope terminators can help you in debugging because they indicate clearly the end of a
statement. The logic of your program will become more apparent, and therefore easier
to trace, if you use scope terminators.

198 COBOL Set for AIX Programming Guide


Using Source Language to Debug

Finding Input/Output Errors (File Status Keys)


File status keys can help you determine if your program errors are due to the logic of
your program or if they are I/O errors occurring on the storage media.

To use file status keys as a debugging aid, include a test after each I/O statement to
check for a value other than zero in the status key. If the value is other than zero, you
can expect that you will receive an error message. You can use a nonzero value as an
indication that you should look at the way the I/O procedures in the program were
coded. You can also include procedures to correct the error based on the value of the
status key.

The status key values and their associated meanings are described in the IBM COBOL
Language Reference.

Generating Information about Procedures (USE FOR DEBUGGING Declaratives)


USE FOR DEBUGGING declaratives are another way to generate information about your
program or test case and how it is running. The declarative allows you to include state-
ments in the program and indicate when they should be performed when you run your
compiled program. For example, if you want to check how many times a procedure is
run, you could include a debugging procedure in the USE FOR DEBUGGING declarative
and use a counter to keep track of the number of times control passes to that proce-
dure.

Rules for Debugging Statements and Debugging Lines


Each USE FOR DEBUGGING declarative must be coded in a separate section. This
section or these sections must be coded in the DECLARATIVES SECTION of the PROCE-
DURE DIVISION. The rules for coding them are provided in IBM COBOL Language Ref-
erence.

You can have either debugging lines or debugging statements or both in your program.
Debugging lines are statements in your program that are identified by a 'D' in column 7.
Debugging statements are the statements coded in the DECLARATIVES SECTION of the
PROCEDURE DIVISION.

Ÿ The debugging statements in a USE FOR DEBUGGING declarative must:


– Be only in a DECLARATIVE SECTION.
– Follow the header USE FOR DEBUGGING.
– Be only in the outermost program; they are not valid in nested programs.
Debugging sections are also never triggered by procedures contained in
nested programs.
Ÿ Debugging lines must have a D in column 7 to identify them.

To use debugging lines in your program, you must include the WITH DEBUGGING MODE
clause on the SOURCE-COMPUTER line in the ENVIRONMENT DIVISION.

Chapter 12. Debugging Techniques 199


Using Source Language to Debug

To use debugging sections in your program, you must include both:


Ÿ The WITH DEBUGGING MODE clause
Ÿ The DEBUG run-time option
See the IBM COBOL Language Reference appendix on source-language debugging for
more details.
Options Note: The TEST compiler option and the WITH DEBUGGING MODE phrase
are mutually exclusive, with the WITH DEBUGGING MODE phrase taking precedence.

USE FOR DEBUGGING Example


The program segments in Figure 50 on page 201 show what kind of statements are
needed to use a DISPLAY statement and a USE FOR DEBUGGING declarative to test a
program. The DISPLAY statement is used to generate information on the terminal or on
the output file The USE FOR DEBUGGING declarative is used with a counter to show
how many times a routine was actually run.

Use the adding-to-a-counter technique to check:


1. How many times a PERFORM was executed. You will know whether a particular
routine is being used and whether the control structure you are using is correct.
2. How many times a loop routine actually executes. This will tell you whether the
loop is executing and whether the number you have used for the loop is accurate.

200 COBOL Set for AIX Programming Guide


Using Source Language to Debug

Environment Division
.
.
.
Data Division.
.
.
.
Working-Storage Section.
.
. (other entries your program needs)
.

ð1 Trace-Msg PIC X(3ð) Value " Trace for Procedure-Name : ".


ð1 Total PIC 9(9) Value 1.
.
.
.
Procedure Division.
Declaratives.
Debug-Declaratives Section.
Use For Debugging On Some-Routine.
Debug-Declaratives-Paragraph.
Display Trace-Msg, Debug-Name, Total.
End Declaratives.

Main-Program Section.
.
. (source program statements)
.
Perform Some-Routine.
.
. (source program statements)
.
Stop Run.
Some-Routine.
.
. (whatever statements you need in this paragraph)
.
Add 1 To Total.
Some-Routine-End

Figure 50. Example of Using the USE FOR DEBUGGING EXAMPLE

In Figure 50, the DISPLAY statement coded in the DECLARATIVES SECTION will issue
this message:
Trace For Procedure-Name : Some-Routine 22
every time the procedure SOME-ROUTINE is run. The number at the end of the message,
22, is the value accumulated in the data-item, TOTAL; it shows the number of times
SOME-ROUTINE has been run. The statements in the debugging declarative are per-
formed before the named procedure is run.

Chapter 12. Debugging Techniques 201


Using Compiler Options for Debugging

Another Use for the DISPLAY Statement: You can also use the DISPLAY statement
technique shown above to trace program execution and show the flow through your
program. You do this by changing the USE FOR DEBUGGING declarative in the DECLAR-
ATIVES SECTION to:
USE FOR DEBUGGING ON ALL PROCEDURES.
and dropping the word TOTAL from the DISPLAY statement. Now, a message will be
displayed before every non-debugging procedure in the outermost program is run.

Using Compiler Options for Debugging

The FLAG Option


This section discusses the compiler options that generate information to help you find
coding mistakes and other errors in your program.

The FLAG option lets you select the level of error to be diagnosed during compilation
and indicate where the syntax-error messages appear in the listing. Use FLAG(I) or
FLAG(I,I) to be notified of all errors in your program.

Code in the first parameter the lowest severity level of the syntax-error messages to be
issued. You can code in the optional second parameter the lowest level of the syntax
messages to be embedded in the source listing.

If you specify:

I (informational)
You get all the messages. I-level messages generate a return code of zero; RC=0.

W (warning)
You get all the warning messages and those of a higher severity. W-level errors
generate a return code of four; RC=4.

E (error)
You get all error messages and those of a higher severity. E-level errors generate
a return code of eight; RC=8.

S (severe)
You get all severe and U (unrecoverable) messages. S-level errors generate a
return code of twelve; RC=12.

U (unrecoverable)
You get only unrecoverable messages. U-level errors generate a return code of
sixteen; RC=16.

When you specify the second parameter, the syntax-error messages are embedded in
the source listing at the point where the compiler had enough information available to
detect the error. All embedded messages, except those issued by the library compiler
phase, will directly follow the statement to which they refer. The number of the state-
ment containing the error is also included with the message. Embedded messages are
repeated with the rest of the diagnostic messages following the source listing.
202 COBOL Set for AIX Programming Guide
Using Compiler Options for Debugging

Embedded Messages:
1. If NOSOURCE is one of your options, the syntax-error messages are included only
in the list at the end of the listing.
2. U-level errors are not embedded in the source listing, as an error of this severity
terminates the compilation.

For an illustration of how messages identifying syntax errors are imbedded in the
source listing, see Figure 51 on page 203.

Note that some messages in the summary apply to more than one COBOL statement.

DATA VALIDATION AND UPDATE PROGRAM FLAGOUT Date ð2/27/1998 Time 12:26:53 Page 26
LineID PL SL ----+-\A-1-B--+----2----+----3----+----4----+----5----+----6----+----7-|--+----8 Map and Cross Reference
.
.
.
ððð977 /
ððð978 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ððð979 \\\ I N I T I A L I Z E P A R A G R A P H \\
ððð98ð \\\ Open files. Accept date, time and format header lines. \\
ððð981 IA469ð\\\ Load location-table. \\
ððð982 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ððð983 1ðð-initialize-paragraph.
ððð984 move spaces to ws-transaction-record IMP 339
ððð985 move spaces to ws-commuter-record IMP 315
ððð986 move zeroes to commuter-zipcode IMP 326
ððð987 move zeroes to commuter-home-phone IMP 327
ððð988 move zeroes to commuter-work-phone IMP 328
ððð989 move zeroes to commuter-update-date IMP 332
ððð99ð open input update-transaction-file 2ð3

==ððð99ð==> IGYPS2ð52-S An error was found in the definition of file "LOCATION-FILE". The
reference to this file was discarded.

ððð991 location-file 192


ððð992 i-o commuter-file 18ð
ððð993 output print-file 216
ððð994 if loccode-file-status not = "ðð" or 248
ððð995 update-file-status not = "ðð" or 247
ððð996 updprint-file-status not = "ðð" 249
ððð997 1 display "Open Error ..."
ððð998 1 display " Location File Status = " loccode-file-status 248
ððð999 1 display " Update File Status = " update-file-status 247
ðð1ððð 1 display " Print File Status = " updprint-file-status 249
ðð1ðð1 1 perform 9ðð-abnormal-termination 1433
ðð1ðð2 end-if
ðð1ðð3 IA476ð if commuter-file-status not = "ðð" and not = "97" 24ð
ðð1ðð4 1 display "1ðð-OPEN"
ðð1ðð5 1 move 1ðð to comp-code 23ð
ðð1ðð6 1 perform 5ðð-vsam-error 1387
ðð1ðð7 1 display "Commuter File Status (OPEN) = "
ðð1ðð8 1 commuter-file-status 24ð
ðð1ðð9 1 perform 9ðð-abnormal-termination 1433
ðð1ð1ð IA479ð end-if

Figure 51 (Part 1 of 3). FLAG(I,I) Output

Chapter 12. Debugging Techniques 203


Using Compiler Options for Debugging

ðð1ð11 accept ws-date from date UND

==ðð1ð11==> IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.

ðð1ð12 IA481ð move corr ws-date to header-date UND 463

==ðð1ð12==> IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.

ðð1ð13 accept ws-time from time UND

==ðð1ð13==> IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.

ðð1ð14 IA483ð move corr ws-time to header-time UND 457

==ðð1ð14==> IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.

ðð1ð15 IA484ð read location-file 192


.
.
.
DATA VALIDATION AND UPDATE PROGRAM FLAGOUT Date ð2/27/1998 Time 12:26:53 Page 69
LineID Message code Message text

192 IGYDS1ð5ð-E File "LOCATION-FILE" contained no data record descriptions. The file definition was discarded.

899 IGYPS2ð52-S An error was found in the definition of file "LOCATION-FILE". The reference to this file was discarded.

Same message on line: 99ð

1ð11 IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.

Same message on line: 1ð12

1ð13 IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.

Same message on line: 1ð14

1ð15 IGYPS2ð53-S An error was found in the definition of file "LOCATION-FILE". This input/output statement was discarded.

Same message on line: 1ð27

1ð26 IGYPS2121-S "LOC-CODE" was not defined as a data-name. The statement was discarded.

12ð9 IGYPS2121-S "COMMUTER-SHIFT" was not defined as a data-name. The statement was discarded.

Same message on line: 123ð

121ð IGYPS2121-S "COMMUTER-HOME-CODE" was not defined as a data-name. The statement was discarded.

Same message on line: 1231

1212 IGYPS2121-S "COMMUTER-NAME" was not defined as a data-name. The statement was discarded.

Same message on line: 1233

1213 IGYPS2121-S "COMMUTER-INITIALS" was not defined as a data-name. The statement was discarded.

Same message on line: 1234

1223 IGYPS2121-S "WS-NUMERIC-DATE" was not defined as a data-name. The statement was discarded.

Figure 51 (Part 2 of 3). FLAG(I,I) Output

204 COBOL Set for AIX Programming Guide


Using Compiler Options for Debugging

Messages Total Informational Warning Error Severe Terminating


Printed: 19 1 18
\ Statistics for COBOL program FLAGOUT:
\ Source records = 1755
\ Data Division statements = 279
\ Procedure Division statements = 479
End of compilation 1, program FLAGOUT, highest severity: Severe.
Return code 12

Figure 51 (Part 3 of 3). FLAG(I,I) Output

The NOCOMPILE Option


Use the NOCOMPILE option to produce a listing that will help you find your COBOL
coding mistakes, such as missing definitions, improperly defined data names, and dupli-
cate data names. You can use NOCOMPILE two ways: with or without parameters.

Using NOCOMPILE with Parameters


When you use NOCOMPILE(x), where x is one of the error levels, your program will be
compiled, if all the errors are of a lower severity than the x level. If an error of x level
or higher occurs, the compilation stops and your program will be syntax-checked only.
You will receive a source listing if you have specified the SOURCE option.

Using NOCOMPILE without Parameters


When you use NOCOMPILE without parameters, the compiler only syntax-checks the
source program. If you have also specified the SOURCE option, the compiler will
produce a listing after the syntax-checking is completed. The compiler does not
produce object code when NOCOMPILE without parameters is in effect.

The following compiler options are suppressed when you use NOCOMPILE without
parameters: LIST, OBJECT, OPTIMIZE, SSRANGE, and TEST.

The SEQUENCE Option


The SEQUENCE option tells the compiler to check your source program and flag state-
ments that are out of sequence. You can use this option to tell you if a section of your
source program was moved or deleted accidentally.

When you use SEQUENCE, the compiler checks the source statement numbers you
have supplied to see if they are in ascending order. Two asterisks are placed along-
side any statement numbers out of sequence, and the total number of these statements
is printed out as the first line of the diagnostics following the source listing.

The XREF Option


The XREF(FULL) option tells the compiler to generate a sorted cross-reference listing of
data-names, procedure-names, and program-names. The cross-reference will include
the line number where the data-name, procedure-name, or program-name was defined
as well as the line numbers of all references.

You can use the cross-reference listing produced by the XREF option to find out where
a data-name, procedure-name, or program-name was defined and referenced.

Chapter 12. Debugging Techniques 205


Using Compiler Options for Debugging

The XREF(SHORT) option allows you to control the cross-reference listing by printing
only the explicitly referenced variables.

When you use both the XREF (with FULL or SHORT) and the SOURCE options, you will
get a modified cross-reference printed to the right of the source listing. This embedded
cross-reference gives the line number where the data-name or procedure-name was
defined.

For more information on the XREF option and some example listings, see “A Data-
Name, Procedure-Name, and Program-Name Cross-Reference Listing” on page 216.

The MAP Option


Use the MAP option to produce a listing of the items you defined in the DATA DIVISION,
plus all items implicitly declared.

For more information on the MAP option, see “Data Map Listing” on page 211.

Embedded Map Summary


When you use the MAP option, an embedded MAP summary is generated to the right of
the COBOL source data declaration. An embedded MAP summary contains condensed
data MAP information. For more information, see “Embedded MAP Summary” on
page 212.

The SSRANGE Option


Use the SSRANGE compiler option to check:
Ÿ Subscripted or indexed data references.
The subscripted or indexed data reference is checked to determine if the effective
address of the desired element is within the maximum boundary of the specified
table.
Ÿ Variable-length data references (a reference to a data item that contains an
OCCURS DEPENDING ON clause).

The variable-length data reference is checked to determine if the actual length is


positive and within the maximum defined length for the group data item.
Ÿ Reference-modified data references.
The reference-modified data reference is checked to determine if the offset and
length are positive and the sum of the offset and length are within the maximum
length for the data item.

When the SSRANGE option is specified, checking is not performed until run time and
then, only if both of the following are true:
Ÿ The COBOL statement containing the indexed, subscripted, variable-length, or
reference-modified data item is actually performed.
Ÿ The CHECK run-time option is ON at run time.

206 COBOL Set for AIX Programming Guide


Getting Useful Listing Components

If any check finds that an address is generated that is outside of the address range of
the group data item containing the referenced data, an error message will be generated
and the program will stop running. The error message identifies the table or identifier
that was being referenced and the line number in the program where the error hap-
pened. Additional information is provided depending on the type of reference that
caused the error.

If all subscripts, indices, or reference modifiers are literals in a given data reference and
they result in a reference outside of the data item, the error will be diagnosed at
compile time, regardless of the setting of the SSRANGE compiler option.
Performance Note: SSRANGE can cause the performance of your program to diminish
somewhat because of the extra overhead needed to check each subscripted or indexed
item.

The TEST Option


On the mainframe, you select the TEST option to prepare your program for use with the
debugger. IBM COBOL Set for AIX includes a graphical debugger. However, rather
than use the TEST option to prepare your executable COBOL program for use with the
debugger, you can use the -g option of the cob2 command (see “Compiling and Linking
Programs” on page 135).

Getting Useful Listing Components


This section introduces the different types of compiler listings produced by COBOL.
The type of listing produced by the compiler depends on which compiler options you
use.
Note: The listing produced by the compiler is not a programming interface and is
subject to change.

After reading this section you should be familiar with each type of output; you will know
how to request each type and what kind of information is provided in the output.

A Short Listing—the Bare Minimum


If you do not specify any compiler options and the default options are NOSOURCE,
NOXREF, NOVBREF, NOMAP, NOOFFSET, and NOLIST, or if all the compiler diagnostic
options have been turned off, you will get a short listing.

The short listing contains diagnostic messages about the compilation, a list of the
options in effect for the program, and statistics about the content of the program.
Figure 52 on page 208 is an example of a short listing.

The listing is explained after Figure 52, and the numbers used in the explanation corre-
spond to those in the figure. (For illustrative purposes, some errors that cause diag-
nostic messages to be issued were deliberately introduced.)

Chapter 12. Debugging Techniques 207


Getting Useful Listing Components

PP 5765-548 IBM COBOL Set for AIX 1.1.ð Date ð2/27/1998 Time 12:26:53 Page 1 .1/
Invocation parameters: .2/
quote
PROCESS(CBL) statements:
CBL FLAG(I,I),MAP,TEST
CBL NONUMBER,QUOTE,SEQ,XREF,VBREF .3/
Options in effect: .4/
ADATA
QUOTE
BINARY(NATIVE)
CALLINT(SYSTEM,NODESCRIPTOR)
CHAR(NATIVE)
NOCICS
COLLSEQ(BINARY)
NOCOMPILE(S)
NOCURRENCY
| NODATEPROC
NODYNAM
ENTRYINT(SYSTEM)
EXIT(NOINEXIT,NOPRTEXIT,NOLIBEXIT,ADEXIT(IWZRMGUX))
FLAG(I,I)
NOFLAGSTD
FLOAT(NATIVE)
NOIDLGEN
LIB
LINECOUNT(6ð)
NOLIST
MAP
NONUMBER
NOOPTIMIZE
PGMNAME(LONGUPPER)
PROBE
NOPROFILE
SEPOBJ
SEQUENCE
SIZE(2ð97152)
SOURCE
SPACE(1)
SQL
NOSSRANGE
TERM
TEST
NOTHREAD
NOTILED
TRUNC(STD)
NOTYPECHK
VBREF
NOWORD
XREF(FULL)
| YEARWINDOW(19ðð)
ZWB

Figure 52 (Part 1 of 2). Example of a Short Listing

208 COBOL Set for AIX Programming Guide


Getting Useful Listing Components

DATA VALIDATION AND UPDATE PROGRAM .5/ SLISTING Date ð2/27/1998 Time 12:26:53 Page 2

LineID Message code Message text .6/

IGYDSð139-W Diagnostic messages were issued during processing of compiler options. These messages are
located at the beginning of the listing.

193 IGYDS1ð5ð-E File "LOCATION-FILE" contained no data record descriptions. The file definition was discarded.

889 IGYPS2ð52-S An error was found in the definition of file "LOCATION-FILE". The reference to this file
was discarded.

Same message on line: 983

993 IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.

Same message on line: 994

995 IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.

Same message on line: 996

997 IGYPS2ð53-S An error was found in the definition of file "LOCATION-FILE". This input/output statement
was discarded.

Same message on line: 1ðð9

1ðð8 IGYPS2121-S "LOC-CODE" was not defined as a data-name. The statement was discarded.

1219 IGYPS2121-S "COMMUTER-SHIFT" was not defined as a data-name. The statement was discarded.

Same message on line: 124ð

122ð IGYPS2121-S "COMMUTER-HOME-CODE" was not defined as a data-name. The statement was discarded.

Same message on line: 1241

1222 IGYPS2121-S "COMMUTER-NAME" was not defined as a data-name. The statement was discarded.

Same message on line: 1243

1223 IGYPS2121-S "COMMUTER-INITIALS" was not defined as a data-name. The statement was discarded.

Same message on line: 1244

1233 IGYPS2121-S "WS-NUMERIC-DATE" was not defined as a data-name. The statement was discarded.

Messages Total Informational Warning Error Severe Terminating .7/

Printed: 21 2 1 18

\ Statistics for COBOL program SLISTING: .8/


Source records = 1765
Data Division statements = 277
Procedure Division statements = 513

End of compilation 1, program SLISTING, highest severity: Severe. .9/


Return code 12

Figure 52 (Part 2 of 2). Example of a Short Listing

.1/ COBOL default page header, including compiler level information from the
LVLINFO installation time compiler option.

.2/ Message about options passed to the compiler at compiler invocation. This
message does not appear if no options were passed.
.3/ Options coded in the PROCESS (or CBL) statement.
.4/ Status of options at the start of this compilation.

Chapter 12. Debugging Techniques 209


Getting Useful Listing Components

.5/ Customized page header resulting from the COBOL program TITLE statement.
.6/ Program diagnostics. The first message will refer you to the library phase diag-
nostics, if there were any. Diagnostics for the library phase are always pre-
sented at the beginning of the listing.
.7/ Count of diagnostic messages in this program, grouped by severity level.
.8/ Program statistics for the program SLISTING.
.9/ Program statistics for the compilation unit. When you perform a batch compila-
tion (multiple outermost COBOL programs in a single compilation), the return
code is the highest message severity level for the entire compilation.

A Listing of Your Source Code—for Historical Records


By using the SOURCE compiler option, you request a copy of your source code to be
included with the compiler output. You will want this output for testing and debugging
your program—and as an historical record when the program is completely debugged.
Figure 53 shows an example of SOURCE output.

Using Your Own Line Numbers


The NUMBER compiler option tells the compiler to use your line numbers in the com-
piled program. When you use the NUMBER option, the compiler does a sequence
check of your source statement line numbers in columns 1 through 6 as the statements
are read in. When a line number is found to be out of sequence, the compiler assigns
to it a number with a value one higher than the line number of the preceding statement.
The new value is flagged with two asterisks. A diagnostic message indicating an out of
sequence error is also included in the compilation listing.

Figure 53 shows an example of the output produced by the NUMBER compiler option.
In the portion of the listing shown, the programmer numbered two of the statements out
of sequence.

DATA VALIDATION AND UPDATE PROGRAM .1/ IGYTCARA Date ð2/27/1998 Time 12:26:53 Page 22
LineID PL SL ----+-\A-1-B--+----2----+----3----+----4----+----5----+----6----+----7-|--+----8 Cross-Reference .2/
.3/ .4/ .5/
ð87ððð/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ð871ðð\\\ D O M A I N L O G I C \\
ð872ðð\\\ \\
ð873ðð\\\ Initialization. Read and process update transactions until \\
ð874ðð\\\ EOE. Close files and stop run. \\
ð875ðð\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ð876ðð procedure division.

Figure 53 (Part 1 of 2). Example of SOURCE and NUMBER Output

210 COBOL Set for AIX Programming Guide


Getting Useful Listing Components

ð877ðð ððð-do-main-logic.
ð878ðð display "PROGRAM SRCOUT - Beginning"
ð879ðð perform ð5ð-create-vsam-master-file.
ð8815ð display "perform ð5ð-create-vsam-master finished".
ð88151\\ ð88125 perform 1ðð-initialize-paragraph
ð882ðð display "perform 1ðð-initialize-paragraph finished"
ð883ðð read update-transaction-file into ws-transaction-record
ð884ðð at end
1 ð885ðð set transaction-eof to true
ð886ðð end-read
ð887ðð display "READ completed"
ð888ðð perform until transaction-eof
1 ð889ðð display "inside perform until loop"
1 ð89ððð perform 2ðð-edit-update-transaction
1 ð891ðð display "After perform 2ðð-edit "
1 ð892ðð if no-errors
2 ð893ðð perform 3ðð-update-commuter-record
2 ð894ðð display "After perform 3ðð-update "
1 ð8965ð else
ð89651\\ 2 ð896ðð perform 4ðð-print-transaction-errors
2 ð897ðð display "After perform 4ðð-errors "
1 ð898ðð end-if
1 ð899ðð perform 41ð-re-initialize-fields
1 ð9ðððð display "After perform 41ð-reinitialize"
1 ð9ð1ðð read update-transaction-file into ws-transaction-record
1 ð9ð2ðð at end
2 ð9ð3ðð set transaction-eof to true
1 ð9ð4ðð end-read
1 ð9ð5ðð display "After '2nd READ' "
ð9ð6ðð end-perform

Figure 53 (Part 2 of 2). Example of SOURCE and NUMBER Output

.1/ Customized page header resulting from the COBOL program TITLE statement.
.2/ The scale line labels Area A, Area B, and source code column numbers.
.3/ Source code line number assigned by compiler.
.4/ Program (PL) and statement (SL) nesting level.
.5/ Columns 1 through 6 of program (the sequence number area).

Data Map Listing


The MAP compiler option provides you with a mapping of all Data Division items, plus
all implicitly declared variables, of your program. You can see an example of MAP
output in Figure 54 on page 212. The numbers used in the explanation below corre-
spond to the numbers used in Figure 54. The terms and symbols used in MAP output
are described in Figure 56 on page 214.

Chapter 12. Debugging Techniques 211


Getting Useful Listing Components

DATA VALIDATION AND UPDATE PROGRAM IGYTCARA Date ð2/27/1998 Time 12:26:53 Page 22

Data Division Map

.1/
Data Definition Attribute codes (rightmost column) have the following meanings:
D = Object of OCCURS DEPENDING G = GLOBAL LSEQ= ORGANIZATION LINE SEQUENTIAL
E = EXTERNAL O = Has OCCURS clause SEQ= ORGANIZATION SEQUENTIAL
VLO=Variably Located Origin OG= Group has own length definition INDX= ORGANIZATION INDEXED
VL= Variably Located R = REDEFINES REL= ORGANIZATION RELATIVE

.2/ .3/ .4/ .5/ .6/ .7/ .8/


Source Hierarchy and Data Def
LineID Data Name Length(Displacement) Data Type Attributes
4 PROGRAM-ID IGYTCARA----------------------------------------------------------------------------------\
18ð FD COMMUTER-FILE . . . . . . . . . . . . . . . . File INDX
182 1 COMMUTER-RECORD . . . . . . . . . . . . . . . 8ð Group
183 2 COMMUTER-KEY. . . . . . . . . . . . . . . . 16(ððððððð) Display
184 2 FILLER. . . . . . . . . . . . . . . . . . . 64(ððððð16) Display
186 FD COMMUTER-FILE-MST . . . . . . . . . . . . . . File INDX
188 1 COMMUTER-RECORD-MST . . . . . . . . . . . . . 8ð Group
189 2 COMMUTER-KEY-MST. . . . . . . . . . . . . . 16(ððððððð) Display
19ð 2 FILLER. . . . . . . . . . . . . . . . . . . 64(ððððð16) Display
192 FD LOCATION-FILE . . . . . . . . . . . . . . . . File SEQ
2ð3 FD UPDATE-TRANSACTION-FILE . . . . . . . . . . . File SEQ
2ð8 1 UPDATE-TRANSACTION-RECORD . . . . . . . . . . 8ð Display
216 FD PRINT-FILE. . . . . . . . . . . . . . . . . . File SEQ
221 1 PRINT-RECORD. . . . . . . . . . . . . . . . . 121 Display
228 1 WORKING-STORAGE-FOR-IGYCARA . . . . . . . . . 1 Display

Figure 54. Example of MAP Output

.1/ Explanations of the data definition attribute codes.


.2/ Source line number where the data item was defined.
.3/ Level definition or number. The compiler generates this number in the following
way:
Ÿ First level of any hierarchy is always 01. Increase 1 for each level— any
item you coded as 02 through 49.
Ÿ Level numbers 66, 77, and 88, and the indicators FD and SD, are not
changed.
.4/ Data-name that is used in the source module.
.5/ Length of data item. Base locator value.
.6/ Hexadecimal displacement from the beginning of the containing structure.
.7/ The data type and usage. These terms are explained in Figure 56 on
page 214.
.8/ Data definition attribute codes. The definitions are explained at the top of the
DATA DIVISION Map.

Embedded MAP Summary


An embedded MAP summary is printed by specifying the MAP option when generating a
listing. The summary appears in the right margin of the listing for lines in the DATA
DIVISION that contain data declarations. Figure 55 on page 213 describes the fields
included in the embedded map summary.

212 COBOL Set for AIX Programming Guide


Getting Useful Listing Components

When both XREF data and an embedded MAP summary exist on the same line, the
embedded MAP summary is printed first.

ððððð2 Identification Division.


ððððð3
ððððð4 Program-id. EMBMAP.
..
.
ððð176 Data division.
ððð177 File section.
ððð178
ððð179
ððð18ð FD COMMUTER-FILE
ððð181 record 8ð characters. .1/ .2/
ððð182 ð1 commuter-record. 8ð
ððð183 ð5 commuter-key PIC x(16). 16(ððððððð)
ððð184 ð5 filler PIC x(64). 64(ððððð16)

...
ððð221 IA162ð ð1 print-record pic x(121). 121
..
.
ððð227 Working-storage section.
ððð228 ð1 Working-storage-for-EMBMAP pic x. 1
ððð229
ððð23ð 77 comp-code pic S9999 comp. 2
ððð231 77 ws-type pic x(3) value spaces. 3
ððð232
ððð233
ððð234 ð1 i-f-status-area. 2
ððð235 ð5 i-f-file-status pic x(2). 2(ððððððð)
ððð236 88 i-o-successful value zeroes. IMP
ððð237
ððð238
ððð239 ð1 status-area. 8
ððð24ð ð5 commuter-file-status pic x(2). .3/ 2(ððððððð)
ððð241 88 i-o-okay value zeroes. IMP
ððð242 ð5 commuter-vsam-status. 6(ðððððð2)
ððð243 1ð vsam-r15-return-code pic 9(2) comp. 2(ðððððð2)
ððð244 1ð vsam-function-code pic 9(1) comp. 2(ðððððð4)
ððð245 1ð vsam-feedback-code pic 9(3) comp. 2(ðððððð6)
ððð246
ððð247 77 update-file-status pic xx. 2
ððð248 77 loccode-file-status pic xx. 2
ððð249 77 updprint-file-status pic xx. 2
..
.
ððð877 procedure division.
ððð878 ððð-do-main-logic.
ððð879 display "PROGRAM EMBMAP - Beginning".
ððð88ð perform ð5ð-create-vsam-master-file. 931
..
.

Figure 55. Example of an Embedded MAP Summary

.1/ Decimal length of data item


.2/ Hexadecimal displacement from the beginning of the base locator value
.3/ Special definition symbols. These symbols are:
UND The user-name is undefined
DUP The user-name is defined more than once
IMP An implicitly defined name, such as special registers and figurative con-
stants

Chapter 12. Debugging Techniques 213


Getting Useful Listing Components

IFN An intrinsic function reference


EXT An external reference
* The program-name is unresolved because the NOCOMPILE option is in
effect

Figure 56. Terms Used in MAP Output


Usage Description
ALPHA-EDIT Alphabetic-Edited
ALPHABETIC Alphabetic
AN-EDIT Alphanumeric-Edited
BINARY Binary (Computational)
COMP-1 Internal floating-point (single-precision)
COMP-2 Internal floating-point (double-precision)
DBCS DBCS (Display-1)
DBCS-EDIT DBCS Edited
DISP-NUM External Decimal
DISPLAY Alphanumeric
File processing method (VSAM) File (FD)
GROUP Group Fixed-Length
GRP-VARLEN Group Variable-Length
INDEX Index
INDX-NAME Index-name
Level name Condition (77)
Level name for condition name Condition (88)
Level name for RENAMES Condition (66)
NUM-EDIT Numeric-Edited
OBJECT REFERENCE Object reference
PACKED-DEC Internal Decimal (Computational-3)
POINTER Pointer
PROCEDURE-POINTER Pointer to an externally invocable program (or
function)
Sort file definition Sort Definition (SD)

Nested Program Map


The MAP compiler option also supplies you with a nested program map if your program
contains nested programs. The nested program map shows where the programs are
defined and provides program attribute information.

214 COBOL Set for AIX Programming Guide


Getting Useful Listing Components

Nested Program Map

.1/

Program Attribute codes (rightmost column) have the following meanings:


C = COMMON
I = INITIAL
U = PROCEDURE DIVISION USING...

.2/ .3/ .4/ .5/

Source Nesting Program


LineID Level Program Name from PROGRAM-ID paragraph Attributes
2 NESTED. . . . . . . . . . . . . . . . . . . . . . . . . . .
12 1 X1. . . . . . . . . . . . . . . . . . . . . . . . . . . .
2ð 2 X11 . . . . . . . . . . . . . . . . . . . . . . . . . .
27 2 X12 . . . . . . . . . . . . . . . . . . . . . . . . . .
35 1 X2. . . . . . . . . . . . . . . . . . . . . . . . . . . .

Figure 57. Example of Nested Program Map

.1/ Explanations of the program attribute codes.


.2/ The source line number where the program was defined.
.3/ Depth of program nesting.
.4/ The program name.
.5/ The program attribute codes.

A PROCEDURE DIVISION Listing with Assembler Expansion (LIST Output)


The LIST compiler option provides you with a listing of the PROCEDURE DIVISION along
with the assembler coding produced by the COBOL compiler. This type of output can
be especially helpful when you are trying to find the failing verb in a program. You can
also use this output to find the address in storage of a data item that was moved during
the program.
Note: The listing produced by the compiler is not a programming interface and is
subject to change.

Getting LIST Output


You request LIST output from the compiler by using the LIST compiler option when you
compile your program.

The assembler listing will be written to the listing file (a file with the same name as the
source program with the extension “.wlist”).

A Verb Cross-Reference Listing


The VBREF compiler-time option produces an alphabetic listing of all the verbs in your
program and shows where each is referenced. The output includes each verb used, a
count of the number of times it is used, and the line numbers where the verb is used.
You can use VBREF output as a handy lookup when you need to find an instance of a
particular verb.

Chapter 12. Debugging Techniques 215


Getting Useful Listing Components

.1/ .2/ .3/

2 ACCEPT . . . . . . . . . . . . 1ð1 1ð1


2 ADD. . . . . . . . . . . . . . 129 13ð
1 CALL . . . . . . . . . . . . . 14ð
5 CLOSE. . . . . . . . . . . . . 9ð 94 97 152 153
2ð COMPUTE. . . . . . . . . . . . 15ð 164 164 165 166 166 166 166 167 168 168 169 169 17ð 171 171
171 172 172 173
2 CONTINUE . . . . . . . . . . . 1ð6 1ð7
2 DELETE . . . . . . . . . . . . 96 119
47 DISPLAY. . . . . . . . . . . . 88 9ð 91 92 92 93 94 94 94 95 96 96 97 99 99 1ðð 1ðð 1ðð 1ðð
1ð3 1ð9 117 117 118 119 138 139 139 139 139 139 139 14ð 14ð 14ð
14ð 143 148 148 149 149 149 152 152 152 153 162
2 EVALUATE . . . . . . . . . . . 116 155
47 IF . . . . . . . . . . . . . . 88 9ð 93 94 94 95 96 96 97 99 1ðð 1ð3 1ð5 1ð5 1ð7 1ð7 1ð7 1ð9
11ð 111 111 112 113 113 113 113 114 114 115 115 116 118 119 124
124 126 127 129 132 133 134 135 136 148 149 152 152
183 MOVE . . . . . . . . . . . . . 9ð 93 95 98 98 98 98 98 99 1ðð 1ð1 1ð1 1ð2 1ð4 1ð5 1ð5 1ð6 1ð6
1ð7 1ð7 1ð8 1ð8 1ð8 1ð8 1ð8 1ð8 1ð9 11ð 111 112 113 113 113 114
114 114 115 115 116 116 117 117 117 118 118 118 119 119 12ð 121
121 121 121 121 121 121 121 121 121 122 122 122 122 122 123 123
123 123 123 123 123 124 124 124 125 125 125 125 125 125 125 126
126 126 126 126 127 127 127 127 128 128 129 129 13ð 13ð 13ð 13ð
131 131 131 131 131 132 132 132 132 132 132 133 133 133 133 133
134 134 134 134 134 135 135 135 135 135 135 136 136 137 137 137
137 137 138 138 138 138 141 141 142 142 144 144 144 144 145 145
145 145 146 149 15ð 15ð 15ð 151 151 155 156 156 157 157 158 158
159 159 16ð 16ð 161 161 162 162 162 168 168 168 169 169 17ð 171
171 172 172 173 173
5 OPEN . . . . . . . . . . . . . 93 95 99 144 148
62 PERFORM. . . . . . . . . . . . 88 88 88 88 89 89 89 91 91 91 91 93 93 94 94 95 95 95 95 96
96 96 97 97 97 1ðð 1ðð 1ð1 1ð2 1ð4 1ð9 1ð9 111 116 116 117 117
117 118 118 118 118 119 119 119 12ð 12ð 124 125 127 128 133 134
135 136 136 137 15ð 151 151 153 153
8 READ . . . . . . . . . . . . . 88 89 96 1ð1 1ð2 1ð8 149 151
1 REWRITE. . . . . . . . . . . . 118
4 SEARCH . . . . . . . . . . . . 1ð6 1ð6 141 142
46 SET. . . . . . . . . . . . . . 88 89 1ð1 1ð3 1ð4 1ð5 1ð6 1ð8 1ð8 136 141 142 149 15ð 151 152 154
155 156 156 156 156 157 157 157 157 158 158 158 158 159 159 159
159 16ð 16ð 16ð 16ð 161 161 161 161 162 162 164 164
2 STOP . . . . . . . . . . . . . 92 143
4 STRING . . . . . . . . . . . . 123 126 132 134
33 WRITE. . . . . . . . . . . . . 94 116 129 129 129 129 129 13ð 13ð 13ð 13ð 145 146 146 146 146 147
147 151 165 165 166 166 167 174 174 174 174 174 174 174 175 175

Figure 58. Example of VBREF Compiler Output

The numbers in the explanation below correspond to Figure 58.


.1/ Number of times the verb is used in the program.
.2/ Verb.
.3/ Line numbers where verb is used.

A Data-Name, Procedure-Name, and Program-Name Cross-Reference Listing


The XREF compiler option provides you with sorted cross-reference listings of data-
names, procedure-names, and program-names. The listings also tell you the location
of all references to a particular data-, procedure-, or program-name. This output will
help you find, quickly, a reference to a particular data-, procedure-, or program-name in
your program.

User-defined words in your program are sorted using the locale that is active. Hence,
the collating sequence will determine the order for the cross-reference listing, including
MBCS words.

216 COBOL Set for AIX Programming Guide


Getting Useful Listing Components

Group Names: Group names in a MOVE CORRESPONDING statement are listed in the
XREF listing. The cross-reference listing includes the group names and all the elemen-
tary names involved in the move.

Using a Sorted Cross-Reference Listing


You can use XREF output to find where you have used a particular data- or procedure-
name. If you need to find all of the statements that modify a particular data item, you
can use the output to determine what line(s) referenced or modified a data item. With
the XREF output, you can also determine the context in which a procedure is referenced
in your program. For example, you can determine whether a verb was used in a
PERFORM block or as part of a USE FOR DEBUGGING declarative. (The context of the
procedure reference is indicated by the characters preceding the line number.)

An "M" preceding a data-name reference indicates that the data-name is modified by this reference.

.1/ .2/ .3/

Defined Cross-reference of data names References

264 ABEND-ITEM1
265 ABEND-ITEM2
347 ADD-CODE . . . . . . . . . . . 1126 1192
381 ADDRESS-ERROR. . . . . . . . . M1156
28ð AREA-CODE. . . . . . . . . . . 1266 1291 1354 1375
382 CITY-ERROR . . . . . . . . . . M1159

.4/

Context usage is indicated by the letter preceding a procedure-name reference.


These letters and their meanings are:
A = ALTER (procedure-name)
D = GO TO (procedure-name) DEPENDING ON
E = End of range of (PERFORM) through (procedure-name)
G = GO TO (procedure-name)
P = PERFORM (procedure-name)
T = (ALTER) TO PROCEED TO (procedure-name)
U = USE FOR DEBUGGING (procedure-name)

.5/ .6/ .7/

Defined Cross-reference of procedures References

877 ððð-DO-MAIN-LOGIC
943 ð5ð-CREATE-VSAM-MASTER-FILE. . P879
995 1ðð-INITIALIZE-PARAGRAPH . . . P881
1471 11ðð-PRINT-I-F-HEADINGS. . . . P926
1511 12ðð-PRINT-I-F-DATA. . . . . . P928
1573 121ð-GET-MILES-TIME. . . . . . P154ð
1666 122ð-STORE-MILES-TIME. . . . . P1541
1682 123ð-PRINT-SUB-I-F-DATA. . . . P1562
17ð6 124ð-COMPUTE-SUMMARY . . . . . P1563
1ð52 2ðð-EDIT-UPDATE-TRANSACTION. . P89ð
1154 21ð-EDIT-THE-REST. . . . . . . P1145
1189 3ðð-UPDATE-COMMUTER-RECORD . . P893
1237 31ð-FORMAT-COMMUTER-RECORD . . P1194 P12ð9
1258 32ð-PRINT-COMMUTER-RECORD. . . P1195 P12ð6 P1212 P1222
1318 33ð-PRINT-REPORT . . . . . . . P12ð8 P1232 P1286 P131ð P137ð P1395 P1399
1342 4ðð-PRINT-TRANSACTION-ERRORS . P896

Figure 59. Example of XREF Output—Data-Name Cross-References

Chapter 12. Debugging Techniques 217


Getting Useful Listing Components

The numbers used in explanation below correspond to the numbers in Figure 59.
Cross-Reference of Data-Names
.1/ Line number where the name was defined.
.2/ Data-name.
.3/ Line numbers where the name was used. If an “M” precedes the line
number, the data-item was explicitly modified at the location.
Cross-Reference of Procedure References
.4/ Explanations of the context usage codes for procedure references.
.5/ Line number where the procedure-name is defined.
.6/ Procedure-name.
.7/ Line numbers where the procedure is referenced and the context usage
code for the procedure.

The XREF compiler option also provides you with a sorted cross-reference listing of
program names in your main program.

PP 5765-548 IBM COBOL Set for AIX 1.1.ð Date ð2/27/1998 Time 12:26:53 Page 4

.1/ .2/ .3/

Defined Cross-reference of programs References

EXTERNAL EXTERNAL1. . . . . . . . . . . 25
2 X. . . . . . . . . . . . . . . 41
12 X1 . . . . . . . . . . . . . . 33 7
2ð X11. . . . . . . . . . . . . . 25 16
27 X12. . . . . . . . . . . . . . 32 17
35 X2 . . . . . . . . . . . . . . 4ð 8

Figure 60. Example of XREF Output - Program Cross-Reference

.1/ The line number where the program-name was defined. If the program is
external, the word EXTERNAL will be displayed instead of a definition line
number.
.2/ The program name.
.3/ Line numbers where the program is referenced.

Using an Embedded Cross-Reference


The XREF compiler option also provides you with a modified cross-reference embedded
in the source listing. This embedded cross-reference provides the line number where
the data-name or procedure-name was defined.

218 COBOL Set for AIX Programming Guide


Getting Useful Listing Components

LineID PL SL ----+-\A-1-B--+----2----+----3----+----4----+----5----+----6----+----7-|--+----8 Map and Cross Reference


..
.
ððð878 procedure division.
ððð879 ððð-do-main-logic.
ððð88ð display "PROGRAM IGYTCARA - Beginning".
ððð881 perform ð5ð-create-vsam-master-file. 932 .1/
ððð882 perform 1ðð-initialize-paragraph. 984
ððð883 read update-transaction-file into ws-transaction-record 2ð4 34ð
ððð884 at end
ððð885 1 set transaction-eof to true 254
ððð886 end-read.
..
.

ððð984 1ðð-initialize-paragraph.
ððð985 move spaces to ws-transaction-record IMP 34ð .2/
ððð986 move spaces to ws-commuter-record IMP 316
ððð987 move zeroes to commuter-zipcode IMP 327
ððð988 move zeroes to commuter-home-phone IMP 328
ððð989 move zeroes to commuter-work-phone IMP 329
ððð99ð move zeroes to commuter-update-date IMP 333
ððð991 open input update-transaction-file 2ð4
ððð992 location-file 193
ððð993 i-o commuter-file 181
ððð994 output print-file 217
..
.

ðð1442 11ðð-print-i-f-headings.
ðð1443
ðð1444 open output print-file. 217
ðð1445
ðð1446 move function when-compiled to when-comp. IFN 698 .2/
ðð1447 move when-comp (5:2) to compile-month. 698 64ð
ðð1448 move when-comp (7:2) to compile-day. 698 642
ðð1449 move when-comp (3:2) to compile-year. 698 644
ðð145ð
ðð1451 move function current-date (5:2) to current-month. IFN 649
ðð1452 move function current-date (7:2) to current-day. IFN 651
ðð1453 move function current-date (3:2) to current-year. IFN 653
ðð1454
ðð1455 write print-record from i-f-header-line-1 222 635
ðð1456 after new-page. 138
..
.

Figure 61. Example of an Embedded Cross-Reference

.1/ The line number of the definition of the data-name or procedure-name in the
program.
.2/ Special definition symbols. These symbols are:
UND The user-name is undefined
DUP The user-name is defined more than once
IMP An implicitly defined name, such as special registers and figurative con-
stants
IFN An intrinsic function reference
EXT An external reference
* The program-name is unresolved because the NOCOMPILE option is in
effect

Chapter 12. Debugging Techniques 219


Debugging Assembler

Debugging User Exit Modules


To debug a user exit routine, you must invoke the debugger on the main compiler
module rather than COB2.EXE. This is because the main compiler module is a separate
process started by cob2, and the debugger can debug only one process.

To do this, first invoke cob2 with the -# option to see how cob2 invokes the main com-
piler module and what options it passes. For example, given the following cob2 invoca-
tion for compiling PGMNAME.CBL with the IWZRMGUX user exit and linking it:
cob2 -q"EXIT(ADEXIT(IWZRMGUX))" pgmname.cbl
modify the cob2 invocation as follows:
cob2 -# -q"EXIT(ADEXIT(IWZRMGUX))" pgmname.cbl
This is what you'll see:
igyccob2 -q"EXIT(ADEXIT(IWZRMGUX))" pgmname.cbl
ilink /free /nol /pm:vio pgmname.obj

You are interested in the IGYCCOB2 invocation because it is what actually calls your user
exit.

You can debug the user exit as follows:


idbug igyccob2 -q"EXIT(ADEXIT(IWZRMGUX))" pgmname.cbl
The debugger will automatically stop at the beginning of your user exit, assuming you
built the exit with debug information.

Debugging Assembler Routines


The debugger will automatically go to the Disassembly view if the module being
debugged does not have debug information. If the module is an assembler routine, of
course you can debug only in this view. You can set a breakpoint at a disassembled
statement in the Disassembly view by double clicking in the prefix area. It should be
noted that by default, during startup the debugger will run until it hits the first
debuggable statement it finds. If instead you would like the debugger to stop at the
very first instruction in the application (debuggable or not), you must use the "-i" option.
For example:
IDBUG -i progname

220 COBOL Set for AIX Programming Guide


Part 3. Object-Oriented Programming Topics
This part of the book covers object-oriented programming topics. Object-oriented pro-
grams are built from some new syntax plus the basic programming topics covered in
Part 1, “Coding Your Program” on page 1.

Chapter 13. Writing Object-Oriented Programs . . . . . . . . . . . . . . . . 222

Chapter 14. Using System Object Model (SOM) . . . . . . . . . . . . . . . . 269

Chapter 15. Using SOM IDL-Based Class Libraries . . . . . . . . . . . . . . 275

Chapter 16. Converting Procedure-Oriented Programs to Object-Oriented


Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310

 Copyright IBM Corp. 1996, 1998 221


Writing Object-Oriented Programs

Chapter 13. Writing Object-Oriented Programs


Object-oriented programs are based on classes and methods for objects. A class is a
template defining the data structure and capabilities of an object. The data structure is
commonly called instance data and the capabilities are commonly called methods.
Usually, a program creates and works with multiple object instances of a class. Each
instance has its own instance data and uses the methods defined for its class.

Consider a mail-order catalog business in which customers call service representatives


to place orders. The service representatives are working with a user interface on the
computer and creating an order. Therefore, in this situation there are two classes:
user interface and order. Because there are many service representatives each proc-
essing a different customer's order, there are multiple instances of the two classes
existing simultaneously.

Once classes are determined, the next step is to determine the methods the classes
need to do their work. The order class must provide the following services:
Ÿ Add items to the order
Ÿ Delete items from the order
Ÿ Calculate the cost of the order
Ÿ Provide the order number to the service representative
Ÿ Write the final order for later processing
The following methods for the order class meet the above need:
AddItem
Add an item to the order
DeleteItem
Delete an item from the order
CalculateCost
Calculate the cost of the order
GetOrderNumber
Provide the order number
WriteOrder
Write the final order

As you design your class and its methods, you discover the need for the class to keep
some instance data. Typically, an order class needs the following instance data:
Ÿ Order number
Ÿ Order date
Ÿ Number of items in the order
Ÿ Table of items ordered

Diagrams are very helpful when designing classes and their methods. The following
diagrams depict the order and user interface classes.

222  Copyright IBM Corp. 1996, 1998


Writing Object-Oriented Programs

┌────────────────┐ ┌──────────────────┐
│Order │ │UserInterface │
│ (order-number) │ │ (action) │
│ (order-date) │ │ (item) │
│ (order-count) │ ├──────────────────┤
│ (order-table) │ │1:ReadUserInput │
├────────────────┤ │2:WriteUserOutput │
│1:AddItem │ │3:WriteUserMessage│
│2:DeleteItem │ └──────────────────┘
│3:CalculateCost │
│4:GetOrderNumber│
│5:WriteOrder │
└────────────────┘
The words in parentheses are instance data and the words after the number and colon
are methods.

The class structure of this object-oriented system is a tree structure. This structure
shows how classes are related to each other and is known as the inheritance hierarchy.
Order and user interface are basic classes, so they inherit from the System Object
Model (SOM) base class, SOMObject.
Multiple Inheritance: All classes in COBOL inherit directly or indirectly from
SOMObject. When multiple inheritance is used, the class structure might not be a
tree—it may be an graph. However, the SOMObject class will always be at the root of
the tree or graph.

The complete class structure for the mail-order catalog system is diagramed as follows:
┌───────────┐
│SOMObject │
├───────────┤
│1:somNew │
│2:somInit │
│3:somFree │
│4:somUninit│
│5: ... │
└────┬──────┘
┌─────────┴──────────┐
┌────────┴───────┐ ┌────────┴─────────┐
│Order │ │UserInterface │
│ (order-number) │ │ (action) │
│ (order-date) │ │ (item) │
│ (order-count) │ ├──────────────────┤
│ (order-table) │ │1:ReadUserInput │
├────────────────┤ │2:WriteUserOutput │
│1:AddItem │ │3:WriteUserMessage│
│2:DeleteItem │ └──────────────────┘
│3:CalculateCost │
│4:GetOrderNumber│
│5:WriteOrder │
└────────────────┘
More Methods: SOMObject has many methods other than the four listed here. See
SOMobjects Developer's Toolkit User's Guide and SOMobjects Developer's Toolkit Pro-
grammer's Reference Manual for a complete description of all the SOM methods.

Chapter 13. Writing Object-Oriented Programs 223


Class ENVIRONMENT DIVISION

Writing a Class Definition


Like a COBOL program, a COBOL class definition consists of four divisions:
Ÿ IDENTIFICATION DIVISION
The class name and class inheritance information are defined in this division.
Ÿ ENVIRONMENT DIVISION
Associations between COBOL class names and SOM class names are defined in
this division.
Ÿ DATA DIVISION
Instance data is defined in this division.
Ÿ PROCEDURE DIVISION
Methods are defined in this division.

Class IDENTIFICATION DIVISION: Required


In the IDENTIFICATION DIVISION of a class, you name a class and provide inheritance
information for it. Optionally, you may give other identifying information. For example:
Identification Division. Required
Class-Id. Order INHERITS SOMObject. Required

The AUTHOR, INSTALLATION, DATE-WRITTEN, and DATE-COMPILED paragraphs are


optional and are treated as documentation.

CLASS-ID Paragraph
Use the CLASS-ID paragraph to:
Ÿ Name a class.
In the example above, Order is the class name.
Ÿ Specify the System Object Model (SOM) base class or user-written class from
which this class inherits its characteristics.
In the example above, INHERITS SOMObject indicates Order inherits its basic char-
acteristics from the base SOM class SOMObject.
Ÿ Name a metaclass.
Discussed in “Writing a Metaclass Definition” on page 258.

SOMObject must be specified in the REPOSITORY paragraph in the ENVIRONMENT DIVI-


SION (see “REPOSITORY Paragraph” on page 225). Order may optionally be speci-
fied in the REPOSITORY paragraph.

Class ENVIRONMENT DIVISION: Required


In the ENVIRONMENT DIVISION of a class, you describe the particular computer environ-
ment in which you are working and relate your class names to external SOM names.
For example:

224 COBOL Set for AIX Programming Guide


Class DATA DIVISION

Environment Division. Required


Configuration Section. Required
Repository. Required
Class SOMObject is 'SOMObject'
Class Order is 'Order'.

The SOURCE-COMPUTER, OBJECT-COMPUTER, and SPECIAL-NAMES paragraphs are


optional. If they are specified in a class CONFIGURATION SECTION, they apply to the
entire class definition, including all methods introduced by the class.

A class CONFIGURATION SECTION can consist of the same entries as a program CON-
FIGURATION SECTION, except the INPUT-OUTPUT SECTION. (See “CONFIGURATION
SECTION” on page 13.)

REPOSITORY Paragraph
The REPOSITORY paragraph declares to the compiler that the specified user-defined
word is a class name and optionally relates the class name to an external class name
in the SOM interface repository. You must specify any class name you explicitly refer-
ence in your class definition in the REPOSITORY paragraph. For example:
Ÿ SOM base classes.
In the example above, CLASS SOMObject IS 'SOMObject' indicates what you are
calling SOMObject in your COBOL program is also called SOMObject in the SOM
interface repository. All SOM names are mixed-case, so SOMObject spelled in
mixed-case is required to properly handle SOM case sensitivity.
Ÿ User-written classes from which your class is inheriting.
Discussed in “Writing a Subclass Definition” on page 242.
Ÿ Metaclass to which your class belongs.
Discussed in “Writing a Metaclass Definition” on page 258.
Ÿ Any class referenced in methods introduced by the class.

You may optionally include the name of the class you are defining. If you do not
include the name of your class, it is treated as all upper-case regardless of how you
typed it on the CLASS-ID. In the example above, Order is stored in the SOM interface
repository in mixed-case.

Class DATA DIVISION: Optional


In the DATA DIVISION of a class, you describe the instance data the class needs. For
example:

Chapter 13. Writing Object-Oriented Programs 225


Class PROCEDURE DIVISION

Data Division.
Working-Storage Section.
ð1 order-number PIC 9(5).
ð1 order-date PIC X(8).
ð1 order-count PIC 99.
ð1 order-table.
ð2 order-entry OCCURS 1ð TIMES.
ð3 order-item PIC X(5).

A class DATA DIVISION contains only a WORKING-STORAGE SECTION.

WORKING-STORAGE SECTION
A class WORKING-STORAGE SECTION describes instance data that is statically allocated
when the instance is created and exists until the instance is freed. By default, the data
is global to all the methods introduced by the class. Instance data in a COBOL class is
private. Thus, it cannot be referenced directly by any other class or subclass. See
“Special Methods” on page 231 for an example of how to share instance data in
COBOL.

Syntax of the class WORKING-STORAGE SECTION is generally the same as in a


program. (described in “WORKING-STORAGE SECTION and LOCAL-STORAGE
SECTION” on page 19).

Exceptions:
1. You cannot use the VALUE clause to initialize the data.
Class instance data is initialized by overriding the 'somInit' method. See “somInit”
on page 231 for an example using 'somInit'.
Level-88 Note: You can have 88 level numbers with the VALUE clause.
2. You cannot use the EXTERNAL attribute.
3. You can use the GLOBAL attribute, but it has no effect.

Class PROCEDURE DIVISION: Optional


The class PROCEDURE DIVISION contains only method definitions. See “Writing a
Method Definition” on page 228 for details about defining methods. A class definition
must be properly terminated with an END CLASS statement. For example:
End Class Order.
marks the end of the Order class.

226 COBOL Set for AIX Programming Guide


Class Example

Complete Class Example


The class definition for the order class:
IDENTIFICATION DIVISION.
\
\ Order is the name of the class
\ Order inherits from SOMObject (SOM base class)
\
CLASS-ID. Order INHERITS SOMObject.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
\
\ SOMObject is known as SOMObject in SOM repository
CLASS SOMObject IS 'SOMObject'
\
\ Order is known as Order in SOM repository
CLASS Order IS 'Order'.
DATA DIVISION.
WORKING-STORAGE SECTION.
\
\ Instance data for Order class
\
ð1 order-number PIC 9(5).
ð1 order-date PIC X(8).
ð1 order-count PIC 99.
ð1 order-table.
ð2 order-entry OCCURS 1ð TIMES.
ð3 order-item PIC X(5).
PROCEDURE DIVISION.
\
\ method definitions in here
\
END CLASS Order.

The class definition for the user interface class:


IDENTIFICATION DIVISION.
\
\ UserInterface is the name of the class
\ UserInterface inherits from SOMObject (SOM base class)
\
CLASS-ID. UserInterface INHERITS SOMObject.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
\
\ SOMObject is known as SOMObject in SOM repository
CLASS SOMObject IS 'SOMObject'
\
\ UserInterface is known as UserInterface in SOM repository
CLASS UserInterface IS 'UserInterface'.

Chapter 13. Writing Object-Oriented Programs 227


Method IDENTIFICATION DIVISION

DATA DIVISION.
WORKING-STORAGE SECTION.
\
\ Instance data for UserInterface class
\
ð1 uif-action PIC X(1ð).
88 uif-add VALUE 'AddItem'.
88 uif-delete VALUE 'DeleteItem'.
88 uif-quit VALUE 'Quit'.
ð1 uif-item PIC X(5).
PROCEDURE DIVISION.
\
\ method definitions in here
\
END CLASS UserInterface.

Writing a Method Definition


A COBOL method can be defined only inside a class definition. Each method name
within a class must be unique.

Like a COBOL program, a COBOL method definition consists of four divisions:


Ÿ IDENTIFICATION DIVISION
The method name and whether it is overriding another method are defined in this
division.
Ÿ ENVIRONMENT DIVISION
Similar to a program ENVIRONMENT DIVISION.
Ÿ DATA DIVISION
Similar to a program DATA DIVISION.
Ÿ PROCEDURE DIVISION
Similar to a program PROCEDURE DIVISION.

Method IDENTIFICATION DIVISION: Required


Use the IDENTIFICATION DIVISION to name a method and indicate whether it is over-
riding another method from a superclass. Optionally, you can give other identifying
information. For example:
Identification Division. Required
Method-Id. WriteOrder. Required

The AUTHOR, INSTALLATION, DATE-WRITTEN, and DATE-COMPILED paragraphs are


optional and are handled as documentation. You can use them for descriptive informa-
tion about your method.

228 COBOL Set for AIX Programming Guide


Method DATA DIVISION

METHOD-ID Paragraph
Use the METHOD-ID paragraph to name the method. In the example above, WriteOrder
is the method name. Other methods or programs use this name to invoke the method.

Method Override
Occasionally, a class defines a method whose name exists in a superclass. In this
case, the superclass method must be overridden with the OVERRIDE clause on the
METHOD-ID. System Object Model (SOM) provides two methods designed to be over-
ridden. These SOM methods allow you to initialize instance data when an instance is
created and save instance data when an instance is freed. The methods are called
'somInit' and 'somUninit' respectively. If you wish to override 'somInit', the IDENTIFICA-
TION DIVISION is coded as follows:
Identification Division. Required
Method-Id. "somInit" Override. Required

Method ENVIRONMENT DIVISION: Optional


The method ENVIRONMENT DIVISION has only one section, the INPUT-OUTPUT SECTION.
The INPUT-OUTPUT SECTION relates your method files to the external file names known
by the operating system. The syntax for a method INPUT-OUTPUT SECTION is the same
as for a program INPUT-OUTPUT SECTION (see “INPUT-OUTPUT SECTION:” on
page 16). For example:
Environment Division.
Input-Output Section.
File-Control.
Select order-file Assign OrdrFile.

Method DATA DIVISION: Optional


A method DATA DIVISION consists of any of four sections:
Ÿ FILE SECTION
A method FILE SECTION is the same as a program FILE SECTION except a method
FILE SECTION can define only EXTERNAL files.

(See “FILE SECTION (Using Data in Input/Output Operations)” on page 18 for


more information.)
Ÿ LOCAL-STORAGE SECTION
A separate copy of the data defined in the method LOCAL-STORAGE SECTION is
allocated for each invocation of the method and is freed on the return from the
method.
If the VALUE clause is specified, the data item is initialized to the value on every
invocation of the method.
The method LOCAL-STORAGE SECTION is similar to a program LOCAL-STORAGE
SECTION, except that the GLOBAL attribute has no effect.

(See “WORKING-STORAGE SECTION and LOCAL-STORAGE SECTION” on


page 19 for more information.)

Chapter 13. Writing Object-Oriented Programs 229


Method PROCEDURE DIVISION

Ÿ WORKING-STORAGE SECTION
A single copy of the data defined in the method WORKING-STORAGE SECTION is
allocated when the run-unit begins and persists in its last-used state until the run-
unit terminates. The same single copy of the WORKING-STORAGE data is used
whenever the method is invoked, regardless of the invoking object.
If the VALUE clause is specified, the data item is initialized to the value on the first
invocation of the method. The EXTERNAL clause may be specified for method
WORKING-STORAGE data items (see “Sharing Data Using the EXTERNAL Clause”
on page 346).
A method WORKING-STORAGE SECTION is similar to a program
WORKING-STORAGE SECTION except the GLOBAL attribute has no effect.

(See “WORKING-STORAGE SECTION and LOCAL-STORAGE SECTION” on


page 19 for more information.)
Ÿ LINKAGE SECTION
A method LINKAGE SECTION is the same as a program LINKAGE SECTION except
the GLOBAL attribute has no effect.
(See “LINKAGE SECTION (Using Data from Another Program)” on page 21 for
more information.)
See “Complete Class with Methods Example” on page 232 for a detailed example of a
method DATA DIVISION.

If the same data item is defined in both the class DATA DIVISION and the method DATA
DIVISION, a reference in the method to the data name refers to the data item in the
method DATA DIVISION. The method DATA DIVISION takes precedence.

Method PROCEDURE DIVISION: Optional


In the PROCEDURE DIVISION of a method, you code the executable statements to com-
plete the service the method is expected to provide. A method definition must be prop-
erly terminated with an END METHOD statement. For example:
End Method WriteOrder.
marks the end of the 'WriteOrder' method.

The EXIT METHOD statement returns control to the invoking program or method.
GOBACK has the same effect as EXIT METHOD. If the RETURNING clause is specified
when the method is invoked, the EXIT METHOD or GOBACK returns the value of the data
item to the invoking program or method. STOP RUN MAY be specified in a method;
however, it terminates the run-unit.

An implicit EXIT METHOD is generated as the last statement of every method PROCE-
DURE DIVISION.

All COBOL statements that can be coded in a program PROCEDURE DIVISION can be
coded in a method PROCEDURE DIVISION except:
Ÿ EXIT PROGRAM

230 COBOL Set for AIX Programming Guide


Method PROCEDURE DIVISION

Ÿ ENTRY statements
Ÿ The following obsolete elements of ANSI COBOL-85:
– ALTER
– GOTO without a specified procedure name
– SEGMENTATION
– USE FOR DEBUGGING

Special Methods
Simulated Attribute Methods: Instance variables in COBOL are all private in the
sense that they are fully encapsulated by the class, and are accessible directly only by
the methods that are introduced by the class that defines them. Normally, a well-
designed object-oriented application does not need to access instance variables from
outside the class.

The concept of a public instance variable, as defined in other object-oriented lan-


guages, and the concept of a class attribute, as defined by SOM and CORBA, are not
directly supported by COBOL. (A CORBA attribute is an instance variable that has 'get'
and/or 'set' methods to access and modify the value of the instance variable from
outside the class definition.) A COBOL programmer can provide this capability by
coding 'getX' and/or 'setX' methods for any instance variables X for which direct access
from outside the class is required. The recommended naming convention for these
methods is either 'getX' and 'setX' or perhaps 'get_X' and 'set_X'. Direct specification of
method names (such as _get_X) is not recommended because such names are not
valid in IDL, and use of such method names with the COBOL IDLGEN compiler option
specified would result in an IDL file that will not compile with the SOM compiler. For
example, this method
Identification Division.
Method-Id. 'getOrderNumber'.
Data Division.
Linkage Section.
ð1 ord-num PIC 9(5).
Procedure Division returning ord-num.
Move order-number To ord-num.
Exit Method.
End Method 'getOrderNumber'.
passes the order number to any program that invokes 'getOrderNumber'.

somInit: The 'somInit' method is automatically invoked when an object instance is


created. The default 'somInit' in SOM does nothing; however, you can override it to do
your own initialization of instance variables. For example:

Chapter 13. Writing Object-Oriented Programs 231


Method Example

Identification Division.
Method-Id. "somInit" Override.
Procedure Division.
Move Function Current-Date(1:8) To order-date.
Move ð To order-count.
Initialize order-table.
Exit Method.
End Method "somInit".

somUninit: The 'somIninit' method is automatically invoked when an object instance is


freed. The default 'somUninit' in SOM does nothing; however, you can override it if you
wish. For example:
Identification Division.
Method-Id. "somUninit" Override.
Data Division.
Local-Storage Section.
ð1 sub Pic 99.
Procedure Division.
Display order-date.
Perform varying sub from 1 by 1 until sub > order-count
Display order-table (sub)
End-Perform.
Exit Method.
End Method "somUninit".

The PROCEDURE DIVISION is discussed further in “PROCEDURE DIVISION” on


page 22.

Complete Class with Methods Example


The class and method definitions for the order class:
IDENTIFICATION DIVISION.
CLASS-ID. Orders INHERITS SOMObject.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in class defintion
REPOSITORY.
CLASS SOMObject IS 'SOMObject'
CLASS Orders IS 'Orders'.

DATA DIVISION.
\ Define instance data
WORKING-STORAGE SECTION.
ð1 order-number PIC 9(5).
ð1 order-date PIC X(8).
ð1 order-count PIC 99.
ð1 order-table.
ð2 order-entry OCCURS 1ð TIMES.
ð3 order-item PIC X(5).

232 COBOL Set for AIX Programming Guide


Method Example

PROCEDURE DIVISION.

\ Method to initialize instance data


\ - this overrides the default 'somInit' method
IDENTIFICATION DIVISION.
METHOD-ID. 'somInit' OVERRIDE.

PROCEDURE DIVISION.
MOVE FUNCTION CURRENT-DATE(1:8) TO order-date.
COMPUTE order-number = FUNCTION RANDOM ( 99999 ).
MOVE ð TO order-count.
INITIALIZE order-table.
EXIT METHOD.
END METHOD 'somInit'.

\ Method to add an item to an order


IDENTIFICATION DIVISION.
METHOD-ID. AddItem.

DATA DIVISION.
\ Use LOCAL-STORAGE for items that should be allocated
\ and initialized for each invocation of the method
LOCAL-STORAGE SECTION.
77 sub PIC 99.
ð1 found-flag PIC 9 VALUE 1.
88 found VALUE ð.
LINKAGE SECTION.
ð1 in-item PIC X(5).
ð1 add-flag PIC 9.

PROCEDURE DIVISION USING in-item


RETURNING add-flag.
MOVE 1 TO add-flag.
PERFORM VARYING sub FROM 1 BY 1
UNTIL (sub > 1ð) OR (found)
IF order-item (sub) = SPACES
MOVE in-item TO order-item (sub)
ADD 1 TO order-count
MOVE ð TO add-flag
SET found TO TRUE
END-IF
END-PERFORM.
EXIT METHOD.
END METHOD AddItem.

\ Method to delete an item from an order


IDENTIFICATION DIVISION.
METHOD-ID. DeleteItem.

DATA DIVISION.
\ Use LOCAL-STORAGE for items that should be allocated
\ and initialized for each invocation of the method

Chapter 13. Writing Object-Oriented Programs 233


Method Example

LOCAL-STORAGE SECTION.
77 sub PIC 99.
ð1 found-flag PIC 9 VALUE 1.
88 found VALUE ð.
LINKAGE SECTION.
ð1 out-item PIC X(5).
ð1 delete-flag PIC 9.

PROCEDURE DIVISION USING out-item


RETURNING delete-flag.
MOVE 1 TO delete-flag.
PERFORM VARYING sub FROM 1 BY 1
UNTIL (sub > 1ð) OR (found)
IF order-item (sub) = out-item
MOVE SPACES TO order-item (sub)
SUBTRACT 1 FROM order-count
MOVE ð TO delete-flag
SET found TO TRUE
END-IF
END-PERFORM.
EXIT METHOD.
END METHOD DeleteItem.

\ Method to compute the total cost of an order


IDENTIFICATION DIVISION.
METHOD-ID. ComputeCost.

DATA DIVISION.
\ Use LOCAL-STORAGE for items that should be allocated
\ and initialized for each invocation of the method
LOCAL-STORAGE SECTION.
77 sub PIC 99.
77 cost PIC 9(5)V99.
LINKAGE SECTION.
ð1 total-cost PIC 9(7)V99.

PROCEDURE DIVISION USING total-cost.


MOVE ð TO total-cost.
PERFORM VARYING sub FROM 1 BY 1
UNTIL sub > order-count
\ Call a subroutine
\ NOTE: The subroutine code is not
\ included in this example.
CALL 'InventoryGetCost'
USING order-item (sub) cost
ADD cost TO total-cost
END-PERFORM.
EXIT METHOD.
END METHOD ComputeCost.

\ Method to return the order number


IDENTIFICATION DIVISION.

234 COBOL Set for AIX Programming Guide


Method Example

METHOD-ID. 'getOrderNumber'.

DATA DIVISION.
LINKAGE SECTION.
ð1 ord-num PIC 9(5).

PROCEDURE DIVISION RETURNING ord-num.


MOVE order-number TO ord-num.
EXIT METHOD.
END METHOD 'getOrderNumber'.

\ Method to write completed order to file


IDENTIFICATION DIVISION.
METHOD-ID. WriteOrder.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT order-file ASSIGN OrdrFile.

DATA DIVISION.
FILE SECTION.
\ Methods support only EXTERNAL files
FD order-file EXTERNAL.
ð1 order-record PIC X(8ð).
\ Use LOCAL-STORAGE for items that should be allocated
\ and initialized for each invocation of the method
LOCAL-STORAGE SECTION.
ð1 print-line.
ð2 print-order-number PIC 9(5).
ð2 print-order-date PIC X(8).
ð2 print-order-count PIC 99.
ð2 print-order-table.
ð3 print-order-entry OCCURS 1ð TIMES.
ð4 print-order-item PIC X(5).

PROCEDURE DIVISION.
OPEN OUTPUT order-file.
MOVE order-number TO print-order-number.
MOVE order-date TO print-order-date.
MOVE order-table TO print-order-table.
MOVE order-count TO print-order-count.
WRITE order-record FROM print-line.
CLOSE order-file.
EXIT METHOD.
END METHOD WriteOrder.

END CLASS Orders.

The class and method definitions for the user interface class:

Chapter 13. Writing Object-Oriented Programs 235


Method Example

IDENTIFICATION DIVISION.
CLASS-ID. UserInterface INHERITS SOMObject.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in class definition
REPOSITORY.
CLASS SOMObject IS 'SOMObject'
CLASS UserInterface IS 'UserInterface'.

DATA DIVISION.
\ Define instance data
WORKING-STORAGE SECTION.
ð1 uif-action PIC X(1ð).
88 uif-add VALUE 'AddItem'.
88 uif-delete VALUE 'DeleteItem'.
88 uif-quit VALUE 'Quit'.
ð1 uif-item PIC X(5).

PROCEDURE DIVISION.

\ Method to get input from customer - action and item


IDENTIFICATION DIVISION.
METHOD-ID. ReadUserInput.

DATA DIVISION.
LINKAGE SECTION.
ð1 action PIC X(1ð).
ð1 item PIC X(5).

PROCEDURE DIVISION USING item action.


DISPLAY 'Enter the action: add, delete, quit'.
ACCEPT action FROM SYSIN.
MOVE FUNCTION UPPER-CASE (action) TO action.
EVALUATE TRUE
WHEN action = 'ADD'
SET uif-add TO TRUE
PERFORM Get-Item
WHEN action = 'DELETE'
SET uif-delete TO TRUE
PERFORM Get-Item
WHEN action = 'QUIT'
SET uif-quit TO TRUE
END-EVALUATE.
MOVE uif-action TO action.
EXIT METHOD.

Get-Item.
DISPLAY 'Enter the item'.
ACCEPT item FROM SYSIN.
MOVE item TO uif-item.

236 COBOL Set for AIX Programming Guide


Writing a Client Defintion

END METHOD ReadUserInput.

\ Method to inform customer how action was completed


IDENTIFICATION DIVISION.
METHOD-ID. WriteUserMessage.

DATA DIVISION.
LINKAGE SECTION.
ð1 flag PIC 9.

PROCEDURE DIVISION USING flag.


IF flag = ð
DISPLAY uif-action
' successfully completed on '
uif-item
ELSE
DISPLAY uif-action
' unsuccessfully completed on '
uif-item
END-IF.
EXIT METHOD.

END METHOD WriteUserMessage.

\ Method to display final order information


IDENTIFICATION DIVISION.
METHOD-ID. WriteUserOutput.

DATA DIVISION.
LOCAL-STORAGE SECTION.
77 formated-cost PIC $Z,ZZZ,ZZ9.99.
LINKAGE SECTION.
ð1 total-cost PIC 9(7)V99.
ð1 order-number PIC 9(5).

PROCEDURE DIVISION USING total-cost order-number.


MOVE total-cost TO formated-cost.
DISPLAY 'Your order costs ' formated-cost.
DISPLAY 'Your order number is ' order-number.
EXIT METHOD.

END METHOD WriteUserOutput.

END CLASS UserInterface.

Writing a Client Definition


Any program that requests services from methods in a class is a client program. The
client program consists of the usual four divisions:
Ÿ IDENTIFICATION DIVISION
Ÿ ENVIRONMENT DIVISION

Chapter 13. Writing Object-Oriented Programs 237


Client DATA DIVISION

Ÿ DATA DIVISION
Ÿ PROCEDURE DIVISION
Method Services: A method may request services from another method. Therefore,
a method can be a client and use the statements discussed in this section.

Client IDENTIFICATION DIVISION: Required


The client IDENTIFICATION DIVISION is coded as usual.

Client ENVIRONMENT DIVISION: Required


In the ENVIRONMENT DIVISION of a client, you describe the particular computer environ-
ment in which you are working and relate your class names to external System Object
Model (SOM) names. For example:
Environment Division. Required
Configuration Section. Required
Repository. Required
Client UserInterface is 'UserInterface'
Client Orders is 'Orders'.

REPOSITORY Paragraph
The REPOSITORY paragraph declares to the compiler that the specified user-defined
word is a class name and optionally relates the class name to an external class name
in the SOM interface repository. You must specify any class name you explicitly refer-
ence in your program in the REPOSITORY paragraph. In the example above, Orders
and UserInterface are the only two classes this program references.

Client DATA DIVISION: Optional


In the DATA DIVISION of a client, you describe the data the client needs. Since the
client is using classes, it needs one or more special data items called object references.
Object references are handles to instances of classes the program creates. All
requests to a method are handled through an object reference to the instance of the
class that defined the method. For example:
Data Division.
Working-Storage Section.
ð1 orderObj Usage Object Reference Orders.
ð1 userObj Usage Object Reference UserInterface.
ð1 univObj Usage Object Reference.
The phrase USAGE OBJECT REFERENCE indicates a data item is used as a handle for
an instance.

In the above example, three object references are defined. The first two, orderObj and
userObj are typed object references because a class name appears after the OBJECT
REFERENCE phrase. Thus, orderObj can only be used to reference instances of the
Orders class, or one of its subclasses. Likewise, userObj can only be used to refer-
ence instances of the UserInterface class, or one of its subclasses. The other object
reference, univObj, does not have a class name after its OBJECT REFERENCE phrase.
It is a universal object reference and can reference instances of any class.

238 COBOL Set for AIX Programming Guide


Client PROCEDURE DIVISION

Remember: Class names used on the OBJECT REFERENCE phrase must be defined in
the REPOSITORY paragraph of the CONFIGURATION SECTION.

Client PROCEDURE DIVISION: Optional


The client PROCEDURE DIVISION contains code to create and free instances of classes,
manipulate object reference data items, and invoke methods.

Creating and Freeing Instances of Classes


Before anything can be done with methods in a class, an instance of the class must be
created. SOM provides a method, 'somNew', to create an instance of a class. For
example:
Invoke Orders 'somNew' Returning orderObj.
creates an instance of the Orders class and assigns its handle to the object reference
orderObj.

When 'somNew' executes it automatically invokes 'somInit', another SOM method, that
you can override to initialize your instance data.
Remember: The class name, in this case Orders, must be defined in the REPOSITORY
paragraph of the CONFIGURATION SECTION. And the object reference, in this case
orderObj, must be defined as USAGE OBJECT REFERENCE in the DATA DIVISION.

When you finish with an instance of a class, you should free it. Again, SOM provides a
method, 'somFree', to free the instance. For example:
Invoke orderObj 'somFree'.
frees the instance of orderObj; orderObj now has an undefined value. When 'somFree'
executes it automatically invokes 'somUninit', another SOM method that you can over-
ride to save or display your instance data.

Manipulating Object References


Object references can be compared in conditional statements. For example:
If orderObj = Null ...
If orderObj = Nulls ...
If orderObj = univObj ...
are all valid uses of object references in an IF statement. The first and second IF state-
ments check whether orderObj is a null object reference (refers to no instance). The
third IF statement checks whether orderObj and univObj refer to the same instance.
Note: In a method there is a fourth form of object reference conditional:
If orderObj = Self ...
This checks whether the instance on which the method was invoked, SELF,
refers to the same instance as orderObj.

It may be necessary to make an object reference null or make one object reference
refer to the same instance as another object reference. The SET statement takes care
of these situations:

Chapter 13. Writing Object-Oriented Programs 239


Client PROCEDURE DIVISION

Set orderObj To Null.


Set univObj To orderObj.
In the first SET statement, orderObj is set to NULL.

In the second SET statement, univObj is made to refer to the instance to which
orderObj refers. In this syntax, if the receiver (univObj) is a universal object reference
then the sender (orderObj) can be either a universal or typed object reference.
However, if the receiver is a typed object reference the sender must also be a typed
object reference and typed to the same class or a subclass.
Note: In a method there is a third form of SET object reference:
Set orderObj To Self.
This makes the receiver (orderObj) refer to the same instance on which the
method was invoked, SELF.

Invoking Methods
To receive service from a method, the method must be invoked with the INVOKE state-
ment. For example:
Invoke Orders 'somNew' Returning orderObj.
Invoke orderObj 'AddItem' Using item Returning flag.

In the first INVOKE, a class name is used to create a new instance whose handle is
returned in the object reference orderObj. The class name, Orders, must be defined in
the REPOSITORY paragraph of the CONFIGURATION SECTION. The object reference,
orderObj, must be define as either an universal object reference or a typed to class
Orders object reference.

In the second INVOKE, an object reference, orderObj, is used to invoke the method
AddItem. The general syntax of this form of INVOKE is one of the following:
Invoke objref 'literal-name'.
Invoke objref identifier-name.
In both cases the invoked method must be defined in the class for which the object
reference, objref, is an instance. If the identifier-name form of the method is used, the
object reference, objref, must by an universal object reference.

Conformance between the invoked method and the object reference is checked at
compile time if the following three items are all true:
1. objref is a typed object reference.
2. The literal form of the method name is used in the INVOKE statement.
3. The TYPECHK compile option is specified.
Otherwise, conformance requirements are checked at run time. Run-time checking,
however, is not as thorough as compile-time checking.

INVOKE has the optional scope terminator END-INVOKE. The USING and RETURNING
phrases on the INVOKE work the same as they do on the CALL statement. Also,

240 COBOL Set for AIX Programming Guide


Client Example

INVOKE has the optional ON EXCEPTION and NOT ON EXCEPTION phrases like the CALL
statement. See IBM COBOL Language Reference for a discussion of USING,
RETURNING, ON EXCEPTION, and NOT ON EXCEPTION.

The RETURN-CODE special register is not set by an INVOKE to a method.

Complete Client Example


A possible client program for the mail-order catalog using the Order and UserInterface
classes:
IDENTIFICATION DIVISION.
PROGRAM-ID. 'PhoneOrders'.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
\ Declare the classes used in the program
REPOSITORY.
CLASS Orders IS 'Orders'
CLASS UserInterface IS 'UserInterface'.

DATA DIVISION.
WORKING-STORAGE SECTION.
\
\ Declare the object references used in the program
77 orderObj USAGE OBJECT REFERENCE Orders.
77 userObj USAGE OBJECT REFERENCE UserInterface.
\
\ Declare other data items used in the program
77 order-number PIC 9(5).
77 total-cost PIC 9(7)V99.
77 item PIC X(5).
77 action PIC X(1ð).
77 flag PIC 9.

PROCEDURE DIVISION.
\
\ Create an instance of the UserInterface class - userObj
INVOKE UserInterface 'somNew' RETURNING userObj.
\
\ Create an instance of the Orders class - orderObj
INVOKE Orders 'somNew' RETURNING orderObj.
\
\ Read customer input - action and item
INVOKE userObj 'ReadUserInput' USING item action.

\
\ Begin customer driven loop based on action
PERFORM UNTIL action = 'Quit'
\
\ Do appropriate action

Chapter 13. Writing Object-Oriented Programs 241


Writing a Subclass Definition

IF action (1:3) = 'Add'


INVOKE orderObj 'AddItem' USING item
RETURNING flag
ELSE
INVOKE orderObj 'DeleteItem' USING item
RETURNING flag
END-IF
\
\ Display result of action
INVOKE userObj 'WriteUserMessage' USING flag
\
\ Read customer input - action and item
INVOKE userObj 'ReadUserInput' USING item action
END-PERFORM.
\ End customer driven loop based on action
\

\
\ Calculate the total cost of the order
INVOKE orderObj 'ComputeCost' USING total-cost.
\
\ Determine the order number
INVOKE orderObj 'getOrderNumber'
RETURNING order-number.
\
\ Display information about the order
INVOKE userObj 'WriteUserOutput'
USING total-cost order-number.

\
\ Write the order to a file
INVOKE orderObj 'WriteOrder'.

\
\ Free the object instances - orderObj and userObj
INVOKE orderObj 'somFree'.
INVOKE userObj 'somFree'.

STOP RUN.
END PROGRAM 'PhoneOrders'.

Writing a Subclass Definition


A subclass, sometimes called a child class, is a specialization of its superclass, some-
times called a parent class. The subclass is related to its superclass by an is-a type
relationship. This means the phrase “Subclass S is a type of superclass P” makes
sense within the application.

Subclassing has several advantages:


Ÿ Reuse of code.

242 COBOL Set for AIX Programming Guide


Writing a Subclass Definition

A subclass can reuse methods already existing in another class through


inheritance.
Ÿ More specific class.
A subclass can add new methods to handle specific instances the superclass does
not handle.
Ÿ Change in action.
A subclass can override a method inherited from its superclass. Overriding can be
anything from a few minor changes in how the method works to a complete over-
haul of what the method does.

In the mail-order catalogue application, Order is a general class. One of the first things
you discover working with Order is there are two kinds of orders: new order and back
order. While both new order and back order have all the characteristics of order, back
order also has the characteristic of requiring the order be read from the file and
checking the status of the items. It might make sense to make new order and back
order subclasses of order, diagramed as follows:
┌───────────┐
│SOMObject │
├───────────┤
│1:somNew │
│2:somInit │
│3:somFree │
│4:somUninit│
│5: ... │
└────┬──────┘
┌─────────┴──────────┐
┌────────┴───────┐ ┌────────┴─────────┐
│Order │ │UserInterface │
│ (order-number) │ │ (action) │
│ (order-date) │ │ (item) │
│ (order-count) │ ├──────────────────┤
│ (order-table) │ │1:ReadUserInput │
├────────────────┤ │2:WriteUserOutput │
│1:AddItem │ │3:WriteUserMessage│
│2:DeleteItem │ └──────────────────┘
│3:CalculateCost │
│4:GetOrderNumber│
│5:WriteOrder │
└────────────┬───┘
┌──────┴─────┐
┌─────┴─────┐ ┌────┴────┐
│BackOrder │ │NewOrder │
├───────────┤ ├─────────┤
│1: │ │1: │
│2: │ │2: │
│3: │ │3: │
│4: │ │4: │
│5: │ │5: │
│6:ReadOrder│ └─────────┘
│7:CheckItem│
└───────────┘

Chapter 13. Writing Object-Oriented Programs 243


Subclass ENVIRONMENT DIVISION

A number and colon with nothing after them represent a method inherited from a super-
class.

In COBOL, a subclass inherits the methods from its superclass. A subclass may
change, or override, one or more methods inherited from its superclass using the OVER-
RIDE clause on the METHOD-ID. Also, a subclass may add new methods it needs to
perform its services.

In COBOL, instance data is private so the superclass must provide methods to allow
the subclass to access instance data. A subclass can retrieve values from or store
values in the instance data using the methods provided by the superclass. A subclass
may also introduce new instance data of its own.

Multiple inheritance, inheriting from more than one superclass, is allowed in COBOL.
Should there be a conflict in method names between two superclasses, the conflict is
resolved according to the System Object Model (SOM) rules. See SOMobjects Devel-
oper's Toolkit User's Guide for an example.

Subclass IDENTIFICATION DIVISION: Required


In the IDENTIFICATION DIVISION of a subclass, you name the subclass and provide
inheritance information for it. Optionally, you may give other identifying information.
For example:
Identification Division. Required
Class-Id. BackOrder INHERITS Order. Required

CLASS-ID Paragraph
The CLASS-ID paragraph names the subclass and indicates from what superclass or
superclasses the subclass inherits. In the example above, BackOrder is the class
name. It inherits all the methods from Order. Also, it can access Order instance data if
Order provides methods to get and set its instance data.

The name(s) of the superclass(es) must be specified in the REPOSITORY paragraph in


the ENVIRONMENT DIVISION (see “REPOSITORY Paragraph”). BackOrder may
optionally be specified in the REPOSITORY paragraph.

Subclass ENVIRONMENT DIVISION: Required


In the ENVIRONMENT DIVISION of a subclass, you relate your subclass and class names
to external System Object Model (SOM) names. For example:
Environment Division. Required
Configuration Section. Required
Repository. Required
Class BackOrder is 'BackOrder'
Class Order is 'Order'.

REPOSITORY Paragraph
The REPOSITORY paragraph relates your subclass and class names to the subclass
and class names in the SOM interface repository. You must include:

244 COBOL Set for AIX Programming Guide


Subclass Method IDENTIFICATION DIVISION

Ÿ User-written classes from which your subclass is inheriting.


Ÿ Metaclass to which your subclass belongs.
Discussed in “Writing a Metaclass Definition” on page 258.
Ÿ Any class referenced in methods introduced by the subclass.

You may optionally include the name of the subclass you are defining. If you do not
include the name of your subclass, it is treated as all upper-case regardless of how you
typed it on the CLASS-ID. In the example above, BackOrder is stored in the SOM inter-
face repository in mixed-case.

Subclass DATA DIVISION: Optional


In the DATA DIVISION of a subclass, you describe any extra instance data the subclass
needs. For example:
Data Division.
Working-Storage Section.
ð1 order-status PIC X(3).

A subclass DATA DIVISION contains only a WORKING-STORAGE SECTION.

WORKING-STORAGE SECTION
A subclass WORKING-STORAGE SECTION describes instance data that is statically allo-
cated when the instance is created and exists until the instance is freed. By default,
the data is global to all the methods introduced by the subclass. Instance data in a
COBOL subclass is private. Thus, it cannot be referenced directly by any other class
or subclass.

Subclass PROCEDURE DIVISION: Optional


The subclass PROCEDURE DIVISION contains only method definitions. A subclass defi-
nition must be properly terminated with an END CLASS statement. For example:
End Class BackOrder.
marks the end of the BackOrder subclass.

Subclass Method IDENTIFICATION DIVISION: Optional


Use the IDENTIFICATION DIVISION to name a method and to optionally give other identi-
fying information. The name of each method in a subclass must be unique. For
example:
Identification Division.
Method-ID. ReadOrder.

METHOD-ID Paragraph
Use the METHOD-ID PARAGRAPH to name the method. Other methods or programs use
this name to invoke the method.

If the subclass defines a method whose name exists in a superclass the OVERRIDE
clause must be specified on the METHOD-ID. For example :

Chapter 13. Writing Object-Oriented Programs 245


Subclass Example

Identification Division.
Method-Id. AddItem Override.
When an object reference that is a handle to the BackOrder subclass invokes AddItem,
this method is invoked rather than the method in the superclass Order.
Note: In a method, a subclass can invoke an overridden superclass method by using
the INVOKE form:
Invoke Super 'AddItem'.
This invokes the method AddItem defined in the superclass rather than the
method AddItem defined in the subclass.

In the case of multiple inheritance, a subclass may inherit several methods with
the same name from different parents. To specify precisely which method from
which parent is invoked use the following INVOKE form:
Invoke Class-A of Super 'AddItem'.
This invokes the method AddItem defined in the superclass Class-A rather than
the method AddItem defined in any other superclass or in the subclass.

Subclass Method ENVIRONMENT DIVISION: Optional


The subclass method ENVIRONMENT DIVISION is coded in the same way a class
method ENVIRONMENT DIVISION is coded. See “Method ENVIRONMENT DIVISION:
Optional” on page 229 for a discussion of the class method ENVIRONMENT DIVISION.

Subclass Method DATA DIVISION: Optional


The subclass method DATA DIVISION is coded in the same way a class method DATA
DIVISION is coded. See “Method DATA DIVISION: Optional” on page 229 for a dis-
cussion of the class method DATA DIVISION.

If the same data item is used in both the subclass DATA DIVISION and the method DATA
DIVISION, a reference in the method to the data name refers to the data item in the
method DATA DIVISION. The method DATA DIVISION takes precedence.

Subclass Method PROCEDURE DIVISION: Optional


In the PROCEDURE DIVISION of a subclass method, you code the executable state-
ments to complete the service the method is expected to provide. A subclass method
definition must be properly terminated with an END METHOD statement. See “Method
PROCEDURE DIVISION: Optional” on page 230 for information about coding a
method.

Complete Subclass with Methods Example


The new class and method definitions for the user interface class:

246 COBOL Set for AIX Programming Guide


Subclass Example

IDENTIFICATION DIVISION.
CLASS-ID. UserInterface INHERITS SOMObject.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in class definition
REPOSITORY.
CLASS SOMObject IS 'SOMObject'
CLASS UserInterface IS 'UserInterface'.

DATA DIVISION.
\ Define instance data
WORKING-STORAGE SECTION.
ð1 uif-action PIC X(1ð).
88 uif-add VALUE 'AddItem'.
88 uif-delete VALUE 'DeleteItem'.
88 uif-quit VALUE 'Quit'.
ð1 uif-item PIC X(5).
PROCEDURE DIVISION.

\ Method to read customer input - request


IDENTIFICATION DIVISION.
METHOD-ID. ReadUserRequest.

DATA DIVISION.
LINKAGE SECTION.
ð1 request PIC X(6).

PROCEDURE DIVISION USING request.


DISPLAY 'Enter the request: new, status'.
ACCEPT request FROM SYSIN.
MOVE FUNCTION UPPER-CASE (request) TO request.
EXIT METHOD.
END METHOD ReadUserRequest.

\ Method to read customer input for new request - action and item
IDENTIFICATION DIVISION.
METHOD-ID. ReadUserInput1.

DATA DIVISION.
LINKAGE SECTION.
ð1 action PIC X(1ð).
ð1 item PIC X(5).

PROCEDURE DIVISION USING item action.


DISPLAY 'Enter the action: add, delete, quit'.
ACCEPT action FROM SYSIN.
MOVE FUNCTION UPPER-CASE (action) TO action.
EVALUATE TRUE
WHEN action = 'ADD'
SET uif-add TO TRUE
PERFORM Get-Item

Chapter 13. Writing Object-Oriented Programs 247


Subclass Example

WHEN action = 'DELETE'


SET uif-delete TO TRUE
PERFORM Get-Item
WHEN action = 'QUIT'
SET uif-quit TO TRUE
END-EVALUATE.
MOVE uif-action TO action.
EXIT METHOD.

Get-Item.
DISPLAY 'Enter the item'.
ACCEPT item FROM SYSIN.
MOVE item TO uif-item.
END METHOD ReadUserInput1.

\ Method to read customer input for status request - order number


IDENTIFICATION DIVISION.
METHOD-ID. ReadUserInput2.

DATA DIVISION.
LINKAGE SECTION.
ð1 acct-numb PIC 9(5).

PROCEDURE DIVISION USING acct-numb.


DISPLAY 'Enter the account number'.
ACCEPT acct-numb FROM SYSIN.
EXIT METHOD.
END METHOD ReadUserInput2.

\ Method to inform customer how action was completed


IDENTIFICATION DIVISION.
METHOD-ID. WriteUserMessage.

DATA DIVISION.
LINKAGE SECTION.
ð1 flag PIC 9.

PROCEDURE DIVISION USING flag.


IF flag = ð
DISPLAY uif-action
' successfully completed on '
uif-item
ELSE
DISPLAY uif-action
' unsuccessfully completed on '
uif-item
END-IF.
EXIT METHOD.
END METHOD WriteUserMessage.

\ Method to display order information


IDENTIFICATION DIVISION.

248 COBOL Set for AIX Programming Guide


Subclass Example

METHOD-ID. WriteUserOutput.
DATA DIVISION.
LOCAL-STORAGE SECTION.
77 formated-cost PIC $Z,ZZZ,ZZ9.99.
LINKAGE SECTION.
ð1 total-cost PIC 9(7)V99.
ð1 order-number PIC 9(5).
PROCEDURE DIVISION USING total-cost order-number.
MOVE total-cost TO formated-cost.
DISPLAY 'Your order costs ' formated-cost.
DISPLAY 'Your order number is ' order-number.
EXIT METHOD.
END METHOD WriteUserOutput.

\ Method to display out of stock items


IDENTIFICATION DIVISION.
METHOD-ID. WriteUserStatus.

DATA DIVISION.
LOCAL-STORAGE SECTION.
77 sub PIC 99.
LINKAGE SECTION.
ð1 out-table.
ð2 out-entry OCCURS 1ð TIMES.
ð3 out-item PIC X(5).
ð1 out-count PIC 99.

PROCEDURE DIVISION USING out-table out-count.


IF out-count > ð
PERFORM VARYING sub FROM 1 BY 1
UNTIL sub > out-count
DISPLAY 'Out of stock '
out-item (sub)
END-PERFORM
END-IF.
EXIT METHOD.
END METHOD WriteUserStatus.

END CLASS UserInterface.

The new class and method definitions for the order class:
IDENTIFICATION DIVISION.
CLASS-ID. Orders INHERITS SOMObject.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in program
REPOSITORY.
CLASS SOMObject IS 'SOMObject'
CLASS Orders IS 'Orders'.

Chapter 13. Writing Object-Oriented Programs 249


Subclass Example

DATA DIVISION.
\ Define instance data
WORKING-STORAGE SECTION.
ð1 order-number PIC 9(5).
ð1 order-date PIC X(8).
ð1 order-count PIC 99.
ð1 order-table.
ð2 order-entry OCCURS 1ð TIMES.
ð3 order-item PIC X(5).
PROCEDURE DIVISION.

\ Method to intiialize instance data


\ - this overrides the default 'somInit' method
IDENTIFICATION DIVISION.
METHOD-ID. 'somInit' OVERRIDE.

PROCEDURE DIVISION.
MOVE FUNCTION CURRENT-DATE(1:8) TO order-date.
COMPUTE order-number = FUNCTION RANDOM ( 99999 ).
MOVE ð TO order-count.
INITIALIZE order-table.
EXIT METHOD.
END METHOD 'somInit'.

\ Method to set instance data read by subclass


IDENTIFICATION DIVISION.
METHOD-ID. 'setInstanceData'.

DATA DIVISION.
LINKAGE SECTION.
ð1 in-order.
ð2 in-order-number PIC 9(5).
ð2 in-order-date PIC X(8).
ð2 in-order-count PIC 99.
ð2 in-order-table.
ð3 in-order-entry OCCURS 1ð TIMES.
ð4 in-order-item PIC X(5).

PROCEDURE DIVISION USING in-order.


MOVE in-order-number TO order-number.
MOVE in-order-date TO order-date.
MOVE in-order-count TO order-count.
MOVE in-order-table TO order-table.
EXIT METHOD.
END METHOD 'setInstanceData'.

\ Method to get instance data and give it to subclass


IDENTIFICATION DIVISION.
METHOD-ID. 'getInstanceData'.

DATA DIVISION.
LINKAGE SECTION.

250 COBOL Set for AIX Programming Guide


Subclass Example

ð1 out-order.
ð2 out-order-number PIC 9(5).
ð2 out-order-date PIC X(8).
ð2 out-order-count PIC 99.
ð2 out-order-table.
ð3 out-order-entry OCCURS 1ð TIMES.
ð4 out-order-item PIC X(5).

PROCEDURE DIVISION USING out-order.


MOVE order-number TO out-order-number.
MOVE order-date TO out-order-date.
MOVE order-count TO out-order-count.
MOVE order-table TO out-order-table.
EXIT METHOD.
END METHOD 'getInstanceData'.

\ Method to add an item to an order


IDENTIFICATION DIVISION.
METHOD-ID. AddItem.
DATA DIVISION.

LOCAL-STORAGE SECTION.
77 sub PIC 99.
ð1 found-flag PIC 9 VALUE 1.
88 found VALUE ð.
LINKAGE SECTION.
ð1 in-item PIC X(5).
ð1 add-flag PIC 9.

PROCEDURE DIVISION USING in-item


RETURNING add-flag.
MOVE 1 TO add-flag.
PERFORM VARYING sub FROM 1 BY 1
UNTIL (sub > 1ð) OR (found)
IF order-item (sub) = SPACES
MOVE in-item TO order-item (sub)
ADD 1 TO order-count
MOVE ð TO add-flag
SET found TO TRUE
END-IF
END-PERFORM.
EXIT METHOD.
END METHOD AddItem.

\ Method to delete an item from an order


IDENTIFICATION DIVISION.
METHOD-ID. DeleteItem.

DATA DIVISION.
LOCAL-STORAGE SECTION.
77 sub PIC 99.
ð1 found-flag PIC 9 VALUE 1.

Chapter 13. Writing Object-Oriented Programs 251


Subclass Example

88 found VALUE ð.
LINKAGE SECTION.
ð1 out-item PIC X(5).
ð1 delete-flag PIC 9.

PROCEDURE DIVISION USING out-item


RETURNING delete-flag.
MOVE 1 TO delete-flag.
PERFORM VARYING sub FROM 1 BY 1
UNTIL (sub > 1ð) OR (found)
IF order-item (sub) = out-item
MOVE SPACES TO order-item (sub)
SUBTRACT 1 FROM order-count
MOVE ð TO delete-flag
SET found TO TRUE
END-IF
END-PERFORM.
EXIT METHOD.
END METHOD DeleteItem.

\ Method to compute the total cost of an order


IDENTIFICATION DIVISION.
METHOD-ID. ComputeCost.

DATA DIVISION.
LOCAL-STORAGE SECTION.
77 sub PIC 99.
77 cost PIC 9(5)V99.
LINKAGE SECTION.
ð1 total-cost PIC 9(7)V99.

PROCEDURE DIVISION USING total-cost.


MOVE ð TO total-cost.
PERFORM VARYING sub FROM 1 BY 1
UNTIL sub > order-count
\ Call a subroutine
\ NOTE: The subroutine code is not
\ included in this example.
CALL 'InventoryGetCost'
USING order-item (sub) cost
ADD cost TO total-cost
END-PERFORM.
EXIT METHOD.
END METHOD ComputeCost.

\ Method to return the order number


IDENTIFICATION DIVISION.
METHOD-ID. 'getOrderNumber'.

DATA DIVISION.
LINKAGE SECTION.
ð1 ord-num PIC 9(5).

252 COBOL Set for AIX Programming Guide


Subclass Example

PROCEDURE DIVISION RETURNING ord-num.


MOVE order-number TO ord-num.
EXIT METHOD.
END METHOD 'getOrderNumber'.

\ Method to write completed order to a file


IDENTIFICATION DIVISION.
METHOD-ID. WriteOrder.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT order-file ASSIGN OrdrFile.

DATA DIVISION.
FILE SECTION.
FD order-file EXTERNAL.
ð1 order-record PIC X(8ð).
LOCAL-STORAGE SECTION.
ð1 print-line.
ð2 print-order-number PIC 9(5).
ð2 print-order-date PIC X(8).
ð2 print-order-count PIC 99.
ð2 print-order-table.
ð3 print-order-entry OCCURS 1ð TIMES.
ð4 print-order-item PIC X(5).

PROCEDURE DIVISION.
OPEN OUTPUT order-file.
MOVE order-number TO print-order-number.
MOVE order-date TO print-order-date.
MOVE order-count TO print-order-count.
MOVE order-table TO print-order-table.
WRITE order-record FROM print-line.
CLOSE order-file.
EXIT METHOD.
END METHOD WriteOrder.

END CLASS Orders.

The subclass and method definitions for the new order subclass:
IDENTIFICATION DIVISION.
CLASS-ID. NewOrders INHERITS Orders.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in subclass defintion
REPOSITORY.
CLASS NewOrders IS 'NewOrders'
CLASS Orders IS 'Orders'.

Chapter 13. Writing Object-Oriented Programs 253


Subclass Example

DATA DIVISION.

PROCEDURE DIVISION.

\ All methods are inherited from superclass

END CLASS NewOrders.

The subclass and method definitions for the back order subclass:
IDENTIFICATION DIVISION.
CLASS-ID. BackOrders INHERITS Orders.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in subclass definition
REPOSITORY.
CLASS BackOrders IS 'BackOrders'
CLASS Orders IS 'Orders'.
DATA DIVISION.

PROCEDURE DIVISION.

\ Method to read back order from file


IDENTIFICATION DIVISION.
METHOD-ID. ReadOrder.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT backorder-file ASSIGN BackFile.

DATA DIVISION.
FILE SECTION.
FD backorder-file EXTERNAL.
ð1 backorder-record PIC X(8ð).
LOCAL-STORAGE SECTION.
ð1 backorder.
ð2 backorder-number PIC 9(5).
ð2 backorder-date PIC X(8).
ð2 backorder-count PIC 99.
ð2 backorder-table.
ð3 backorder-entry OCCURS 1ð TIMES.
ð4 backorder-item PIC X(5).
77 eof-flag PIC 9 VALUE 1.
88 eof VALUE ð.
LINKAGE SECTION.
ð1 order-number PIC 9(5).

PROCEDURE DIVISION USING order-number.


OPEN INPUT backorder-file.

254 COBOL Set for AIX Programming Guide


Subclass Example

PERFORM UNTIL eof


READ backorder-file INTO backorder
AT END
SET eof TO TRUE
NOT AT END
IF order-number = backorder-number
INVOKE SELF 'setInstanceData' USING backorder
END-IF
END-READ
END-PERFORM.
CLOSE backorder-file.
EXIT METHOD.
END METHOD ReadOrder.

\ Method to check whether item is still not in stock


IDENTIFICATION DIVISION.
METHOD-ID. CheckItem.

DATA DIVISION.
LOCAL-STORAGE SECTION.
ð1 backorder.
ð2 backorder-number PIC 9(5).
ð2 backorder-date PIC X(8).
ð2 backorder-count PIC 99.
ð2 backorder-table.
ð3 backorder-entry OCCURS 1ð TIMES.
ð4 backorder-item PIC X(5).
77 sub PIC 99.
77 status-flag PIC 9.
88 in-stock VALUE ð.
88 out-stock VALUE 1.
LINKAGE SECTION.
ð1 out-table.
ð2 out-entry OCCURS 1ð TIMES.
ð3 out-item PIC X(5).
ð1 out-count PIC 99.

PROCEDURE DIVISION USING out-table out-count.


INVOKE SELF 'getInstanceData' USING backorder.
MOVE ð TO out-count.
PERFORM VARYING sub FROM 1 BY 1
UNTIL sub > backorder-count
\ Call a subroutine
\ NOTE: The subroutine code is not
\ included in this example.
CALL 'InventoryGetItem'
USING backorder-item (sub) status-flag
IF out-stock
ADD 1 TO out-count
MOVE backorder-item (sub) TO out-item (out-count)
END-IF
END-PERFORM.

Chapter 13. Writing Object-Oriented Programs 255


Subclass Example

EXIT METHOD.
END METHOD CheckItem.

END CLASS BackOrders.

A possible new client program:


IDENTIFICATION DIVISION.
PROGRAM-ID. 'PhoneOrders'.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
\ Declare the classes used in the program
REPOSITORY.
CLASS NewOrders IS 'NewOrders'
CLASS BackOrders IS 'BackOrders'
CLASS UserInterface IS 'UserInterface'.

DATA DIVISION.
WORKING-STORAGE SECTION.
\
\ Declare the object references used in the program
\ Note: univObj is a universal object reference
77 univObj USAGE OBJECT REFERENCE.
77 userObj USAGE OBJECT REFERENCE UserInterface.
\
\ Declare other data items used in the program
77 order-number PIC 9(5).
77 total-cost PIC 9(7)V99.
77 out-count PIC 9(2).
77 request PIC X(6).
77 action PIC X(1ð).
77 flag PIC 9.
77 item PIC X(5).
ð1 item-table.
ð2 item-entry OCCURS 1ð TIMES.
ð3 item-element PIC X(5).

PROCEDURE DIVISION.
\
\ Create an instance of the UserInterface class - userObj
INVOKE UserInterface 'somNew' RETURNING userObj.
\
\ Read customer input - request
INVOKE userObj 'ReadUserRequest' USING request.
\
\ What is the customer's request?
IF request = 'STATUS'
PERFORM CheckBackOrder
ELSE
PERFORM CreateNewOrder

256 COBOL Set for AIX Programming Guide


Subclass Example

END-IF.
\
\ Free the instance of the UserInterface class - userObj
INVOKE userObj 'somFree'.

STOP RUN.

CreateNewOrder.
\
\ Create an instance of the NewOrders class - univObj
INVOKE NewOrders 'somNew' RETURNING univObj.
\
\ Read customer input - action and item
INVOKE userObj 'ReadUserInput1' USING item action.

\
\ Begin customer driven loop based on action
PERFORM UNTIL action = 'Quit'
\
\ Do appropriate action
IF action (1:3) = 'Add'
INVOKE univObj 'AddItem' USING item
RETURNING flag
ELSE
INVOKE univObj 'DeleteItem' USING item
RETURNING flag
END-IF
\
\ Display result of action
INVOKE userObj 'WriteUserMessage' USING OMITTED flag
\
\ Read customer input - action and item
INVOKE userObj 'ReadUserInput1' USING item action
END-PERFORM.
\ End customer driven loop based on action
\

\
\ Calculate the total cost of the order
INVOKE univObj 'ComputeCost' USING total-cost.
\
\ Determine the order number
INVOKE univObj 'getOrderNumber'
RETURNING order-number.
\
\ Display information about the order
INVOKE userObj 'WriteUserOutput'
USING total-cost order-number.

\
\ Write the order to a file
INVOKE univObj 'WriteOrder'.

Chapter 13. Writing Object-Oriented Programs 257


Writing a Metaclass Definition

\
\ Free the NewOrders instance - univObj
INVOKE univObj 'somFree'.

CheckBackOrder.
\
\ Create an instance of the BackOrders class - univObj
INVOKE BackOrders 'somNew' RETURNING univObj.
\
\ Read customer input - order number
INVOKE userObj 'ReadUserInput2' USING order-number.
\
\ Read the back-ordered information from a file
INVOKE univObj 'ReadOrder' USING order-number.
\
\ Check whether the back-ordered items are now in stock
INVOKE univObj 'CheckItem' USING item-table out-count.
\
\ Display the status of the back-ordered items
INVOKE userObj 'WriteUserStatus' USING item-table out-count.
\
\ Free the BackOrders instance - univObj
INVOKE univObj 'somFree'.

END PROGRAM 'PhoneOrders'.

Writing a Metaclass Definition


A metaclass is a special type of class whose instances are called class-objects. Class-
objects are the run-time objects that represent SOM classes. Object-oriented COBOL
applications either use the default metaclasses provided automatically by the SOM
environment, or explicit metaclass definitions may be provided for specialized purposes.

Metaclasses have their own methods and can have their own instance data. The most
common use of a metaclass is to control how an instance of a class is created. The
method in the metaclass that creates the instance of a class is a constructor method.
Metaclasses are also useful when multiple instances of a class are created and data
must be gathered from all the instances. See the SOMobjects Developer's Toolkit
User's Guide and SOMobjects Developer's Toolkit Programmer's Reference Manual
(available online) for further details on metaclasses and their uses.

In the mail-order catalogue application, BackOrder required the reading of a file to


establish its instance data. Reading the file cannot be done by somInit because an
order number is needed as a parameter. This is a good place to use a metaclass with
a constructor method to create the instance of BackOrder and read the file.

258 COBOL Set for AIX Programming Guide


Metaclass ENVIRONMENT DIVISION

Metaclass IDENTIFICATION DIVISION: Required


In the IDENTIFICATION DIVISION of a metaclass, you name the metaclass and
provide inheritance information for it. Optionally, you may give other identifying infor-
mation. For example:
Identification Division. Required
Class-Id. MetaBackOrder INHERITS SOMClass. Required

CLASS-ID Paragraph
The CLASS-ID paragraph names the metaclass and indicates from what base System
Object Model (SOM) class the metaclass inherits. In the example above,
MetaBackOrder is the class name. It inherits from the base SOM class SOMClass. All
metaclasses inherit directly or indirectly from SOMClass.

SOMClass must be specified in the REPOSITORY paragraph in the ENVIRONMENT DIVI-


SION (see “REPOSITORY Paragraph”). MetaBackOrder may optionally be specified in
the REPOSITORY paragraph.

Metaclass ENVIRONMENT DIVISION: Required


In the ENVIRONMENT DIVISION of a metaclass, you relate your metaclass names to
external SOM names. For example:
Environment Division. Required
Configuration Section. Required
Repository. Required
Class MetaBackOrder is 'MetaBackOrder'
Class SOMClass is 'SOMClass'.

REPOSITORY Paragraph
The REPOSITORY paragraph relates your metaclass and class names to the metaclass
and class names in the SOM interface repository. You must include:
Ÿ SOM base classes.
In the example above, CLASS SOMClass IS 'SOMClass' indicates what you are
calling SOMClass in your COBOL program is also called SOMClass in the SOM
repository.
Ÿ User-written classes from which your metaclass is inheriting.
Discussed in “Writing a Subclass Definition” on page 242.
Ÿ Any class referenced in methods introduced by the metaclass.

You may optionally include the name of the metaclass you are defining. If you do not
include the name of your metaclass, it is treated as all upper-case regardless of how
you typed it on the CLASS-ID. In the example above, MetaBackOrder is stored in the
SOM interface repository in mixed-case.

Chapter 13. Writing Object-Oriented Programs 259


Metaclass Method PROCEDURE DIVISION

Metaclass DATA DIVISION: Optional


In THE DATA DIVISION of a metaclass, you describe any instance data the metaclass
needs. For example:
Data Division.
Working-Storage Section.
ð1 total-orders PIC X(3).
A metaclass DATA DIVISION contains only a WORKING-STORAGE SECTION.

WORKING-STORAGE SECTION
A metaclass WORKING-STORAGE SECTION describes instance data that is statically allo-
cated when the first instance of an object in the metaclass is created and exists until
the COBOL run-unit terminates. By default, the data is global to all the methods intro-
duced by the metaclass. Instance data in a COBOL metaclass is private. Thus, it
cannot be referenced directly by any other class or metaclass.

Metaclass PROCEDURE DIVISION: Optional


The metaclass PROCEDURE DIVISION contains only method definitions. A metaclass
definition must be properly terminated with an END CLASS statement. For example:
End Class MetaBackOrder.
marks the end of the MetaBackOrder metaclass.

Metaclass Method IDENTIFICATION DIVISION: Optional


The metaclass method IDENTIFICATION DIVISION is coded in the same way a class
method IDENTIFICATION DIVISION is coded. See “Method IDENTIFICATION DIVISION:
Required” on page 228 for a discussion of the class method IDENTIFICATION DIVISION.

Metaclass Method ENVIRONMENT DIVISION: Optional


The metaclass method ENVIRONMENT DIVISION is coded in the same way a class
method ENVIRONMENT DIVISION is coded. See “Method ENVIRONMENT DIVISION:
Optional” on page 229 for a discussion of the class method ENVIRONMENT DIVISION.

Metaclass Method DATA DIVISION: Optional


The metaclass method DATA DIVISION is coded in the same way a class method DATA
DIVISION is coded. See “Method DATA DIVISION: Optional” on page 229 for a dis-
cussion of the class method DATA DIVISION.

If the same data item is used in both the metaclass DATA DIVISION and the method
DATA DIVISION, a reference in the method to the data name refers to the data item in
the method DATA DIVISION. The method DATA DIVISION takes precedence.

Metaclass Method PROCEDURE DIVISION: Optional


In the PROCEDURE DIVISION of a metaclass method, you code the executable state-
ments to complete the service the method is expected to provide. For the most part, a
metaclass method PROCEDURE DIVISION is coded in the same way a class method

260 COBOL Set for AIX Programming Guide


Changes to Client Program

PROCEDURE DIVISION is coded. See “Method PROCEDURE DIVISION: Optional” on


page 230 for a discussion of the class method PROCEDURE DIVISION.

Constructor Method
A metaclass constructor method is usually invoked with a class name so the use of the
following INVOKE form is needed in the constructor method to create an instance of the
class:
Invoke Self 'somNew' Returning anObj.
This creates an instance of the class on which the method was invoked, SELF, and
returns the handle to that instance in the object reference anObj.
Method Only: SELF can be used only in a method.

Changes to Class or Subclass Definitions


When a class or subclass uses an explicit metaclass, the name of the metaclass must
be specified with the METACLASS IS clause in the CLASS-ID paragraph. For example:
Identification Division.
Class-Id. BackOrder Inherits Order
Metaclass is MetaBackOrder.

Also, the name of the metaclass must be specified in the REPOSITORY paragraph of the
CONFIGURATION SECTION. For example:
Environment Division.
Configuration Section.
Repository.
Class MetaBackOrder Is 'MetaBackOrder'
Class BackOrder Is 'BackOrder'
Class Order Is 'Order'.

Changes to the Client Program


To use the metaclass constructor method, the client program invokes the constructor
method instead of 'somNew'. For example:
Invoke BackOrder 'CreateObject' Using order-number Returning anObj.
The method CreateObject is defined in the metaclass for BackOrder. This method
invokes somNew to create an instance, reads the data from the file using the order
number, and returns the handle to the instance in the object reference anObj. See
“Complete Metaclass with Methods Example” on page 262 for a detailed example of
using a metaclass constructor method.

Any method in a metaclass can be invoked with the class name. For example:
Invoke BackOrder 'CountOrders'.
Or, a metaclass object reference can be defined as a handle to the metaclass. For
example:
Working-Storage Section.
ð1 metaObj Usage Object Reference Metaclass BackOrder.

Chapter 13. Writing Object-Oriented Programs 261


Metaclass Example

The object reference metaObj is a handle to the metaclass for BackOrder, not a handle
to BackOrder itself.

The metaclass object reference is used as follows:


Procedure Division.
.
.
Invoke backObj 'somGetClass' Returning metaObj.
Invoke metaObj 'CountOrders'.

The first INVOKE statement invokes a SOM method somGetClass which takes an object
reference, backObj, to an instance and returns an object reference, metaObj, for the
metaclass to which backObj belongs.

The second INVOKE statement uses the object reference to the metaclass, metaObj to
invoke the method CountOrders which is defined in the metaclass. See “Complete
Metaclass with Methods Example” for a detailed example of using a metaclass method.

Complete Metaclass with Methods Example


The metaclass and method definitions for the back order subclass:
IDENTIFICATION DIVISION.
CLASS-ID. MetaBackOrders INHERITS SOMClass.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in metaclass definition
REPOSITORY.
CLASS MetaBackOrders IS 'MetaBackOrders'
CLASS BackOrders IS 'BackOrders'
CLASS SOMClass IS 'SOMClass'.

DATA DIVISION.
\ Define instance data
WORKING-STORAGE SECTION.
ð1 status-count PIC 99.
PROCEDURE DIVISION.

\ Method to initialize instance data


IDENTIFICATION DIVISION.
METHOD-ID. 'somInit' OVERRIDE.

PROCEDURE DIVISION.
MOVE ð TO status-count.
EXIT METHOD.
END METHOD 'somInit'.

\ Method to create and initialize instances of BackOrders


IDENTIFICATION DIVISION.
METHOD-ID. CreateBackOrders.

262 COBOL Set for AIX Programming Guide


Metaclass Example

DATA DIVISION.
LINKAGE SECTION.
ð1 order-number PIC 9(5).
ð1 anObj USAGE OBJECT REFERENCE.

PROCEDURE DIVISION USING order-number RETURNING anObj.


INVOKE SELF 'somNew' RETURNING anObj.
INVOKE anObj 'ReadOrder' USING order-number.
ADD 1 TO status-count.
EXIT METHOD.
END METHOD CreateBackOrders.

\ Method to return the number of back orders processed


IDENTIFICATION DIVISION.
METHOD-ID. CountBackOrders.

DATA DIVISION.
LINKAGE SECTION.
ð1 out-count PIC 9(2).

PROCEDURE DIVISION RETURNING out-count.


MOVE status-count TO out-count.
EXIT METHOD.
END METHOD CountBackOrders.

END CLASS MetaBackOrders.

The new subclass and method definitions for the back order subclass:
IDENTIFICATION DIVISION.
CLASS-ID. BackOrders INHERITS Orders
METACLASS MetaBackOrders.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\ Declare classes used in subclass definition
REPOSITORY.
CLASS MetaBackOrders IS 'MetaBackOrders'
CLASS BackOrders IS 'BackOrders'
CLASS Orders IS 'Orders'.

DATA DIVISION.

PROCEDURE DIVISION.

\ Method to read back order from file


IDENTIFICATION DIVISION.
METHOD-ID. ReadOrder.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.

Chapter 13. Writing Object-Oriented Programs 263


Metaclass Example

FILE-CONTROL.
SELECT backorder-file ASSIGN BackFile.

DATA DIVISION.
FILE SECTION.
FD backorder-file EXTERNAL.
ð1 backorder-record PIC X(8ð).
LOCAL-STORAGE SECTION.
ð1 backorder.
ð2 backorder-number PIC 9(5).
ð2 backorder-date PIC X(8).
ð2 backorder-count PIC 99.
ð2 backorder-table.
ð3 backorder-entry OCCURS 1ð TIMES.
ð4 backorder-item PIC X(5).
77 eof-flag PIC 9 VALUE 1.
88 eof VALUE ð.
LINKAGE SECTION.
ð1 order-number PIC 9(5).

PROCEDURE DIVISION USING order-number.


OPEN INPUT backorder-file.
PERFORM UNTIL eof
READ backorder-file INTO backorder
AT END
SET eof TO TRUE
NOT AT END
IF order-number = backorder-number
INVOKE SELF 'setInstanceData' USING backorder
END-IF
END-READ
END-PERFORM.
CLOSE backorder-file.
EXIT METHOD.
END METHOD ReadOrder.

\ Method to check whether item is still not in stock


IDENTIFICATION DIVISION.
METHOD-ID. CheckItem.

DATA DIVISION.
LOCAL-STORAGE SECTION.
ð1 backorder.
ð2 backorder-number PIC 9(5).
ð2 backorder-date PIC X(8).
ð2 backorder-count PIC 99.
ð2 backorder-table.
ð3 backorder-entry OCCURS 1ð TIMES.
ð4 backorder-item PIC X(5).
77 sub PIC 99 VALUE ð.
77 status-flag PIC 9.
88 in-stock VALUE ð.

264 COBOL Set for AIX Programming Guide


Metaclass Example

88 out-stock VALUE 1.
LINKAGE SECTION.
ð1 out-table.
ð2 out-entry OCCURS 1ð TIMES.
ð3 out-item PIC X(5).
ð1 out-count PIC 99.

PROCEDURE DIVISION USING out-table out-count.


INVOKE SELF 'getInstanceData' USING backorder.
MOVE ð TO out-count.
PERFORM VARYING sub FROM 1 BY 1
UNTIL sub > backorder-count
\ Call a subroutine
\ NOTE: The subroutine code is not
\ included in this example.
CALL 'InventoryGetItem'
USING backorder-item (sub) status-flag
IF out-stock
ADD 1 TO out-count
MOVE backorder-item (sub) TO out-item (out-count)
END-IF
END-PERFORM.
EXIT METHOD.
END METHOD CheckItem.

END CLASS BackOrders.

A possible new client program:


IDENTIFICATION DIVISION.
PROGRAM-ID. 'PhoneOrders'.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
\ Declare the classes used in the program
REPOSITORY.
CLASS NewOrders IS 'NewOrders'
CLASS BackOrders IS 'BackOrders'
CLASS UserInterface IS 'UserInterface'.

DATA DIVISION.
WORKING-STORAGE SECTION.
\
\ Declare the object references used in the program
77 univObj USAGE OBJECT REFERENCE.
\ Note: metaObj is an object reference to a metaclass
77 metaObj USAGE OBJECT REFERENCE METACLASS BackOrders.
77 userObj USAGE OBJECT REFERENCE UserInterface.
\
\ Declare other data items used in the program
77 order-number PIC 9(5).
77 total-cost PIC 9(7)V99.
Chapter 13. Writing Object-Oriented Programs 265
Metaclass Example

77 out-count PIC 9(2).


77 request PIC X(6).
77 action PIC X(1ð).
77 flag PIC 9.
77 item PIC X(5).
ð1 item-table.
ð2 item-entry OCCURS 1ð TIMES.
ð3 item-element PIC X(5).

PROCEDURE DIVISION.
\
\ Create an instance of the UserInterface class - userObj
INVOKE UserInterface 'somNew' RETURNING userObj.
\
\ Read customer input - request
INVOKE userObj 'ReadUserRequest' USING request.
\
\ What is the customer's request?
IF request = 'STATUS'
PERFORM CheckBackOrder
ELSE
PERFORM CreateNewOrder
END-IF.
\
\ Free the instance of the UserInterface class - userObj
INVOKE userObj 'somFree'.

STOP RUN.

CreateNewOrder.
\
\ Create an instance of the NewOrders class - univObj
INVOKE NewOrders 'somNew' RETURNING univObj.
\
\ Read customer input - action and item
INVOKE userObj 'ReadUserInput1' USING item action.

\
\ Begin customer driven loop based on action
PERFORM UNTIL action = 'Quit'
\
\ Do appropriate action
IF action (1:3) = 'Add'
INVOKE univObj 'AddItem' USING item
RETURNING flag
ELSE
INVOKE univObj 'DeleteItem' USING item
RETURNING flag
END-IF
\
\ Display result of action

266 COBOL Set for AIX Programming Guide


Metaclass Example

INVOKE userObj 'WriteUserMessage' USING OMITTED flag


\
\ Read customer input - action and item
INVOKE userObj 'ReadUserInput1' USING item action
END-PERFORM.
\ End customer driven loop based on action
\

\
\ Calculate the total cost of the order
INVOKE univObj 'ComputeCost' USING total-cost.
\
\ Determine the order number
INVOKE univObj 'getOrderNumber'
RETURNING order-number.
\
\ Display information about the order
INVOKE userObj 'WriteUserOutput'
USING total-cost order-number.

\
\ Write the order to a file
INVOKE univObj 'WriteOrder'.

\
\ Free the NewOrders instance - univObj
INVOKE univObj 'somFree'.

CheckBackOrder.
\
\ Read customer input - order number
INVOKE userObj 'ReadUserInput2' USING order-number.

\
\ Begin customer driven loop based order number
PERFORM UNTIL order-number < ð
\
\ Create an instance of the BackOrders class (univObj) and
\ read the back order from a file using a metaclass method
INVOKE BackOrders 'CreateBackOrders'
USING order-number RETURNING univObj
\
\ Check whether the back-ordered items are now in stock
INVOKE univObj 'CheckItem'
USING item-table out-count
\
\ Display the status of the back-ordered items
INVOKE userObj 'WriteUserStatus'
USING item-table out-count
\
\ Read customer input - order number
INVOKE userObj 'ReadUserInput2'

Chapter 13. Writing Object-Oriented Programs 267


Metaclass Example

USING order-number
END-PERFORM.
\ End customer driven loop based on order number
\

\
\ Get an object reference to the metaclass
\ Note: 'somGetClass' is a SOM method
INVOKE univObj 'somGetClass' RETURNING metaObj.
\
\ How many back orders were processed?
\ Note: Metaclass object reference to invoke metaclass method
INVOKE metaObj 'CountBackOrders' RETURNING out-count.
\
\ Display number of back orders processed
INVOKE userObj 'WriteUserMessage' USING out-count OMITTED.

\
\ Free the metaclass instance - metaObj
\ Note: This also frees all BackOrders instances
INVOKE metaObj 'somFree'.

END PROGRAM 'PhoneOrders'.


Others the Same: Other programs stay the same as the subclass example on page
246.

268 COBOL Set for AIX Programming Guide


SOM Interface Repository

Chapter 14. Using System Object Model (SOM)


System Object Model (SOM) is an object-oriented programming technology that allows
class implementers to describe the interface for a class in a standard language called
the Interface Definition Language (IDL). Unlike the object model found in most other
object-oriented programming languages, SOM is language-neutral. It preserves the key
object-oriented programming characteristics of encapsulation, inheritance, and
polymorphism without requiring the implementer of a SOM class and user of a SOM
class to use the same programming language.
Note: The object-oriented COBOL language support is based on OS/390 SOMobjects.
This support is not available on VM/CMS.

SOM Interface Repository


The SOM Interface Repository (IR) is a database in which the SOM Compiler optionally
creates and maintains class interface definitions. The SOM IR is used by the COBOL
compiler when compiling object-oriented COBOL programs. When compiling a class
definition or client program with the IDLGEN or the TYPECHK option, the interface infor-
mation for referenced classes must be present in the IR. (All referenced classes are
declared in the REPOSITORY paragraph of the CONFIGURATION SECTION.)

Accessing the IR
The interface repository files to be used are specified outside the COBOL program
using a SOM environment variable. The environment variable that specifies the IR is
SOMIR. This environment variable is set as follows:
export SOMIR=/mydir/mycls.ir
If you do not set the SOMIR environment variable, the IR emitter creates a file named
“som.ir” in the current directory.
export SOMIR=/som/som.ir:/dept/dept.ir:/work/work.ir
In this case, som.ir is SOM's IR that is not updated, dept.ir is a stable department IR
that is not updated, and work.ir is the working IR that is updated.
Note: You may need to update the SOMIR environment variable if you delete and
reinstall IBM COBOL Set for AIX, or install another product that updates it.

You may set SOMIR at the time you use it; however, it is easier to put the statement in
the above example into your environment file. For more information see the Interface
Repository chapter of the SOMobjects Developer's Toolkit User's Guide (available
online).

Populating the IR
The IR can be populated with interface information from COBOL classes via the fol-
lowing procedure:
1. Compile the COBOL class definition with the COBOL compiler, specifying the
IDLGEN compiler option.

 Copyright IBM Corp. 1996, 1998 269


SOM Environment Variables

2. Compile the IDL source files with the SOM compiler, using the IR emitter.

Some COBOL class definitions with complex interdependencies may have to be com-
piled in two steps. For example, there may be circular compilation order dependencies,
such as when two class definitions each contain references to the other. Such complex
configurations may be compiled with the following procedure:
1. Compile all of the COBOL class definition source files with the IDLGEN,
NOTYPECHK, and NOCOMPILE compiler options. This generates IDL files for the
class interfaces, but does not perform type checking or generate an object file.
2. Compile the IDL files with the SOM compiler, using the IR emitter. This populates
the IR with the class interface information.
3. Compile the COBOL class definitions again, with the NOIDLGEN and TYPECHK
compiler options. This final compile performs full type checking and generates
object files.

Compiling IDL Files


Compile IDL files and populate the IR using the SOM Compiler (for example, SC
command or JCL procedure) with the -usir option. For example:
sc -usir myclass.idl
The SOM Compiler, sc, is started with the file myclass.idl and -usir option, which
means update the IR. The rightmost IR file in the SOMIR list is the one updated.

SOM Environment Variables


The following environment variables specify information that is needed by the SOM
compiler, interface repository framework, and run time. For full details, see SOMobjects
Developer's Toolkit User's Guide (available online).
SMINCLUDE Specifies where to look for #include files included by the .idl file being
compiled.
export SMINCLUDE=/toolkt2ð/include:/som/include
SMTMP Specifies where to put intermediate output files. This directory should
not be the same as the ones where input and output files are located.
export SMTMP=/tmp/garbage
SMEMIT Specifies which emitters the SOM compiler runs.
For a COBOL class the most frequent emitter is the .h emitter which
produces a header file for use by a C client of the COBOL class.
export SMEMIT="h"
For example, the following series of statements
export SMEMIT="h"
sc -usir myclass.idl
directs the SOM Compiler to produce 'myclass.h', and populate the IR
from the 'myclass.idl' input specification.

270 COBOL Set for AIX Programming Guide


SOM Services

SOMIR Specifies the location of the interface repositories.


export SOMIR=/mydir/mycls.ir

As with the SOMIR environment variable, you can type these environment variables
when you need them. However, it is easier to put the above “export”" statements in
your environment file. For more information see the SOM Compiler chapter of the
SOMobjects Developer's Toolkit User's Guide (available online).

System Object Model (SOM) Services


IBM COBOL implements a subset of the ANSI Object-Oriented COBOL syntax based
on the SOM object-oriented engine. Not all essential object-oriented capabilities are
implemented in native COBOL syntax. Instead, SOM application programming inter-
faces, methods and functions are used. For example, native COBOL syntax is avail-
able for class definitions, object-reference datatype, and method invocation. However
object creation, destruction, initialization, and termination are handled by invoking SOM
methods provided by the SOMObject and SOMClass classes. Many other SOM facilities
are available to COBOL programmers either for direct use or for overriding and custom-
izing. These are described in SOMobjects Developer's Toolkit User's Guide (available
online).

SOM Methods and Functions


The following SOM methods and function are especially important to COBOL
programmers:
somNew A method in SOMClass to create a new object instance of a class.
During creation, somInit is invoked for customized initialization of the
object.
somFree A method in SOMObject to free an object instance releasing the
storage used. Prior to freeing storage, “somUninit” is invoked for cus-
tomized uninitialization.
somFree must not be invoked to destroy an active object, that is, an
object upon which a method has been invoked that has not yet
returned control to the invoker.
somInit A method in SOMObject that has no default function, but may be over-
ridden explicitly in a COBOL class definition to perform customized
initializations when an object is created.
somUninit A method in SOMObject that has no default function, but may be over-
ridden explicitly in a COBOL class definition to perform customized
uninitialization (typically the inverse of the function performed by a
customized somInit).
somGetClass A method in SOMObject that returns an object reference for the class-
object associated with the metaclass of an object.

Chapter 14. Using System Object Model (SOM) 271


SOM Services

somIsObj A function that determines whether an object-reference refers to a


valid object.
“somIsObj” returns a Boolean. While COBOL has no BOOLEAN data
type, COBOL programmers can declare the return value as PIC X and
test the value using a symbolic character or hex literal.
...
Data Division.
Working-Storage Section.
ð1 somBoolean Pic X.
88 invalid-obj Value X'ðð'.
88 valid-obj Value X'ð1'.
Procedure Division.
...
Call 'somIsObj' Using By Value anObj Returning somBoolean.
If invalid-obj
Display 'Object reference does not refer to a valid object'
End-if.
...
Function Note: When compiling a program that calls a SOM function, such as
somIsObj:
Ÿ The PGMNAME(MIXED) compiler option must be specified, because the API names
are case-sensitive. Otherwise, the compiler will translate somIsObj to SOMISOBJ,
and you will get an unresolved external reference.
Ÿ The SOM API functions use the SYSTEM linkage convention. Hence the
CALLINT(SYSTEM) compiler option or the >>CALLINT SYSTEM directive must be in
effect for the CALL statement.
Your invocations of SOM methods does not require any special considerations; the
correct linkage conventions are used automatically for method invocations.

SOM Initialization
During initialization of programs using object-oriented features, the COBOL run-time
system automatically initializes the SOM environment and creates class-objects for
classes referenced in the application. Application programmers do not have to perform
these initializations manually.

Class Initialization
The SOM architecture specifies that every SOM class exports an initialization function
<classname>NewClass. Normally COBOL programmers do not use this function directly,
but the function is available on all COBOL classes. The COBOL run-time system auto-
matically initializes all classes referenced within a COBOL program by calling their class
initialization functions prior to the execution of the first user-written COBOL statement in
the PROCEDURE DIVISION.

The class initialization function has a case-sensitive name, thus any COBOL program
that explicitly calls a class-initialization function must be compiled with
PGMNAME(LONGMIXED).

272 COBOL Set for AIX Programming Guide


SOM Services

If an external class-name is specified in the REPOSITORY paragraph for a class, then


the external class-name is used to form the initialization function name. If an external
class-name is not specified in the REPOSITORY paragraph for a class, then the class-
name declared is processed to form a CORBA-compliant external class name and this
name is used to form the class initialization function. In a CORBA-compliant external
class-name:
Ÿ The name is folded to upper case
Ÿ Hyphens in the name are translated to zero (0)
Ÿ If the first character in the name is a digit
– 1 through 9 are translated to A through I
– 0 is translated to J

For example:
Identification Division.
Class-Id. Employee inherits SOMObject.
Environment Division.
Configuration Section.
Repository.
Class SOMObject is class "SOMObject".
...
End-Class Employee.

The class initialization function names in the above cases are:


EMPLOYEENewClass
SOMObjectNewClass

and
Identification Division.
Class-Id. Employee inherits SOMObject.
Environment Division.
Configuration Section.
Repository.
Class Employee is class "Employee"
Class SOMObject is class "SOMObject".
...
End-Class Employee.

The class initialization function names in the above cases are:


EmployeeNewClass
SOMObjectNewClass

Class Interface Evolution


One of the benefits of SOM is that classes can undergo changes over time and retain
backward binary compatibility, that is, not require recompilation of programs and
classes that reference the changed class. Changes that can be made to classes
without recompilation requirements include:
1. Adding new methods.
2. Changing the size of an object by adding or deleting instance data.
3. Inserting new parent classes above a class in the inheritance hierarchy.

Chapter 14. Using System Object Model (SOM) 273


SOM Services

4. Relocating methods upward in the class hierarchy.

The SOM engine provides several alternative mechanisms for method resolution (see
SOMobjects Developer's Toolkit User's Guide (available online) for details). IBM
COBOL uses SOM name-lookup resolution to invoke methods. Thus when COBOL
methods are invoked from COBOL code, the somewhat more stringent recompilation
requirements of the SOM offset-resolution mechanism are not applicable. For example,
COBOL methods that are invoked with COBOL INVOKE statements are not subject to
the restriction in item four above. A COBOL method may be relocated anywhere in a
class hierarchy without requiring recompilation of the COBOL programs that invoke the
method.

Methods defined in COBOL classes may be invoked from other languages, such as C
code built with the SOM C emitter, that use offset-resolution. In this case, the standard
SOM requirements apply. Note that COBOL does not provide language comparable to
the SOM “release-order” mechanism, which is used to ensure methods can be added to
a class definition without requiring recompilation of code that invokes the methods using
offset-resolution. When adding methods to an existing COBOL class, it is recom-
mended that the new methods be added at the end of the PROCEDURE DIVISION of the
class definition, after all of the existing methods. This will ensure that any existing code
invoking the original methods does not require recompilation.

274 COBOL Set for AIX Programming Guide


SOM Objects

Chapter 15. Using SOM IDL-Based Class Libraries


This chapter is intended for COBOL programmers who want to use SOM IDL-based8
class libraries, either as clients of the class, or by specializing the class using sub-
classing.

The chapter assumes that you understand the System Object Model (SOM), at least
conceptually, and know where to find more detailed documentation about SOM when
you need it. It also assumes that you have access to the documentation for the partic-
ular class library that you are intending to use.

To get started, you need one of the object-enabled IBM COBOL products, together with
the executables for the class library, plus its documentation, as above.

SOM Objects—a Refresher


A SOM class library consists of executable code and interface information that defines
the operations that the library supports, including the parameters for invoking the
operations—known as the operation “signatures.”

When the library is being used at run time, the components that are present in memory
are illustrated in Figure 62.

Figure 62. Run-time Components of a SOM Class Library. The example also shows the COBOL
components that are using the library.
┌───────────┐ ┌───────────────┐
│ COBOL app ├%─────5┤ Class library │
└─────┬─────┘ └───────┬───────┘
6 6
└───┬───%──────5──┬───┘
6 6
┌──────────┴───────┬─────┴────────────┐
│ SOM Kernel ┌─────┘ C/COBOL run-time │
└──────┬─────┴────────┬──────┬────────┘
6 6 6
┌───────────────┴──────────────┴──────┴──────────────────┐
│ O p e r a t i n g S y s t e m │
└────────────────────────────────────────────────────────┘

8 There are various forms of Interface Definition Language (IDL), such as those for the Distributed Computing Environment (DCE) or
the Object Management Group's Common Object Request Broker Architecture (OMG CORBA), but in this chapter, we shall be
concerned only with IBM's System Object Model Interface Definition Language (SOM IDL). SOM IDL is consistent with CORBA but
also allows some additional data types, such as pointers, that are not included in CORBA.

 Copyright IBM Corp. 1996, 1998 275


Mapping IDL to COBOL

SOM IDL
The interface information for a SOM class library may be in various forms:
Ÿ IDL files;
Ÿ An Interface Repository (IR)—a machine-readable form of IDL, used during compi-
lation;
Ÿ A book or on-line documentation describing the interfaces in IDL, together with
operational descriptions of the methods.

IDL expresses the contract between the provider of object services, in this case the
class library, and the user of these services: the COBOL program, method or subclass.
The interface description is formally independent of the language in which either the
user of the service or the service itself is implemented. This property is known as
“language-neutrality.” The separation of the interface from the implementation also
allows flexibility in the deployment of the objects on the nodes of a network.

IDL data types have their origins in the C and C++ data model. Because many of them
do not have an exact counterpart in the COBOL language, there needs to be a trans-
lation or “mapping” between IDL and COBOL. The mapping recommended here makes
the explicit assumption that the data structures may be passed directly9 between the
COBOL and C/C++ mappings to SOM IDL.

Mapping IDL to COBOL


To use an IDL-based class library from COBOL, you must be able to map the elements
of IDL in which it is expressed into the COBOL language. Typically, you find the
description of the class library in a user's guide and reference, containing not only the
guidelines for using the class library, but also the calling sequences for the individual
methods expressed in SOM IDL. This, and the following sections, tell you how to map
these IDL definitions into COBOL:
Ÿ “IDL Identifiers” on page 277 describes how to map IDL identifiers to COBOL
names.
Ÿ “IDL Operations” on page 277 introduces IDL operations, which are described in
more detail in “Operation Example” on page 294.
Ÿ “IDL Attributes” on page 278 explains how to express IDL attributes in COBOL.
Ÿ “Common IDL Types” on page 279 covers the “normal” IDL elements that virtually
all interfaces use.

9 The standard CORBA model presumes a “stub” routine between the invoking and invoked object to do argument translation,
marshalling, and so on. Passing the structures directly yields very significant gains in efficiency, but it also means that some of the
mappings may not seem as “natural” to the COBOL programmer as they would be if the transfer were mediated by a stub routine. It
also means that you must ensure that you have the correct alignment and padding of any structures that are passed across an
interface. In general the recommended way to achieve this for IDL-based interfaces is to specify the SYNCHRONIZED clause for
COBOL mappings to any IDL structs or arrays that directly contain structs

276 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

Ÿ “Complex Types” on page 284 is provided for completeness; most interfaces do


not use these complex IDL constructs.
Ÿ “Argument and Return Value Passing Conventions” on page 287 is a discussion of
argument passing mechanisms.

IDL Identifiers
The only IDL names that must be identical in COBOL are the class (IDL interface) and
method (IDL operation) names. These may be specified exactly by using literals:
Ÿ For a class, in the REPOSITORY paragraph using the CLASS IS clause.
Ÿ For a method, by using the literal form of the method name in the METHOD-ID para-
graph. When you invoke a method, you use either the literal form of the name or a
data name initialized with the exact method name.

The other identifiers, such as parameter, constant, and exception names, are internal to
your program or class, and don't have to be identical to the IDL. However, it is a good
idea to keep the spelling of these close to that of the IDL originals to enhance the read-
ability and maintainability of your programs.

IDL Operations
IDL operations correspond with COBOL methods, and represent the services that an
IDL interface provides. To use an operation, you code an INVOKE statement with the
appropriate USING and RETURNING phrases that correspond with the parameters and
the return value of the operation. If these parameters are all simple scalar types, the
operation definition is self-contained. But if an operation uses one of the so-called
“constructed” types, you may have to look elsewhere in the documentation for the defi-
nition of the parameter type in order to specify your INVOKE statement completely.

Consider the IDL operation definition:


void addColor(in color that);

The single input argument is of type color, which is not one of the basic scalar IDL
types. Suppose that color is an IDL enum (see “enum” on page 280) with the following
definition, typically found in a different section of the library documentation:
typedef enum color{red, white, blue};

Then the COBOL code to map the operation, adding the color blue to an object, could
be written as follows:
1 color binary pic 9(9).
88 red value 1.
88 white value 2.
88 blue value 3.
...
Set blue to true
Invoke anobject 'addColor' using by value evp color

Chapter 15. Using SOM IDL-Based Class Libraries 277


Mapping IDL to COBOL

The evp argument is the environment pointer, which precedes the explicit operation
arguments. It is used for communicating back to the caller any exceptions that the
operation encounters. See “Errors and Exceptions” on page 297 for a more detailed
discussion.

IDL Attributes
An IDL attribute behaves like instance data that you can see outside the class defi-
nition (but note that there need not be any actual instance variable corresponding with
it). Attributes are modeled as a pair of operations, one to set and one to get the attri-
bute value. Attribute operations return errors by means of standard exceptions.

The mapping for attributes is best explained through an example. Consider the fol-
lowing IDL specification:
interface foo {
struct position_t {
float x, y;
};

attribute float radius;


readonly attribute position_t position;
};

This is exactly equivalent to the following illegal10 IDL specification:


interface foo {
struct position_t {
float x, y;
};

float _get_radius();
void _set_radius(in float r);
position_t _get_position();
};

The COBOL code to use these operations is straightforward:


1 radius comp-1.
1 position-t.
2 x comp-1.
2 y comp-1.
...
Invoke a-foo '_get radius' using by value evp returning radius
Invoke a-foo '_set_radius' using by value evp radius
Invoke a-foo '_get_position' using by value evp
returning position-t

10 Illegal, because IDL identifiers are not permitted to start with an underscore (_) character.

278 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

Common IDL Types


These are the IDL types that you normally encounter in SOM IDL interfaces. The
complex types are discussed in the next section.

Reference Summary
Figure 63. IDL Type to COBOL Mapping
IDL Type COBOL Equivalent
boolean display picture x [+ level-88s...]
char display picture x
double computational-2
enum binary picture 9(9) [+ level-88s...]
float computational-1
interface object reference
long computational-5 or binary picture s9(9)1
octet display picture x
pointer pointer
short computational-5 or binary picture s9(4)1
string display pic x(n+1), z'value' or variable-length alphanumeric
table2
unsigned long computational-5 or binary picture 9(9)1
unsigned short computational-5 or binary picture 9(4)1
Note:
1. USAGE COMPUTATIONAL-5 data items are available only on the OS/2 and AIX versions of IBM
COBOL. But if you map this IDL type to USAGE BINARY rather than COMP-5, you must either
know that the expected range of values is accommodated by the PICTURE clause, or use the
TRUNC(BIN) compiler option and, on the workstation or PC, ensure that the BINARY(NATIVE)
compiler option is in effect.
Also be aware that there are significant performance effects associated with the use of
COMP-5 data items or the TRUNC(BIN) compiler option (which affects every USAGE BINARY data
item in your program). So if you know that the picture accommodates the expected range of
values, USAGE BINARY may be the better choice.
2. See “string” on page 282 for details.

boolean
The SOM IDL boolean type is mapped to a one-byte alphanumeric data item, together
with suitable level-88 condition names. The condition names are recommended for
convenience, but are not essential. For example, the following IDL:
boolean that;

could be written in COBOL as:


1 that display pic x.
88 that-false value x'ðð'.
88 that-true value x'ð1' thru x'ff'.

Chapter 15. Using SOM IDL-Based Class Libraries 279


Mapping IDL to COBOL

char
The SOM IDL char type maps to a one-byte alphanumeric data item. The IDL
declaration:
char that;

could be written in COBOL as:


1 that display pic x.

double
The SOM IDL double type represents 64-bit floating-point data, and is mapped to
USAGE COMPUTATIONAL-2 in IBM COBOL. The IDL definition:
double that;

could be written in COBOL as:


1 that comp-2.

enum
The closest COBOL equivalent to a SOM IDL enum11 is an unsigned binary full-word,
together with condition name entries for each of the enumeration members. For
example, the following IDL:
enum that{red, white, blue, green};

could be written in COBOL as:


1 that binary pic 9(9).
88 that-red value 1.
88 that-white value 2.
88 that-blue value 3.
88 that-green value 4.

In the unlikely event that any enumeration member exceeds 999,999,999, decimal
picture considerations may apply—see the note in Figure 63 on page 279.

The way that you refer to a particular enum value in your PROCEDURE DIVISION depends
on whether the value is supplied to an operation, or returned by it. See “Enum Type”
on page 289 for more details.

11 Note that a SOM IDL enum is different from a C/C++ enum:

1. it is always exactly four bytes long, whereas a C/C++ enum is one, two or four bytes long, depending on the maximum enum
value and on compiler options;
2. the members are numbered sequentially starting from one, whereas a C/C++ enum starts at zero by default, or may optionally
have specific values assigned to the enumeration members.

280 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

float
The SOM IDL float type represents 32-bit floating-point data and is mapped to
COMPUTATIONAL-1 in IBM COBOL. For IDL:
float that;

you could write in COBOL:


1 that comp-1.

interface
The use of an IDL interface as an argument to, or result of, an operation denotes an
object reference to an instance of the class to which the interface has been mapped.
In simple terms, if a method has an interface type as one of its parameters, specify an
OBJECT REFERENCE to an instance of a class that supports that interface. Suppose
you have the following skeletal IDL interface:
interface that {
...
}

You would specify the corresponding class in the REPOSITORY paragraph as usual:
Repository.
class that 'that'.

Then you declare an instance of the that class:


1 a-that object reference that.

and pass it according to the rules in “Argument and Return Value Passing Conventions”
on page 287.

long
The SOM IDL long type describes 32-bit signed binary quantities, and is approximated
by USAGE BINARY data items with a PICTURE clause of S9(9) in COBOL. On the work-
station or PC, the type is exactly mapped by a USAGE COMPUTATIONAL-5 data item
with a PICTURE clause of S9(5) through S9(9). Whichever mapping you use, be aware
of the discussion in the note in Figure 63 on page 279.

For the IDL declaration:


long that;

you could write in COBOL:


1 that binary pic s9(9).

or, on the workstation or PC:


1 that comp-5 pic s9(9).

Chapter 15. Using SOM IDL-Based Class Libraries 281


Mapping IDL to COBOL

octet
The SOM IDL octet type represents an 8-bit quantity that is guaranteed to be
unchanged during transmission between different objects. It is most closely matched in
COBOL by a one-byte alphanumeric data item. Thus for IDL:
octet that;

you could write in COBOL:


1 that display pic x.

pointer
A SOM IDL pointer corresponds with a COBOL POINTER data item. The IDL
declaration:
pointer that;

would be written in COBOL as:


1 that pointer.

short
The SOM IDL short type defines 16-bit signed binary data, and is most closely
matched by COBOL data items with USAGE BINARY and a PICTURE clause of S9(4). On
the workstation or PC, the type is exactly mapped by a USAGE COMPUTATIONAL-5 data
item with a PICTURE clause of S9(1) through S9(4). Whichever mapping you use, be
aware of the discussion in the note in Figure 63 on page 279.

The SOM IDL definition:


short that;

could be written in COBOL as:


1 that binary pic s9(4).
or, on the workstation or PC:
1 that comp-5 pic s9(4).

string
The SOM IDL type string is one of the most important types, since it is widely used in
operations and interfaces. It is also one of the most difficult to match in COBOL,
because SOM IDL strings are modeled on those of C and C++. These have a null
terminator to determine the length of the string, and are passed via a typed pointer.
IBM COBOL does not support such null-terminated strings as a native data type.
However, the null-terminated literal — Z'string-value' — alleviates some of the prob-
lems and, when it can be passed BY CONTENT, is an exact match to a SOM IDL in

282 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

string.12 A null-terminated literal may also be used to set the initial VALUE of a data
item to be used as a string argument.

In general though, IDL strings are mapped to pointers to the appropriate character
string data or buffer. Except for in strings, what is actually passed in a method invoca-
tion is just the pointer. But, for this to work operationally, the pointer must be set to the
address of the underlying character string data or buffer in PICTURE X format. There
are several styles of data definition, depending on whether the parameter is an in,
inout, or out argument, or a return value. These are discussed in more detail under
“String Type” on page 290. For now, note that the declarations described below may
be used to represent both the COBOL and SOM IDL view of a variable-length string
simultaneously.

The main cases to distinguish are bounded and unbounded strings. Bounded strings
have a fixed upper limit on their size. The IDL declaration:
string<1ðð> that;
represents a SOM IDL string of no more than 100 characters in length, and may be
approximated by the following COBOL data declarations:
1 that-l-max binary pic 9(9) value 1ð1.
1 that-l binary pic 9(9).
1 that.
2 that-v pic x occurs 1 to 1ð1 depending that-l.

The “-l” suffix denotes the length of the string, the “-v” its value. Note the extra posi-
tion to allow for the null terminator, and note that the data item that, in addition to
being a valid SOM IDL string, is also variable-length in COBOL, because of the
OCCURS DEPENDING clause.

For unbounded strings, the maximum length must be inferred from ancillary information
about the interface and the semantics of its operations. Thus, for the IDL declaration:
string that;

which represents an unbounded SOM IDL string, you may, for example, know that the
strings that are passed across the interface do not in practice exceed 4095 characters.
Then the following COBOL declarations would be appropriate:
1 that-l-max binary pic 9(9) value 4ð96.
1 that-l binary pic 9(9).
1 that.
2 that-v pic x occurs 1 to 4ð96 depending that-l.

See “Helper Routines Source Code” on page 308 for the C source code for a pair of
“helper” routines to synchronize the two representations, for example, either the
bounded or unbounded that, above:
Ÿ 'IDLStringToCOBOL' using that that-l

12 See the note in Figure 65 on page 288 about some restrictions on the use of BY CONTENT.

Chapter 15. Using SOM IDL-Based Class Libraries 283


Mapping IDL to COBOL

This routine sets the COBOL OCCURS subject that-l from the position of the man-
datory null terminator.
If you prefer, you can achieve the same result in COBOL:
Move that-l-max to that-l
Move zero to tally
Inspect that tallying tally for characters before x'ðð'
Move tally to that-l
Ÿ 'IDLStringFromCOBOL' using that that-l
This routine inserts the null terminator at the string position indicated by the
COBOL OCCURS object.
If you prefer, you can do this quite easily yourself in COBOL:
Move x'ðð' to that-v(that-l)

unsigned long and unsigned short


The unsigned forms of binary data are mapped as for SOM IDL types long and short,
above, except that the picture clause does not specify the character “S.” Thus for the
following IDL declarations:
unsigned long this;
unsigned short that;

you could write in COBOL:


1 this binary pic 9(9).
1 that binary pic 9(4).

or, on the workstation or PC:


1 this comp-5 pic 9(9).
1 that comp-5 pic 9(4).

void
When used as a return type for an operation, the IDL type void means that the opera-
tion doesn't return anything. You map this in COBOL merely by omitting the
RETURNING phrase in the corresponding INVOKE statements or PROCEDURE DIVISION
headers.

Complex Types
These are types that, although defined in SOM IDL, are rarely found as a type definition
or as an argument to or result of an operation.

Reference Summary
Figure 64 (Page 1 of 2). IDL Type to COBOL Mapping
IDL Type COBOL Equivalent
any group + COBOL type
array table

284 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

Figure 64 (Page 2 of 2). IDL Type to COBOL Mapping


IDL Type COBOL Equivalent
sequence group + variable-length table
struct group
union group + redefines

any
The IDL any type is a self-describing representation of any of the IDL types, including
another IDL any. The descriptor is mapped to COBOL as a group item, which includes
a pointer to the actual data item of the particular type. Suppose you want to map the
following IDL declaration:
any that;

In COBOL, this would be represented by the following COBOL group item:


1 that.
2 that-type pointer.
2 that-value pointer.

The that-type field is a pointer to a “TypeCode” structure whose actual representation


is opaque. SOM provides a set of functions to create and interrogate “TypeCode”s. A
simple numeric type code is insufficient to describe an IDL type, because some types
have additional information. For example, the type information for an IDL bounded
string includes the size of the upper bound.

The that-value field points to the start of the data for the item that the any represents.

array
IDL arrays map to COBOL tables—groups whose subordinate items contain the
OCCURS clause. The underlying IDL type can be any of the IDL types, including array
itself, and is mapped according to the rules in this or the preceding section.

A simple instance of the IDL array type:


long that[4][5];

is represented in COBOL as:


1 that.
2 occurs 4.
3 that-v binary pic s9(9) occurs 5.

The “-v” suffix denotes the individual element values. The un-suffixed name is used to
pass the entire array as an argument to a method; the suffixed name is used to refer to
individual elements of the array.

You must specify the SYNCHRONIZED clause on the group item if the array contains a
struct or union at any level of the array. This is to ensure that the subordinate items

Chapter 15. Using SOM IDL-Based Class Libraries 285


Mapping IDL to COBOL

are aligned on their natural boundaries, in conformance with the default alignment of
SOM IDL structures.

sequence
An IDL sequence is a one-dimensional array with a descriptor that specifies a maximum
and current size for the sequence. If the maximum size is explicitly declared, the
sequence is said to be “bounded.” Otherwise, the sequence is “unbounded,” and the
maximum size is determined at run time (in an application-specific way) and is set prior
to passing the sequence to an operation. There are no restrictions on the element type
of a sequence. In particular, it is possible to have a sequence of another sequence
type.

Let's look at a simple example, a bounded sequence of IDL type long:


sequence<long,1ð> that;

The descriptor for the maximum and current size and address of this sequence is
represented in COBOL as a group item:
1 that.
2 that-maximum binary pic 9(9).
2 that-length binary pic 9(9).
2 that-buffer pointer.

Then the element data are mapped as a variable-length table of the appropriate type, in
this case, an array of IDL longs:
1 that-t.
2 that-v binary pic s9(9) occurs 1 to 1ð
depending that-length.

struct
An IDL struct type corresponds with a COBOL group item containing the individually
mapped components of the struct as subordinate data items. Thus the following IDL
struct:
struct that {
long x;
double y;
};

could be represented in COBOL as:


1 that sync.
2 x binary pic s9(9).
2 y comp-2.

The SYNCHRONIZED clause is required so that the alignment of the subordinate items
approximates the default alignment of SOM IDL structures. In most practical cases, the
alignment would be correct either way, but specifying SYNCHRONIZED is a sensible pre-
caution.

286 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

union
A SOM IDL union has a discriminator that indicates which format variant to use. In
COBOL, this is mapped to a group item containing the discriminator, plus the union
itself represented by using the REDEFINES clause. Then, in the PROCEDURE DIVISION,
use an EVALUATE statement to determine which format is currently in effect.

An example should make all this more clear. Suppose you have the following IDL:
union that switch (long) {
case 2:char x;
case 5:long y;
default:float z;
};

The data declaration part of the COBOL mapping could be written as follows:
1 that sync.
2 that-d binary pic s9(9).
2 that-u display pic x(4).
2 that-x redefines that-u display pic x.
2 that-y redefines that-u binary pic s9(9).
2 that-z redefines that-u comp-1.

The SYNCHRONIZED clause makes sure that COBOL mimics the default SOM IDL
alignment rules. Thus, in the unlikely event that any IDL structures have “holes,”
COBOL would insert slack bytes in the record as appropriate.

Notice the extra member of the union, that-u, whose size is the maximum of the sizes
of the explicit union members. This is needed because of the COBOL restriction that a
data item being redefined must be at least as large as the item redefining it. Alterna-
tively, you could just declare the union members in order of decreasing size, although
that may lose the correspondence between the COBOL declaration and the original
IDL.

Whichever style you adopt, you can use an EVALUATE construct such as the following
to determine which of the union members is currently in effect:
Evaluate that-d
When 2
Display 'case 2:IDL-char: ' that-z
When 5
Display 'case 5:IDL-long: ' that-x
When other
Display 'default case:IDL-float: ' that-y
End-evaluate

Argument and Return Value Passing Conventions


This section describes how to write COBOL argument-passing constructs, such as BY
REFERENCE or BY VALUE, to comply with the IDL access intent specifiers.

Chapter 15. Using SOM IDL-Based Class Libraries 287


Mapping IDL to COBOL

Argument/Result Passing Summary


Figure 65. Argument/Result Passing Conventions
IDL Type in inout/out return value
any content1 reference1 type3
array content1 reference1 pointer4
boolean value reference1 type3
char value reference1 type3
double value reference1 type3
enum value reference1 type3
float value reference1 type3
long value reference1 type3
object ref value reference1 type3
octet value reference1 type3
pointer value reference1 type3
short value reference1 type3
sequence content1 reference1 type3
string content1 pointer2 pointer4
struct content1 reference1 type3
union content1 reference1 type3
unsigned long value reference1 type3
unsigned short value reference1 type3
Note:
1. For IBM COBOL for OS/390 & VM you can use BY CONTENT or BY REFERENCE only if the
argument is not the last. This is due to the System/390 linkage conventions of the high-order
bit of the last argument address being set ON to indicate the end of the argument list. This
confuses C and C++ programs that attempt to manipulate the address as a pointer. An alter-
native to BY REFERENCE (for this situation and in general) is to pass BY VALUE a pointer that
has previously been set to the address of the data item.
2. For inout and out strings, you must pass a pointer to the string data or buffer BY REFERENCE.
3. The term “type” means the COBOL equivalent of the IDL type, specified directly in the
RETURNING phrase of the INVOKE statement.

4. The term “pointer” means a COBOL POINTER that has been set to the address of the equiv-
alent data item or output buffer.

IDL Access Intent Specifiers


The IDL intent specifiers, in, inout, and out, do not correspond exactly with COBOL
BY VALUE, BY CONTENT, and BY REFERENCE phrases. The IDL access intent deter-
mines only the semantics of the parameter, without necessarily implying a particular
argument passing mechanism. In COBOL, both BY VALUE and BY CONTENT have
input-only semantics but use different mechanisms, while BY REFERENCE parameters
may have either input-output or output-only semantics, depending how they are used.

288 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

Some kinds of output parameters, IDL strings for example, cannot be expressed
directly in COBOL, but must be mapped to pointers.

Literal Arguments
For return values, and for inout and out arguments, you must pass a data item. For
input arguments however, you may be able to specify a literal, passed BY VALUE:
Ÿ Integer-valued fixed-point numeric literals and the figurative constant ZERO are
formally equivalent to full-word binary data items, and thus match signed or
unsigned long IDL types.
Ÿ Floating-point literals are formally equivalent to double-word floating-point
(COMPUTATIONAL-2) data items, and thus match the IDL double type.
Ÿ Single-byte alphanumeric literals, symbolic characters, and figurative constants
(other than ZERO) match boolean, char, and octet.

or BY CONTENT:
Ÿ Null-terminated literals of the form Z'value' match the IDL string type.

Note that literal arguments are not supported for enums, because of the risk of the
source getting out of sync with the enumeration list.

Enum Type
The access intent of an enum parameter affects the way you refer to its value, not just
on the INVOKE statement, but also elsewhere in your program. Consider an operation
that expects an enum to be passed in both directions—as an input value and as the
operation result:
that changeColor(in that hue);
typedef enum that{red, white, blue};

To supply a particular color to the operation, you use the corresponding condition name
in a SET statement. For example, to pass the input value white, specify:
1 that-input binary pic 9(9).
88 that-red-input value 1.
88 that-white-input value 2.
88 that-blue-input value 3.
...
Set that-white-input to true
Invoke anObject 'changeColor' using by value evp that-input
returning that-output

Then, to inspect the returned color, use conditional statements:

Chapter 15. Using SOM IDL-Based Class Libraries 289


Mapping IDL to COBOL

1 that-output binary pic 9(9).


88 that-red-output value 1.
88 that-white-output value 2.
88 that-blue-output value 3.
...
Evaluate true
When that-red-output
Perform red-stuff
...
End-evaluate

Complex Types
For the complex types (not including string, which is discussed separately below), you
pass the level-1 group item. In the examples above, this is always the COBOL data
name that. Where the conventions expect a pointer, this is set:
Ÿ For an argument, prior to executing the INVOKE statement
Ÿ For a return value, on return from the method

The rules for passing these types are quite involved and are described in some detail in
the SOMobjects Developer's Toolkit Programming Guide. Generally, you provide the
storage for all in and inout arguments, all modes of struct and union parameters,
and, curiously enough, for out array arguments. The called method allocates some or
all of the storage for all other out arguments and return values. You are not allowed to
modify this returned storage, though you can, of course, use it otherwise, to copy it, for
example. You must free it using OMMFree when you are finished with it. See “Helper
Routines Source Code” on page 308.

If you have to supply inout arguments of any of the complex types, you would do well
to allocate the storage dynamically, using OMMAllocate, and declare the COBOL equiv-
alent type in the LINKAGE SECTION.13 See “Memory Management” on page 304 for
more information about OMMAllocate and OMMFree.

String Type
The examples in this section all presume the SOM IDL declaration:
string<1ðð> that;

You pass in string types in several ways. Where the content is known, you could
specify it as a null-terminated literal, either directly or as the value of a data item:

13 This is because later versions of CORBA allow the called routine to re-allocate inout arguments when the output value is incon-
sistent with the type or size of the input data item. For this to work, a standard memory management protocol must be used by both
the caller and the called routine.

290 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

1 that pic x(1ð1) value z'initial value'.


...
Invoke anObject 'method'
using by value evp by content z'this or that'
...
Invoke anObject 'method' using by value evp by content that

For variable-content strings, you may find it convenient to use a plain (PICTURE X)
alphanumeric data declaration for the string buffer. You can use reference modification
if you want to see the valid part of the string:
1 that-l binary pic 9(9).
1 that pic x(1ð1).
...
Display 'Content of "that" = "' that(1:that-l) '"'
However, if you want the string to behave naturally as a variable-length string in both
COBOL and the SOM IDL-based library, use the dual representations:
1 that-l binary pic 9(9).
1 that.
2 that-v pic x occurs 1 to 1ð1 depending that-l.

You can synchronize either the reference modified or the OCCURS DEPENDING form of
the COBOL string representation with the IDL representation by using the
IDLStringToCOBOL and IDLStringFromCOBOL helper routines given in “Helper Routines
Source Code” on page 308.

For inout and out strings, you must pass the string buffer with an extra level of indi-
rection. The way that you express the extra level of indirection in COBOL is to pass a
pointer, which for inout strings has previously been set to the address of the string
data. As usual, you have a choice of passing this pointer BY REFERENCE, or declaring
a second pointer that you have set to the address of the first, then passing this second
pointer BY VALUE:
1 ptr1 pointer.
1 ptr2 pointer.
1 that-l binary pic 9(9).
...
Linkage section.
1 that.
2 that-v pic x occurs 1 to 1ð1 depending that-l.
...
Set ptr1 to address of that
Invoke anObject 'method' using by value evp by reference ptr1 ...
...
Set ptr2 to address of ptr1
Invoke anObject 'method' using by value evp ptr2

It's clear why the extra level of indirection is needed for out strings, given that they are
allocated by the method and may be arbitrarily long. But the output size of an inout

Chapter 15. Using SOM IDL-Based Class Libraries 291


Mapping IDL to COBOL

string is limited by the input size: the upper bound for a bounded string, and the actual
input size for an unbounded string.14

For a return value, specify a pointer, which the method sets to the address of the
output string before it returns.

For all the output modes of string, including inout, declare the string buffer itself in the
LINKAGE SECTION, to allow the method to allocate, or re-allocate, the storage for the
string. Storage for an inout string should be acquired by calling OMMAllocate, so that
(in future) methods can re-size the string if necessary.

Be aware of your responsibilities for any storage allocated and returned by a SOM
IDL-based library method. You can look at the storage, by declaring appropriate
LINKAGE SECTION data items as usual, but do not attempt to modify it.15 If you want to
do that, make a copy of it and modify the copy. Also, note that you are responsible for
freeing the storage for the original returned string when you have finished with it, by
calling the OMMFree routine.

You can find the source code for OMMAllocate and OMMFree under “Helper Routines
Source Code” on page 308.

Given the IDL definition:


interface this {
string that (
in string in_string,
inout string inout_string,
out string out_string
);
};
and assuming an arbitrary limit of 99 characters on the string sizes, the following
COBOL fragments illustrate these various techniques. This code is written in a very
simple style, does not check for errors, and might not be complete.

14 Because of this restriction, inout strings are not very useful, but you still need to pass the pointer rather than the string itself,
because later versions of the CORBA argument conventions do allow reallocation of the string if the output is larger than the input.
15 This is because the storage may be protected, and you cannot assume that you have appropriate write privileges.

292 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

Data division.
Local-/Working-storage section.
1 inout-string-p pointer.
1 out-string-p pointer.
1 return-string-p pointer.
...
1 work-string-l binary pic 9(9).
1 inout-string-l binary pic 9(9).
1 out-string-l binary pic 9(9).
1 return-string-l binary pic 9(9).
...
1 work-string pic x(1ðð).
1 in-string pic(1ðð) value z'Nothing strange for in strings'.
1 evp pointer.
...
Linkage section.
1 inout-string.
2 inout-string-v pic x occurs 1 to 1ðð depending inout-string-l.
1 out-string.
2 out-string-v pic x occurs 1 to 1ðð depending out-string-l.
1 return-string.
2 return-string-v pic x occurs 1 to 1ðð depending return-string-l.
1 ev.
2 major binary pic 9(9).
88 no-exception value ð.
...

Chapter 15. Using SOM IDL-Based Class Libraries 293


Mapping IDL to COBOL

Procedure division.
...
\ Acquire storage for, and initialize, inout-string:
Move 1ðð to inout-string-l
Call 'OMMAllocate' using content length of inout-string
returning inout-string-p
Set address of inout-string to inout-string-p
Move z'Initial value for inout-string' to inout-string
Call 'IDLStringToCOBOL' using inout-string inout-string-l
\ Invoke method 'that' on an instance of the 'this' class:
Invoke a-this 'that' using by value evp
by reference in-string inout-string-p out-string-p
returning return-string-p
\ De-reference the returned pointers and copy one string:
Set address of inout-string to inout-string-p
Call 'IDLStringToCOBOL' using inout-string inout-string-l
Set address of out-string to out-string-p
Call 'IDLStringToCOBOL' using out-string out-string-l
Set address of return-string to return-string-p
Call 'IDLStringToCOBOL' using return-string return-string-l
Move out-string to work-string
\ Operate on copy, and free allocated storage when done:
Move function reverse(work-string) to work-string
If work-string = out-string then
Display '"' out-string '" is palindromic.'
End-if
...
Call 'OMMFree' using inout-string-p
Call 'OMMFree' using out-string-p
Call 'OMMFree' using return-string-p
...

Operation Example
This section illustrates the COBOL coding to use a very simple class library.

Let us begin by looking at the “documentation” for our class library, which provides a
bucket class. A bucket is a container that lets you add or remove objects, and that can
report the number of objects it contains. Buckets have no special initializer methods,
and can thus be created and initialized correctly just by invoking the somNew method on
the class. Normally, the documentation would define and describe each operation sep-
arately, but for this simple example, we will give the complete interface definition of a
bucket:
interface Bucket {
readonly attribute unsigned long count;
void add(in SOMObject element) raises(BucketFull);
SOMObject remove() raises(BucketEmpty);
};

The raises clause specifies the exceptions that the operation can incur.

294 COBOL Set for AIX Programming Guide


Mapping IDL to COBOL

The things that we put into our buckets have no external behavior beyond their exist-
ence. That is, they can be created and destroyed, and are identifiable by their object
references, but they have no methods or attributes.

The COBOL program in Figure 66 shows how you might use this class library. It per-
forms the following steps:
1. It creates an instance of a bucket.
2. It creates and adds some things to the bucket.
3. It prints the number of things in the bucket.
4. It removes a thing from the bucket.
5. It again prints the number of things in the bucket.

.1/ Process pgmname(longmixed)


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Client program for Bucket. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Program-id. 'TryBucket'.
Environment division.
Configuration section.
Repository.
class thing 'Thing'
class bucket 'Bucket'
class somobject 'SOMobject'.
Data division.
Working-storage section.
.2/ 1 evp pointer.
1 abucket object reference bucket.
1 athing object reference thing.
1 asomobject redefines athing object reference somobject.
1 cntnts binary pic 9(9).
Linkage section.
.3/ 1 ev.
2 major binary pic 9(9).
88 no-exception value ð.
88 any-exception value 1 thru 999999999.

Figure 66 (Part 1 of 2). Complete Mapping Example

Chapter 15. Using SOM IDL-Based Class Libraries 295


Mapping IDL to COBOL

Procedure division.
display 'Trying Bucket...'
.4/ call 'somGetGlobalEnvironment' returning evp
set address of ev to evp

.5/ invoke bucket 'somNew' returning abucket


perform 5 times
.6/ invoke thing 'somNew' returning athing
.7/ invoke abucket 'add' using by value evp athing
perform chkxcp
end-perform

.8/ invoke abucket '_get_count' using by value evp returning cntnts


perform chkxcp
display 'Our bucket now has ' cntnts ' things in it.'
.9/ invoke abucket 'remove' using by value evp returning asomobject
perform chkxcp
invoke abucket '_get_count' using by value evp returning cntnts
perform chkxcp
display 'We took one out, so now it has only ' cntnts
' things in it.'

.1ð/ invoke abucket 'somFree'


display 'Done with Bucket.'
stop run.

chkxcp.
if any-exception
display 'An exception occurred; quitting the program!'
stop run
end-if.

End program 'TryBucket'.

Figure 66 (Part 2 of 2). Complete Mapping Example

Notice that the COBOL coding in this example is very simplistic. For example, it does
not check for errors realistically, or even free all the objects that it creates. But it does
cover most of the things that you have to do to start using a class library. Refer to the
numbered keys in Figure 66 on page 295:
.1/ Regardless of what you call your program, you need to specify the
PGMNAME(LONGMIXED) compiler option to be able to call SOM APIs such as
somGetGlobalEnvironment. The option doesn't affect INVOKE statements, but it
does apply to program names in CALL statements.
.2/, .3/, and .4/ If not stated otherwise, SOM IDL class libraries use callstyle idl.
With this convention, every operation has an implicit environment pointer pre-
ceding the explicit IDL arguments for the operation. Although this argument is
implicit in the IDL, you code it explicitly on your INVOKE statements.
You must, at a minimum, define the environment pointer in the
WORKING-STORAGE or LOCAL-STORAGE SECTION. If you want to examine any
exceptions that are returned, you must also define the exception type in the
LINKAGE SECTION, and set its base address to the value returned by

296 COBOL Set for AIX Programming Guide


Other SOM Topics

somGetGlobalEnvironment. In the example, the exception type field is named


major.
.5/ The somNew method creates an instance of the bucket class, and returns an
object reference to the instance. Notice that this method does not take an envi-
ronment pointer as its first argument.
.6/ Each time through the loop, a new thing is returned in the same variable. This
is acceptable for the example, but normally, it would be very bad practice to
lose addressability to one's objects. Among other reasons, the storage they use
remains allocated and, without the object reference, cannot be freed.
.7/ For the methods that correspond to the IDL operations, the environment pointer
is included as the first argument, evp, in the argument list. It's important to
check for exceptions after invoking these methods. The ensuing PERFORM
statement shows one way of doing that.
.8/ This statement shows how attributes are mapped to get/set methods. In this
case, the attribute is readonly, so only the get method is defined.
.9/ It is a problem peculiar to container classes that they must allow arbitrary types
for the elements that they contain. Thus the return type of the remove operation
is specified as a SOMObject. We want to use the returned element with its
proper description, to assure type safety. But coding a thing as the
RETURNING value on the INVOKE statement would be a type violation. So the
returned value, asomobject, is specified as a redefinition of athing. This allows
the INVOKE statement to match the “signature” of the IDL operation. By using
the redefined variable, athing, for any subsequent operations on the object, we
can ensure that these operations are type safe.
.1ð/ This statement reminds us that all object instances that the program creates
should be freed to avoid memory leaks. However, in this example none of the
things in the bucket are freed.

Other SOM Topics


You will find it helpful to be familiar with the topics discussed in this section.

Errors and Exceptions


SOM uses two error or exception mechanisms: SOMError and CORBA-style exceptions.

SOMError is used for internal errors in the kernel classes, and is not really relevant to
the average user. Methods of the kernel classes are used to create an object (somNew
and somNewNoInit) or destroy it (somFree). The main implication of SOMError for these
methods is that you don't have to provide an environment argument when you invoke
them, and of course you don't have to check for exceptions after they return.

However you do need to know how to use the SOM exception mechanism, which is
used for most other methods. Exceptions aren't necessarily errors, but errors do use
the SOM exception mechanism.

Chapter 15. Using SOM IDL-Based Class Libraries 297


Other SOM Topics

SOM exceptions are not the same as C++ exceptions, but instead set the value of an
exception structure, which you can think of as a special kind of “return code,” accessed
via the environment variable.

There are two ways of passing the environment variable, depending on the callstyle of
the method you want to invoke, and check. For each of them, provide a global (per
thread) environment variable, as shown in Figure 67 on page 299. For callstyle oidl
methods, there's no explicit environment variable parameter. Such methods just use
the global environment variable implicitly. Callstyle idl methods, on the other hand,
use the same global environment variable, but passed explicitly, as the first argument to
the method. Again, see Figure 67 on page 299 for an example of how this is accom-
plished in COBOL.

The environment variable is opaque, except for the exception type field (major) at the
beginning of the structure. This is a four-byte C/C++ enum, origin zero, with three
values: NO_EXCEPTION, USER_EXCEPTION and SYSTEM_EXCEPTION — and is coded in
COBOL as BINARY PIC 9(9), with suitable level-88 condition names as illustrated in
Figure 67 on page 299.

Every callstyle idl operation (that is, a method whose first parameter is an environment
structure) can return one of the standard system exceptions16, even if it does not
declare any explicit exceptions with a raises expression in the operation declaration.
This means that you must check the exception type field of the environment variable
after every invocation of a method of a class defined with callstyle idl.

When one of these callstyle idl methods that you've invoked detects a condition that is
to be expressed as an exception, it uses the somSetException function to supply the
exception name and an exception structure.

Then, if you decide to handle the exception, perhaps by printing a message and contin-
uing, you must reset the environment variable and free the associated exception struc-
ture by using the somExceptionFree function. Of course, there are other ways of
handling exceptions. You may want to change the state of one of the input arguments
to the method, then re-try it, or you might prefer to terminate your program rather than
attempting to continue.

But in every case, at a minimum, check the successful completion of each method. It's
not good programming practice to assume that a method completed successfully
without checking it. You will not get a reliable implementation of your application unless
you do so.

COBOL Example
The program fragments in Figure 67 on page 299 show in some detail how you can
accomplish the foregoing in IBM COBOL. The data names are not mandatory; only
suggestions.

16 See the SOMobjects Developer's Toolkit Programming Guide for a list of the CORBA standard exceptions.

298 COBOL Set for AIX Programming Guide


Other SOM Topics

In the WORKING-STORAGE or LOCAL-STORAGE SECTION:


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Declare the environment variable pointer: \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
1 evp pointer.

In the LINKAGE SECTION:


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Declare the environment variable itself: \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
1 ev.
2 major binary pic 9(9).
88 no-exception value ð.
88 any-exception value 1 thru 999999999.
88 user-exception value 1.
88 system-exception value 2.

In the PROCEDURE DIVISION:


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Acquire a global environment variable \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Call 'somGetGlobalEnvironment' returning evp
Set address of ev to evp
...
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Check environment after invoking a method \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Invoke anObject 'op1' using by value evp other-args ...
If any-exception then
\ respond to exception appropriately, perhaps by using:
Call 'Print-ev' using evp by content z'op1 on anObject'
End-if
...

Figure 67 (Part 1 of 3). Checking SOM Exceptions in COBOL

Chapter 15. Using SOM IDL-Based Class Libraries 299


Other SOM Topics

Here's a sample subroutine for printing out exceptions:


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Subroutine for printing exceptions \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Program-id.
'Print-ev'.
Data division.
Working-storage section.
1 counter binary pic 9(9) value ð.
Local-storage section.
1 d pic x(13ð).
1 eip pointer.
1 i binary pic 9(9).
1 p binary pic 9(9).
1 s pic 9(9).
Linkage section.
1 evp pointer.
1 kind pic x(4ð).
1 ev global.
2 major binary pic 9(9).
88 user-exception value 1.
88 system-exception value 2.
1 ei pic x(1ðð).

Procedure division using evp kind.


Add 1 to counter
Set address of ev to evp
Call 'SLZ' using counter s i
Move 1 to p
String 'Check #' s(i : ) ': method invocation "'
delimited size into d pointer p
Move ð to i
Inspect kind tallying i for characters before initial x'ðð'
String kind(1 : i) '" returned '
delimited size into d pointer p
Evaluate true
When user-exception
String 'a user' delimited size into d pointer p
When system-exception
String 'a system' delimited size into d pointer p
When other
String 'an unknown' delimited size into d pointer p
End-evaluate

Figure 67 (Part 2 of 3). Checking SOM Exceptions in COBOL

300 COBOL Set for AIX Programming Guide


Other SOM Topics

Call 'SLZ' using major s i


String ' exception (major = ' s(i : ) ')'
delimited size into d pointer p
Display d(1 : p - 1)
Call 'somExceptionId' using by value evp returning eip
Set address of ei to eip
Move ð to i
Inspect ei tallying i for characters before initial x'ðð'
Display ' Exception ID: <' ei(1 : i) '>'
Call 'somExceptionFree' using by value evp
Goback
.
End program 'Print-ev'.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Subroutine to strip leading zeroes \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Program-id.
'SLZ'.
Data division.
Linkage section.
1 uint binary pic 9(9).
1 str pic x(9).
1 pos binary pic 9(9).
Procedure division using uint str pos.
Move uint to str
Move ð to pos
Inspect str(1 : length str - 1)
tallying pos for leading 'ð'
Add 1 to pos
Goback
.
End program 'SLZ'.

Figure 67 (Part 3 of 3). Checking SOM Exceptions in COBOL

Initializers
IBM COBOL directly supports the existing somInit and somUninit protocols. For
classes that use somInit, and this includes all pure COBOL classes, you can use the
somNew method to create and initialize an object instance in one step. This is an appro-
priate technique when all instances have the same initial value, or do not have an
explicit initial value at all. If, on the other hand, you want to parameterize object initial-
ization, so that each object instance has a unique initial value, you may prefer the con-
venience of a metaclass; see the discussion of metaclasses later in this section.

You can execute the non-default initializer methods (as a client) of a class by using the
documented technique of first invoking somNewNoInit, then invoking the appropriate
initializer method explicitly. This is the recommended way of creating an instance of
one of the SOM-enabled collections, for example.

Chapter 15. Using SOM IDL-Based Class Libraries 301


Other SOM Topics

You do need to know how to specify the so-called somInitCtrl structure that is used to
control the progress of the initializer as it traverses the class hierarchy. For a client of
a class initializer method (as opposed to a sub-class that provides its own initializer
methods), this structure is initially null, represented in COBOL as an OMITTED argu-
ment. Suppose that the IDL for the initialization method is:
void ISHeap_withNumber(inout somInitCtrl ctrl, in long number);
then COBOL code for invoking this initializer might be:
1 a-heap object reference isheap.
...
Invoke isheap 'somNewNoInit' returning a-heap
Invoke a-heap 'ISHeap_withNumber'
using by value evp by reference omitted by value 1ðððð

For COBOL subclasses of classes that use explicit initializers, the recommended tech-
nique is to use metaclass methods to instantiate and initialize the COBOL object. After
creating the instance, the metaclass method invokes the initializer for each parent (and
with multiple inheritance, there may be several), then initializes any instance data intro-
duced by the subclass itself. There is nothing to prevent you from doing this directly in
the client code; but where it is possible to encapsulate the logic in a metaclass method,
it is both more reliable and more convenient to do so, especially when the subclass
inherits from multiple parents.

Using a metaclass method is also a good way of creating and initializing your own pure
COBOL objects in a single step, particularly where each object may have a unique
initial value.

If You Need to Look at the IDL File


Generally, the documentation for a class library has all the information you need to use
(as a client) or specialize (subclass) the classes. In particular, you would expect to find
the interfaces (types and operations or methods) expressed in IDL, together with the
semantics of the operations and descriptions of the protocols for using the library. The
operation definitions would include the required data types and argument passing con-
ventions. The class library protocols are the rules for using the library: which objects
must be instantiated, and in what order; what methods must be invoked to initialize the
classes; what the relation between the classes is; and so on.

Sometimes, however, you may need more detailed information about a class library, for
example when you are specializing the library by subclasssing. To get this additional
information, you may need to look at the IDL or header files. It is then helpful to know
their structure: what is relevant and what you can ignore. Consider the sample IDL file
spred from the collection class library, shown in Figure 68 on page 303.

302 COBOL Set for AIX Programming Guide


Other SOM Topics

#ifndef _ISPRED_IDL .1/


#define _ISPRED_IDL

#include <somobj.idl> .2/

interface ISPredicate : SOMObject { .3/

boolean evaluateFor (in SOMObject element); .4/

#ifdef __SOMIDL__ .5/


implementation {
releaseorder: evaluateFor;

somDefaultInit: override,init;
somDestruct: override;

callstyle = idl;
majorversion = 1;
minorversion = ð;
filestem = spred;
dllname = "sccl.dll";
functionprefix = sISPredicate_;

#ifdef __PRIVATE__ .6/


passthru C_xh_before = "#include <ssglobal.xih>";
#endif
};
#endif
};
#endif

Figure 68. Sample Collection Class IDL File

Typically, the IDL file consists of some IDL definitions, guarded so that they are proc-
essed only once per IDL compilation, plus some implementation-specific information,
also guarded so that it is conditionally included. Refer to the numbered keys in
Figure 68:
.1/ One of three conditional sections in the file; its purpose is to ensure that the IDL
definitions in the file are processed no more than once during the IDL compila-
tion. The matching #endif statement is at the end of the file.
.2/ The #include statement incorporates another IDL file that you may have to refer
to.
.3/ The compound statement specifies the IDL element that this file defines, the
ISPredicate interface.
.4/ This definition is for the (single) new operation evaluateFor that ISPredicate
introduces.
.5/ The start of some SOM-specific implementation information, which needn't
concern you; its matching #endif is the second to last.
.6/ A directive that is needed only by the implementation itself. Again it is not rele-
vant to you, as a client of the class.

Chapter 15. Using SOM IDL-Based Class Libraries 303


Memory Management

Memory Management
It is important to avoid memory leaks. This is particularly true with objects, because
there are typically so many individual object instances created and destroyed. The idea
is to ensure that, when an object is destroyed or assigned, all of its associated storage
is also freed. “Helper Routines Source Code” on page 308 contains the source code
for a pair of C routines that you can use to allocate and free dynamic storage for data
that is pointed to by an object, for an inout argument to a method, and so on:
Ÿ 'OMMAllocate' using storage-size returning a-pointer, to allocate storage,
where storage-size is the 4-byte unsigned binary number of bytes to allocate;
Ÿ 'OMMFree' using a-pointer, to free the previously allocated storage element that
a-pointer addresses.

You must use OMMFree to free output storage allocated and returned to you by SOM
class libraries. See “Complex Types” on page 290 and “String Type” on page 290 for
details of how and when to do this.

You can also use these routines to manage dynamic storage (as opposed to instance
data) for your own classes. Let's look at an example of a variable-length string class,
where the string data is not an explicit part of the instance, but is instead a separate
storage area that the instance refers to.

Here's the COBOL definition for the class:

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ COBOL variable-length string class definition. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Class-id.
varstring inherits somobject.
Environment division.
Configuration section.
Repository.
Class varstring 'VarString'
Class somobject 'SOMObject'
.

Figure 69 (Part 1 of 4). COBOL Variable-Length String Class Example

304 COBOL Set for AIX Programming Guide


Memory Management

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Variable-length string class instance data. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Data division.
Working-storage section.
1 vstlen binary pic 9(9).
1 vstptr pointer.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Variable-length string class method: default initialization; \
\ set the instance to a predictable state. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Method-id.
'somInit' override.
Procedure division.
.1/ Set vstptr to null
Move ð to vstlen
Goback
.
End method 'somInit'.

Figure 69 (Part 2 of 4). COBOL Variable-Length String Class Example

Chapter 15. Using SOM IDL-Based Class Libraries 305


Memory Management

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Variable-length string class method: assignment from a literal\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Method-id.
'SetVarstring'.
Data division.
Local-storage section.
1 strsze pic 9(9) binary.
Linkage section.
1 valptr pointer.
1 setval pic x(1ðð).
1 vstval pic x(1ðð).
Procedure division using by value valptr.
.2/ If vstptr not = null then
Call 'OMMFree' using vstptr
End-if
Move ð to vstlen
Set address of setval to valptr
Inspect setval tallying vstlen
for characters before initial x'ðð'
Add 1 to vstlen giving strsze
Call 'OMMAllocate' using strsze returning vstptr
Set address of vstval to vstptr
Move setval(1:strsze) to vstval(1:strsze)
Goback
.
End method 'SetVarstring'.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Variable-length string class method: return string (pointer). \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Method-id.
'GetVarstring'.
Data division.
Linkage section.
1 valptr pointer.
Procedure division returning valptr.
Set valptr to vstptr
Goback
.
End method 'GetVarstring'.

Figure 69 (Part 3 of 4). COBOL Variable-Length String Class Example

306 COBOL Set for AIX Programming Guide


Memory Management

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Variable-length string class method: assign from another string\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Method-id.
'AssignVarstring'.
Data division.
Local-storage section.
1 strsze binary pic 9(9).
1 valptr pointer.
Linkage section.
1 str object reference varstring.
Procedure division using by value str.
.3/ If self not = str then
Invoke str 'GetVarstring' returning valptr
Invoke self 'SetVarstring' using by value valptr
End-if
Goback
.
End method 'AssignVarstring'.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Variable-length string class method: free associated storage. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification division.
Method-id.
'somUninit' override.
Procedure division.
.4/ If vstptr not = null then
Call 'OMMFree' using vstptr
Set vstptr to null
Move ð to vstlen
End-if
Goback
.
End method 'somUninit'.

End class varstring.

Figure 69 (Part 4 of 4). COBOL Variable-Length String Class Example

There are several points to notice about the use of storage in this example:
.1/ All VarString instances are created in a predictable initial state, with the length
set to zero, and the string pointer set to null.
.2/ Before assigning a new value to an instance, the storage allocated for any
current value is freed. If this weren't done, the storage would be “orphaned,”
causing a memory leak.
.3/ When assigning one string to another, you have to check whether the sender is
identical to the receiver before doing the assignment and thereby prematurely
freeing the sender's storage.

Chapter 15. Using SOM IDL-Based Class Libraries 307


.4/ Although somFree de-allocates the storage for the instance data, it does NOT
free storage that the instance refers to. Thus it is critical to free any such
storage when the instance is uninitialized.

Helper Routines Source Code


The C source in Figure 70 may be used to implement the helper functions for string
representation and memory management discussed in this chapter. You can either
statically link the functions into your application, or generate a shared library for the
functions and bind your application to the shared library.

/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/
/\ Helper functions for using SOM IDL-based class libraries. \/
/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\/

/\ OS/39ð pragma to generate long, mixed-case names \/


#pragma longname

/\ Macro to clear the high-order bit of the argument address (OS/39ð \/


/\ and VM) \/
#define Clean(p,q) p=(void\)((int)q&ðx7fffffff)
#include <som.h>

/\ Object Memory Management: allocate memory. \/


somToken OMMAlloc(size_t \sze){
size_t \s;
Clean(s,sze);
return SOMMalloc(\s);
}

/\ Object Memory Management: free allocated memory. \/


void OMMFree(somToken \ptr){
somToken \p;
Clean(p,ptr);
SOMFree(\p);
return;
}

/\ Set COBOL representation (ODO object) from IDL string length \/


void IDLStringToCOBOL(char \str, long \len) {
char \s;
long \l;
Clean(s,str);
Clean(l,len);
(\l)=strlen(s);
return;
}

Figure 70 (Part 1 of 2). C Source for IDL-based Library Helper Functions

308 COBOL Set for AIX Programming Guide


/\ Set IDL string length (null byte) from COBOL (ODO) representation \/
void IDLStringFromCOBOL(char \str, long \len) {
char \s;
long \l;
Clean(s,str);
Clean(l,len);
s[\l]=ð;
return;
}

Figure 70 (Part 2 of 2). C Source for IDL-based Library Helper Functions

Chapter 15. Using SOM IDL-Based Class Libraries 309


Wrapping

Chapter 16. Converting Procedure-Oriented Programs to


Object-Oriented Programs
Conventional COBOL programs belong to one of three types:
Ÿ Batch
Ÿ Online
Ÿ Subprogram

Batch programs are often constructed to access files and/or databases and produce
reports. In the access files and/or databases case, the file or database is the object of
the action; however, the program is structured around the action—delete, insert, or
update. In the produce reports case, the report can be viewed as an object; however,
the program structure reflects the structure of the report.

Online transaction processing programs are built around the transactions which they
process and these are reflected in the user interface maps or panels which make up
the transaction. Online transactions may access several files or databases from one
panel. In this case, there is a one to many relationship between the source of the
action and the targets of the action, all of which can be viewed as objects.

Subprograms normally are called to provide a function too large or complex to include
in the main program. They are also used to implement general purpose functions
required by many other programs; in which case, they embody reusable code. In many
cases, the subprogram alters the values of some parameters based on the values of
other parameters. In other cases, the subprogram accesses files/databases or prints
reports. In this case, the parameter list can be viewed as a message to trigger some
action on a file or database object.

Wrapping a Procedure-Oriented Program


Wrapping is a technique to integrate existing procedure-oriented code with new object-
oriented code. Two of the definitions for wrap are:
1. To enclose as if with a protective covering.
2. To conceal as if by enveloping.
Wrappers are objects that provide an interface between object-oriented code and
procedure-oriented code. They enclose the procedure-oriented code in a package,
concealing its true nature and making it seem like object-oriented code.

Wrappers are useful in two situations:


Ÿ Glass-top coordination
Ÿ Boundary interface coordination

310  Copyright IBM Corp. 1996, 1998


Boundary Wrappers

Glass-top Coordination
This type of wrapper integrates the old and new code at the user interface or
“glass-top” level. As user interfaces move toward a object-oriented approach, you find
direct manipulation used more. This implies actions such as “dragging” and “dropping”
objects into or onto other objects. When this occurs, the objects involved must work
together to take the appropriate action. If one of the objects is really procedure-
oriented code, the wrapper is an interface to the true objects.

For example, you have a stable set of procedural code for updating a database.
However, you would like to include the database as part of a graphical user interface.
The goal is to drop a list object representing an update to the database on the data-
base object and have the update performed. You need to write a wrapper class to
accept messages from the list object; i. e. the list object invokes methods in the
wrapper. The methods in the wrapper class interpret the information from the list object
and use the CALL statement to call the appropriate subprogram in the old procedural
code.
┌────────────────────────────┐User
├────────────────────────────┤Interface
│┌───────┐ drop ┌────────┐│
││List of├────┬────5Database││
││Updates│ │ └────────┘│
│└───────┘ │ │
└─────────────┼──────────────┘
┌──────────┘
┌──6─┐ ┌───────┐ ┌──────────┐ Code
│True│INVOKE│Wrapper│CALL│Procedural│ Level
│O-O %──────5 O-O %────5 Code │
│Code│ │ Code │ └──────────┘
└────┘ └───────┘

Boundary Interface Coordination


Boundary interface wrappers create objects for procedural code outside the boundaries
of the new object-oriented subsystem. These wrappers allow the object-oriented part of
the system to deal with the procedure-oriented part of the system as if it were object-
oriented. Thus, you can phase in new object-oriented code and continue to use your
existing procedure-oriented code.

You can write a wrapper for each subprogram in the procedural code. Or if several
subprograms are working with the same object, processing the same file or producing
the same report, you can write a single wrapper for all the related subprograms. The
appropriate method in the wrapper is invoked from a true object and the method in turn
calls the appropriate subprogram.

Chapter 16. Converting Procedure-Oriented Programs to Object-Oriented Programs 311


Converting

┌──────────┐
│O%──────5O│Object-Oriented
│& &│ Subsystem
││ ││(True Objects)
││ ││-----
│6 6│ |Boundary
│O%──────5O%─5O |Subsystem
└&────────&┘ & |(Wrappers)
|└─5O 6 └─|─────┐
| & O | │
----│-----&------ │
┌───6┐ ┌──6──────┐ ┌──6───┐
│Read│ │Calculate│ │Write │Procedural
│File│ │ Taxes │ │Report│Subsystem
└────┘ └─────────┘ └──────┘

Required Change to Procedural Code


If you decide to use wrappers, there is one change you must make to your procedural
code. Since methods are always recursive, it is possible to INVOKE method A which
CALLs program B. While program B is executing, method A could be invoked again
causing a second call to program B. This second call is considered a recursive call.
Therefore, any procedural code invoked from a method should have the RECURSIVE
clause on the PROGRAM-ID statement.

For example:
Identification Division.
Program-Id. ProgB recursive.
Environment Division.
.
.

Coexistence
The object-oriented and procedure-oriented parts of your system can exist quite well
together. Certainly, you want to reuse your existing code as long as it continues to
meet your needs. However, you can add new function to your system using object-
oriented implementations. Only if your existing code no longer meets your needs or its
maintenance cost is too high should you consider converting the entire procedure-
oriented system to an object-oriented system.

Converting a Procedure-Oriented Program


Taking as input a typical COBOL batch or online program, the goal is to produce a
formal specification of the program in object-oriented form. The conversion involves
four steps:
Ÿ Identify objects
Ÿ Analyze data flow and usage
Ÿ Reallocate code to objects
Ÿ Write the object-oriented code

312 COBOL Set for AIX Programming Guide


Step Three

Identify Objects
First, partition the DATA DIVISION into potential objects by identifying every record as an
object and every field in the record as its instance data. You can start by taking record
structures that define files and making them objects called FffffFile, where Fffff is a
name of your choosing. Record structures that define database views become objects
called VvvvvView. Map or panel record structures become objects called
UuuuuInterface. Other record structures in the WORKING-STORAGE SECTION not
related to files, databases, maps, or panels become objects called WwwwWork. Finally,
record structures in the LINKAGE SECTION become objects called PppppParameter.

Now you have a lot of potential objects, some of which are redundant. Study the
potential objects and decide if two or more are slight variations of the same object.
Maybe you have two detail lines as potential objects that differ in only one or two of
their fields. If possible use REDEFINES or some other technique to combine the two
detail lines into one and, thus, combine the two potential objects into one object.

The result of this step is an object list with the name of each object and its instance
data.

Analyze Data Flow and Usage


Analyze the file and database accesses to collect the access operations, such as
SELECT, UPDATE, INSERT, DELETE, READ, and WRITE, for each object. The purpose is
to find the relationship between objects via access sequence. For example, if one
record read from the input file results in one detail line written to a report then a
relationship exists between the file and the report objects. The relationships are tied to
the source object and the target object.

Trace the data flow between objects to identify those objects which use instance data
from another object.

If the two objects share a superclass - subclass (parent - child) relationship, then the
subclass inherits methods from the superclass and shares instance data via 'get' and
'set' methods. (The get and set methods are written in the superclass definition.)

If the two objects are separate and distinct, then they are collaborators. Collaborators
do not inherit anything from each other. Instance data that needs to be shared
between two collaborators is typically passed as parameters on an INVOKE statement.

The result of this step is an object relationship table listing all the inheritance and col-
laboration relationships between objects.

Reallocate Code to Objects


For each object you identified, collect all references to it from the PROCEDURE
DIVISION. Look for procedural code that changes the state of the object's instance
data. If an instruction affects several data items in different objects, it must be changed
or duplicated and the proper form associated with the correct object.

Chapter 16. Converting Procedure-Oriented Programs to Object-Oriented Programs 313


Step Four

For example:
Move ð To input-z output-z.
must be changed to
Move ð To input-z.
Move ð To output-z.
The first MOVE is associated with the appropriate input object and the second with the
appropriated output object.

Now couple the procedural instructions from the PROCEDURE DIVISION with the objects
to form methods. Take the code you pulled from the program and organize it into task-
oriented methods.

Refer to the object relationship table from step two and determine if any new methods
must be written to facilitate passing data between two objects. See “Writing a Method
Definition” on page 228 for information about writing methods.

The result of this step is completed method definitions.

Write the Object-Oriented Code


Write a class definition using the object list from step one and the methods from step
three. See “Writing a Class Definition” on page 224 for information about writing
classes.

Also, write the client program to create instances of the classes and invoke methods.
See “Writing a Client Definition” on page 237 for information about writing client pro-
grams.

Your client program may be a modification of your original procedure-oriented program


with invokes and manipulation of object references added where needed in the proce-
dural code. This is the case when all the procedure-oriented code was not placed into
methods. However, if all the procedure-oriented code was placed into methods, then
your client program is a new program you write from scratch.

314 COBOL Set for AIX Programming Guide


Part 4. Advanced Topics
This part of the book covers advanced programming topics. Basic programming topics
are covered in Part 1, “Coding Your Program” on page 1.

Chapter 17. Porting Applications between Platforms . . . . . . . . . . . . . 316

Chapter 18. Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323

Chapter 19. Data Sharing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336

Chapter 20. Programming for a DB2 Environment . . . . . . . . . . . . . . . 354

Chapter 21. Programming for a CICS Environment . . . . . . . . . . . . . . 358

Chapter 22. Open Database Connectivity . . . . . . . . . . . . . . . . . . . 369

Chapter 23. Building Shared Libraries . . . . . . . . . . . . . . . . . . . . . 386

Chapter 24. Preparing COBOL Programs for Multithreading . . . . . . . . . 397

Chapter 25. National Language Support Considerations . . . . . . . . . . . 407

Chapter 26. Pre-initializing the COBOL Run-Time Environment . . . . . . . 415

Chapter 27. Productivity and Tuning Techniques . . . . . . . . . . . . . . . 422

Chapter 28. The "Year 2000" Problem . . . . . . . . . . . . . . . . . . . . . 436

| Chapter 29. Using the Millennium Language Extensions . . . . . . . . . . . 446

 Copyright IBM Corp. 1996, 1998 315


Getting Mainframe Applications to Compile Under AIX

Chapter 17. Porting Applications between Platforms


Your AIX workstation has a different hardware and operating system architecture than
IBM mainframes or PCs. Because of fundamental platform differences, some problems
can arise as you move COBOL programs between the AIX workstation, PC, and
mainframe environments.

The following information describes some of the differences between development plat-
forms and provides instructions to help you minimize portability problems.

Getting Mainframe Applications to Compile under AIX


As you move programs to an AIX workstation from the mainframe, one of your first
goals is to get the applications you have already been using to compile in the new
environment without errors.

Choosing the Right Compiler Options


Some mainframe COBOL compiler options are not applicable under AIX, and are
treated as comments. For a full list of differences between host COBOL and IBM
COBOL Set for AIX (including compiler options), see Appendix A, “Summary of Differ-
ences with Host COBOL” on page 466.

Two compiler options might yield unpredictable results and are flagged by the compiler
with W-level messages:
CMPR2
This compiler option impacts the interpretation of language elements. The AIX
compiler does not support VS COBOL II Release 2 language elements that are in
conflict with the ANSI 85 COBOL standard. A program that depends on the
CMPR2 option is not portable.

NOADV
Programs that require the use of NOADV are sensitive to device control charac-
ters and almost certainly are not portable. If your program relies on NOADV,
revise it such that language specification does not assume a printer control char-
acter as the first character of the ð1 record for the file.

AIX Differences from Mainframe COBOL Language Features


The following section describes some language features that were valid under
mainframe COBOL but can create errors or unpredictable results in your AIX compila-
tion. Where possible, a solution to the potential problem is provided.

ACCEPT and DISPLAY statements


Under AIX, the targets of DISPLAY or ACCEPT statements are determined by
checking COBOL environment variables (see “Run-Time Environment Variables” on
page 130). If your mainframe program assumes the use of host DDNAMEs as the
targets of ACCEPT or DISPLAY statements, ensure that these targets are defined by
equivalent AIX environment variables set to appropriate filenames.

316  Copyright IBM Corp. 1996, 1998


Getting Mainframe Applications to Run under AIX

ASSIGN clause
There is a different syntax and mapping to the system filename based on ASSIGN-
MENT name (see the IBM COBOL Language Reference).

CALL statement
A filename as a CALL argument is not supported.

CLOSE statement
The phrases FOR REMOVAL, WITH NO REWIND, and UNIT/REEL are treated as com-
ments. Avoid their use in portable programs.

LABEL RECORD clause


LABEL RECORD IS data-name, USE...AFTER...LABEL PROCEDURE, and GO TO
MORE-LABELS are treated as errors. Programs depending on the user label proc-
essing supported through OS/390 QSAM are not portable.

POINTER and PROCEDURE-POINTER data items


Under mainframe COBOL, a POINTER data item is defined as four bytes, and a
PROCEDURE-POINTER data item is defined as eight bytes. Under AIX, the size of
these data items are consistent with the native pointer definition of the platform (for
example, four bytes for a 32-bit machine).

RERUN clause
Treated as a comment.

SHIFT-IN, SHIFT-OUT special registers


Not applicable under AIX, results in an E-level message.

SORT-CONTROL special register


Because it identifies a system filename, this register is sensitive to the filename
conventions of the platform. Be aware of the differences in naming conventions
between AIX and the mainframe.

WRITE statement
If you specify WRITE...ADVANCING with the environment names C01-C12 or S01-S05,
the ADVANCING phrase is ignored.

Using the COPY Statement to Help Port Programs


In many cases, potential portability problems can be avoided by using the COPY state-
ment to isolate platform-specific code. For example, you can include platform-specific
code in a compilation for a given platform and exclude it from compilation for a different
platform. You can also use the COPY REPLACING phrase to globally change non-
portable source code elements, such as filenames.

For information about the COPY statement, see the IBM COBOL Language Reference.

Getting Mainframe Applications to Run under AIX


Once you have downloaded your source program from the mainframe and compiled it
on the AIX workstation without errors, the next step is to run the program. In many
cases, you can get the same results from the AIX run as from the mainframe COBOL

Chapter 17. Porting Applications between Platforms 317


Getting Mainframe Applications to Run under AIX

run without serious source-language modifications. In order to assess whether or not


you should make source-language modifications to your program, you need to know
about elements and behavior of the COBOL language that vary due to the underlying
hardware or software architecture.

Data Representations Causing Run-Time Differences


COBOL stores USAGE PACKED-DECIMAL data in the same manner on both the
mainframe and on the AIX workstation, but all other computational data is, by default,
represented differently. Most programs act the same on an AIX workstation as they do
on the mainframe regardless of the data representation. To ensure that this is true for
your programs, you should try to understand the differences described in the following
sections.

ASCII vs EBCDIC
The AIX workstation uses the ASCII-based character set while the mainframe uses
the EBCDIC character set. This means that most characters have a different
hexadecimal value. For example, the hexadecimal value for a blank is X'20' in
the ASCII character set and X'40' in the EBCDIC character set.
Code which is dependent on the EBCDIC hexadecimal values of character data
probably fails when run using ASCII. For example, code that tests whether or not
a character is a blank by comparing it with X'40' fails when run using an ASCII
collating sequence.
In the ASCII character set, characters '0' through '9' have the hexadecimal values
X'30' through X'39'. The ASCII lowercase letter 'a' has the hexadecimal value
X'61', and the uppercase letter 'A' has the hexadecimal value X'41'. In the
EBCDIC character set, characters 0 through 9 have the hexadecimal values X'F0'
through X'F9'. In EBCDIC, the lowercase letter 'a' has the hexadecimal value
X'81', and the uppercase letter 'A' has the hexadecimal value X'C1'. These
differences have some important consequences:

While 'a' < 'A' is true for EBCDIC, it is false for ASCII.
While 'A' < '1' is true for EBCDIC, it is false for ASCII.
While x >= '0' almost always means that x is a digit in EBCDIC, this is not
true for ASCII.

Because of these differences, the results of sorting character strings are different
under EBCDIC and ASCII. For many programs, this has no effect, but you should
be aware of potential logic errors if your program depends on the exact sequence
in which some character strings are sorted. If your program is dependent on the
EBCDIC collating sequence and you are porting it to AIX, you can obtain the
EBCDIC collating sequence using PROGRAM COLLATING SEQUENCE IS EBCDIC or
the COLLSEQ(EBCDIC) compiler option.
To avoid problems with the different data representation between ASCII and
EBCDIC characters, use the CHAR(EBCDIC) compiler option. For more information,
see “CHAR” on page 151.

318 COBOL Set for AIX Programming Guide


Getting Mainframe Applications to Run under AIX

IEEE vs HEXADEC
The AIX workstation represents floating-point data using the IEEE format while the
mainframe uses the hexadecimal format.
Figure 71 summarizes the differences between normalized floating-point IEEE and
hexadecimal for USAGE COMP-1 data:

Figure 71. Normalized IEEE vs. Normalized Hexadecimal for COMP-1 Data
Specification IEEE Hexadecimal
Range ±1.17E-38 to ±5.4E-79 to
±3.37E+38 ±7.2E+75
Exponent representation 8 bits 7 bits
Mantissa representation 23 bits 24 bits
Accuracy 6 digits 6 digits

Figure 72 summarizes the differences between normalized floating-point IEEE and


hexadecimal for USAGE COMP-2 data:

Figure 72. Normalized IEEE vs. Normalized Hexadecimal for COMP-2 Data
Specification IEEE Hexadecimal
Range ±2.23E-308 to ±5.4E-79 to
±1.67E+308 ±7.2E+75
Exponent representation 11 bits 7 bits
Mantissa representation 52 bits 56 bits
Digits of accuracy 15 digits 16 digits

For most programs these differences should create no problems. However, use
caution in porting if your program depends on hexadecimal representation of data.
To avoid most problems with the different representation between IEEE and
hexadecimal floating-point data, use the FLOAT(S390) compiler option. For more
information, see “FLOAT” on page 165.

EBCDIC DBCS vs ASCII multi-byte strings


Mainframe double-byte character strings (DBCS) are enclosed in shift codes, while
AIX multi-byte character strings (including DBCS and Extended UNIX Code, EUC)
are not enclosed in shift codes. The hexadecimal values used to represent the
same characters are also different.
For most programs this should not make porting difficult. However, if your program
depends on the hexadecimal value of a graphic string or on a character string con-
taining mixed character and graphic data, use caution in your coding practices.
Single-byte: DBCS or EUC data can contain single-byte characters as well as
multi-byte (2, 3, or 4 byte ) characters.

Chapter 17. Porting Applications between Platforms 319


Getting Mainframe Applications to Run under AIX

Environment Differences Affecting Portability


There are some differences, other than data representation, between the AIX work-
station and mainframe platforms that can also affect the portability of your programs.
This section describes some of these differences.

File names
File naming conventions on the AIX workstation are very different from those on
the mainframe. The following file name, for example, is valid on the AIX work-
station but not on the mainframe:
/users/joesmith/programs/cobol/myfile.cbl
This can have an effect on portability if you use file names in your COBOL source
programs.
Case Sensitivity: Unlike the mainframe, AIX is case-sensitive. Names used in
source programs (such as upper-case file names) should be named appropriately
in AIX file directories.

Control codes
Some characters that have no particular meaning on the mainframe are interpreted
as control characters by AIX. This can lead to incorrect processing of ASCII text
files. Files should not contain any of the following characters:

X'0A' (“LF - line feed”)


X'0D' (“CR - carriage return”)
X'1A' (“EOF - end of file”)

Device-dependent control codes


Use of device-dependent (platform-specific) control codes in your programs or files
can cause problems when trying to port them to other platforms that do not neces-
sarily support the control codes.
As with all other very platform-specific code, it is best to isolate such code as much
as possible so that it can be replaced easily when you move the application to
another platform.

Language Elements Causing Run-Time Differences


In general, you can expect your portable COBOL programs to behave the same way on
the AIX workstation that they do on the mainframe. However, be aware of the differ-
ences in FILE STATUS values use for I/O processing.

If your program is written to respond to status key data items, you should be concerned
with two issues, depending on whether the program is written to respond to the first
status key or the second status key:
1. If your program is written to respond to the first file status data item (data-name-1),
be aware that values returned in the 9X range are platform-dependent. If your
program depends on the interpretation of a particular 9X value (for example, 97),
do not expect the value to have the same meaning on the workstation that it does
on the mainframe. Instead, revise your program so that it responds to any 9X
value as a generic I/O failure.

320 COBOL Set for AIX Programming Guide


Writing AIX Code to Run on the Mainframe

2. If your program is written to respond to the second file status data item
(data-name-8), be aware that the values returned are both platform and file system
dependent. For example, VSAM returns values with a different record structure on
the mainframe than it does on the workstation. If your program relies on the inter-
pretation of the second file status data item, it is probably not portable.

For more information about the FILE STATUS clause, see the IBM COBOL Language
Reference.

Writing AIX Code to Run on the Mainframe


You can use IBM COBOL Set for AIX to write new applications, taking advantage of the
productivity gains and increased flexibility of using your AIX workstation. The purpose
of this section is to make you aware of how to avoid using IBM COBOL Set for AIX
features not supported by mainframe COBOL.

Language Features Supported Only by the AIX Compiler


IBM COBOL Set for AIX supports several language features not supported by
mainframe COBOL compilers. As you write code on your workstation that is intended
to run on the mainframe, avoid using these features:
Ÿ Format 5 SET statement extension that allows setting of pointers or ADDRESS OF
special register to an address of level 01, 02-49, or 77 in the LINKAGE SECTION or
the WORKING-STORAGE SECTION
Ÿ LOCK MODE IS AUTOMATIC
Ÿ READ statement using PREVIOUS phrase
Ÿ START statement using < or <= in the KEY PHRASE
Ÿ USAGE COMP-5 data items

Compiler Options Supported Only under AIX


A number of compile-time options are available with IBM COBOL Set for AIX. Do not
use any of the following options in your source code if you intend to port this code to
the mainframe COBOL compiler:
Ÿ BINARY
Ÿ CHAR
Ÿ FLOAT
Ÿ PROFILE
Ÿ THREAD

Names Supported Only under AIX


Be aware of the difference in naming conventions supported by the AIX and mainframe
file systems. Try to avoid hard-coding the names of files in your source programs.
Instead, use mnemonic names (in turn, mapped to mainframe DDNAMEs or AIX environ-
ment variables) which can be defined on each platform, allowing you to compile your
program without source code changes to accommodate the file name changes.

Chapter 17. Porting Applications between Platforms 321


Writing Portable Applications

Specifically, consider how you refer to files in the following language elements:
Ÿ ACCEPT or DISPLAY target names
Ÿ ASSIGN clause
Ÿ COPY statement (text-name and library-name)

Writing Applications That Are Portable between AIX and the PC


The AIX environment and the OS/2 and Windows COBOL environments are similar,
and their language support is practically identical. However, there are two key differ-
ences between these platforms that you should keep in mind when developing applica-
tions that are portable between AIX and the PC (OS/2 or Windows).
1. As you can expect when porting programs between AIX and the mainframe, hard-
coded filenames in your source programs can lead to problems. See “Names Sup-
ported Only under AIX” on page 321 for a description of how and where to avoid
using literal file names in your source programs.
2. IBM PC-compatibles represent integers in “Little Endian” format (least significant
digit is stored first). Like mainframes, AIX workstations maintain integers in “Big
Endian” format. Therefore, if your AIX COBOL program depends on the internal
representation of an integer, the program is probably not portable to the PC. Avoid
writing programs that rely on such internal representation. If your program requires
manipulating the internal representation of PC-format integers, use the
BINARY(S390) compiler option and avoid the USAGE COMP-5 type.

322 COBOL Set for AIX Programming Guide


Main Programs and Subprograms

Chapter 18. Subprograms


Often, an application will consist of several, separately compiled programs linked
together.

When a run unit consists of several, separately compiled programs that call each other,
the programs must be able to communicate with each other. They need to transfer
control and usually need to have access to common data. The following sections
describe the methods that allow separately compiled programs to communicate with
one another.

COBOL programs that are nested within each other can also communicate. All the
required subprograms for an application can be contained in one program and thereby
require only a single compilation. This method is explained in “Structure of Nested
Programs” on page 324.

Transferring Control to Another Program


In the PROCEDURE DIVISION, a program can call another program (generally called a
subprogram in COBOL terms), and this called program can itself call other programs.
The program that calls another program is referred to as the calling program, and the
program it calls is referred to as the called program. When the called program proc-
essing is completed, the program can either transfer control back to the calling program
or end the run unit.

The called COBOL program starts running at the top of the PROCEDURE DIVISION.
Not Recomended: You can specify another entry point where the program will begin
running by using the ENTRY label in the called program. However, this is not recom-
mended in a structured program.

Recursive Calls
If a called program directly or indirectly executes its caller (such as program X calling
program Y; program Y calling program Z; and program Z then calling program X), this is
called a recursive call. Recursive calls are allowed if you code the RECURSIVE attribute
on the PROGRAM-ID paragraph of the recursively invoked program and/or if you specify
the THREAD compiler option. If you try to recursively call a COBOL program that does
not have the RECURSIVE attribute coded on its PROGRAM-ID paragraph, the run unit will
end abnormally.

For considerations in using the LINKAGE SECTION with recursive calls, see “With
Recursion or Multithreading” on page 22.

Main Programs and Subprograms


No specific source code statements or options identify a COBOL program to be a main
program or a subprogram. If a COBOL program is the first program in the run unit, that

 Copyright IBM Corp. 1996, 1998 323


Calling COBOL Programs

COBOL program is the main program. Otherwise, it and all other COBOL programs in
the run unit are subprograms.

Whether a COBOL program is a main program or a subprogram can be significant for


either of two reasons:
Ÿ If execution ends in the main program, the main program must use a STOP RUN or
GOBACK statement. STOP RUN terminates the run unit, and closes all files opened
by the main program and its called subprograms. Control is returned to the caller
of the main program, which is often the operating system. GOBACK has the same
effect in the main program. An EXIT PROGRAM performed in a main program has
no effect.
A subprogram can end with an EXIT PROGRAM, a GOBACK, or a STOP RUN state-
ment. If the subprogram ends with an EXIT PROGRAM or a GOBACK statement,
control returns to its immediate caller without ending the run unit. An implicit EXIT
PROGRAM statement is generated if there is no next executable statement in a
called program. If the subprogram ends with a STOP RUN statement, the effect is
the same as it is in a main program: all COBOL programs in the run unit are termi-
nated, and control returns to the caller of the main program.
Ÿ A subprogram is usually left in its last-used state when it terminates with EXIT
PROGRAM or GOBACK. The next time it is called in the run unit, its internal values
will be as they were left, except that return values for PERFORM statements will be
reset to their first values. In contrast, a main program is initialized each time it is
called. There are three exceptions:
1. A subprogram that is called and then cancelled will be in the initial state the
next time it is called.
2. A program with the INITIAL attribute will be in the initial state each time it is
called.
3. Data defined in the LOCAL-STORAGE section is in initial state each time it is
called.

Making Calls between COBOL Programs


You can transfer control to nested and/or non-nested COBOL programs.

Calls to nested programs allow you to create applications using structured programming
techniques. They can also be used in place of PERFORM procedures to prevent unin-
tentional modification of data items. Calls to nested programs can be made using
either the CALL literal or CALL identifier statement. For more information on nested
programs, see “Structure of Nested Programs.”

Structure of Nested Programs


A COBOL program can contain or “nest” other COBOL programs. The nested pro-
grams can themselves nest yet other programs. A nested program can be directly or
indirectly nested in a program.

324 COBOL Set for AIX Programming Guide


Calling COBOL Programs

Figure 73 describes a nested program structure with directly and indirectly nested pro-
grams.

┌──────────Id Division.
X is the outermost program │ Program─Id. X.
and directly contains X1 and ─────────5│ Procedure Division.
X2, and indirectly contains │ Display "I'm in X"
X11 and X12 │ Call "X1"
│ Call "X2"
│ Stop Run.
│ ┌──────Id Division.
X1 is directly contained │ │ Program─Id. X1.
in X and directly ─────────│─5│ Procedure Division.
contains X11 and X12 │ │ Display "I'm in X1"
│ │ Call "X11"
│ │ Call "X12"
│ │ Exit Program.
│ │ ┌───Id Division.
X11 is directly │ │ │ Program─Id. X11.
contained in X1 ────────│──│─5│ Procedure Division.
and indirectly │ │ │ Display "I'm in X11"
contained in X │ │ │ Exit Program.
│ │ └───End Program X11.
│ │ ┌───Id Division.
X12 is directly │ │ │ Program─Id. X12.
contained in X1 ────────│──│─5│ Procedure Division.
and indirectly │ │ │ Display "I'm in X12"
contained in X │ │ │ Exit Program.
│ │ └───End Program X12.
│ └──────End Program X1.
│ ┌──────Id Division.
│ │ Program─Id. X2.
X2 is directly ───────────────────│─5│ Procedure Division.
contained in X │ │ Display "I'm in X2"
│ │ Exit Program.
│ └──────End Program X2.
└─────────End Program X.

Figure 73. Nested Program Structure with Directly and Indirectly Contained Programs

Conventions for Using Nested Program Structure


Follow these conventions when using nested program structures:
Ÿ The IDENTIFICATION DIVISION is required in each program. All other divisions are
optional.
Ÿ Nested program names must be unique.
Ÿ Nested program names can be any valid COBOL word or a non-numeric literal.
Ÿ Nested programs cannot have a CONFIGURATION SECTION. The outermost
program must set any CONFIGURATION SECTION options that might be required.
Ÿ Each nested program is included in the nesting program immediately before its End
Program header (see Figure 73).
Ÿ Nested and nesting programs must be terminated by an End Program header.

Calling nested Programs


A nested program can be called only by its directly nesting program, unless the nested
program is identified as COMMON in its PROGRAM-ID clause. In that case, the
common program can also be called by any program that is nested (directly or indi-

Chapter 18. Subprograms 325


Calling COBOL Programs

rectly) in the same program as the common program. Only nested programs can be
identified as COMMON. Recursive calls are not allowed.

Figure 74 shows the outline of a nested structure with some nested programs identified
as COMMON.

┌───Program─Id. A.

│ ┌───Program─Id. A1.
│ │
│ │ ┌───Program─Id. A11.
│ │ │
│ │ │ ┌───Program─Id. A111.
│ │ │ │
│ │ │ └───End Program A111.
│ │ └───End Program A11.
│ │ ┌───Program─Id. A12 is Common.
│ │ │
│ │ └───End Program A12.
│ └───End Program A1.
│ ┌───Program─Id. A2 is Common.
│ │
│ └───End Program A2.
│ ┌───Program─Id. A3 is Common.
│ │
│ └───End Program A3.
└───End Program A.

Figure 74. A Nested Structure with COMMON Programs

The following table describes the calling hierarchy for the structure that is shown in
Figure 74. Programs A12, A2, and A3 are identified as COMMON, and t he calls associ-
ated with them differ.

Figure 75. Calling Hierarchy for Nested Structures with COMMON programs
This Program Can call these programs And can be called by these pro-
grams
A A1, A2, A3 None
A1 A11, A12, A2, A3 A
A11 A111, A12, A2, A3 A1
A111 A12, A2, A3 A11
A12 A2, A3 A1, A11, A111
A2 A3 A, A1, A11, A111, A12, A3
A3 A2 A, A1, A11, A111, A12, A2

Note that:
Ÿ A2 cannot call A1 because A1 is not common and is not contained in A2.
Ÿ A1 can call A2 because A2 is common.

326 COBOL Set for AIX Programming Guide


Linker and Run-Time Resolution

Scope of Names
Names in nested programs are divided into two classes: local and global. The class
determines whether a name is known beyond the scope of the program that declares it.
A specific search sequence locates the declaration of a name after it is referenced in a
program.

Local Names: Names are local unless declared to be otherwise (except the program
name). Local names are not visible or accessible to any program outside of the one in
which they were declared; this includes both contained and containing programs.

Global Names: A name that is global (indicated using the GLOBAL clause) is visible
and accessible to the program in which it is declared, and to all the programs that are
directly and indirectly contained in that program. This allows the contained programs to
share common data and files from the containing program, simply by referencing the
name of the item.

Any item that is subordinate to a global item (including condition names and indexes) is
automatically global.

The same name can be declared with the GLOBAL clause more than one time, pro-
viding that each declaration occurs in a different program. Be aware that masking, or
hiding, a name in a nested program is possible by having the same name occur in
different programs of the same containing structure. This could possibly cause some
problems when a search for a name declaration is taking place.

Searching for Name Declarations: When a name is referenced in a program, a


search is made to locate the declaration for that name. The search begins in the
program that contains the reference and continues outward to containing programs until
a match is found. The search follows this process:
1. Declarations in the program are searched first.
2. If no match is found, only global declarations are searched in successive outer
containing programs.
3. The search ends when the first matching name is found; otherwise, an error exists
if no match is found.

Note that the search is for a global name, not for a particular type of object associated
with the name, such as a data item or file connector. The search stops when any
match is found, regardless of the type of object. If the object declared is of a different
type than that expected, an error condition exists.

Static, Dynamic, and Run-time Linking


COBOL calls can be made to a subprogram that is either linked into the same execut-
able module as the caller (static linking) or a subprogram that is provided in a DLL
(dynamic linking). IBM COBOL Set for AIX also provides for run-time resolution of the
target subprogram from a DLL. If it is linked statically, it is part of the caller's execut-
able module and is loaded with the caller. If it is linked dynamically or resolved at run

Chapter 18. Subprograms 327


Calling C/C++

time, it is provided in a library and is loaded either when the caller is loaded or when it
is called.

Static linking and dynamic linking are done for COBOL CALL literal subprograms only.
See “Static Linking Overview” on page 386 for a discussion on static linking. See
“Shared Library Overview” on page 386 for a discussion of dynamic linking.

Run-time resolution is always done for COBOL CALL identifier and is done for CALL
literal when the DYNAM option is in effect.

CALL identifier
The COBOL CALL identifier, where identifier is a data item that contains the name of a
non-nested subprogram when the program is run, always results in the target subpro-
gram being loaded when it is called. Also, the name of the DLL must match the name
of the target entry point. See “Terminology Notes” on page 387 for a discussion of
COBOL terminology.

CALL literal
The COBOL CALL literal, where literal is the explicit name of a non-nested subprogram
being called, can be resolved statically, dynamically or at run time. If the NODYNAM
compile-time option is in effect, either static or dynamic linking can be done. If DYNAM
is in effect, the CALL literal is resolved the same as CALL identifier: the target subpro-
gram is loaded when it is called, and the name of the DLL must match the name of the
target entry point.

These call definitions apply only in the case of a COBOL program calling a non-nested
program. When a COBOL program calls a nested program, the CALL is resolved by
the compiler without any system intervention.

For a detailed description of the CALL statement, see the IBM COBOL Language Refer-
ence. For more information on calling subprograms in shared libraries see Chapter 23,
“Building Shared Libraries” on page 386.

Making Calls between COBOL and C/C++ Programs


You can call functions written in C or C++ from your COBOL programs and vice versa.
This chapter describes how to perform such interlanguage calls from your COBOL and
C or C++ programs.

Rules and Guidelines for ILC Applications


The following are rules and guidelines for COBOL—C/C++ ILC applications:
Ÿ Run Unit/Process Termination and Stack Frame Collapsing
Functions invoked in one language which result in collapsing of program stack
frame(s) of other language(s) should be avoided. This includes:

328 COBOL Set for AIX Programming Guide


Calling C/C++

– Collapsing some active stack frames from one language with active stack
frames written in another language in the to-be-collapsed stack frames (C
longjmp()).
– Terminating run unit/process from one language while stack frames written in
another language are active: For example, COBOL STOP RUN and C exit() or
_exit().
Instead, the application should be structured in such a way that an invoked
program terminates by returning to its invoker.
These function can be used in an ILC environment as long as the use of such a
function does not result in collapsing of active stack frame(s) of a language other
than the one initiating such a function.
This is a guideline and will not be enforced. Potential adverse effects for the lan-
guages not initiating the collapsing/termination are:
– Normal clean-up/exit functions of the language might not be performed.
An example is the closing of files by COBOL on a run unit termination, or the
clean-up of dynamically acquired resources by the involuntarily terminated lan-
guage.
– User specified exits/functions for the exit/termination might not be invoked.
Examples are destructors and the C atexit() function.
Ÿ Exception Handling
Exceptions incurred during the execution of a stack frame written in one language
might not be processed according to the rules of other languages active in the
invocation stack.
In general, such an exception will be handled according to the rules of the lan-
guage incurring the exception.
This COBOL product will save the exception environment on entry to the COBOL
run time environment and restores it on termination of the COBOL environment.
COBOL expects interfacing languages and tools to follow the same convention.
Since the COBOL implementation does not depend on the interception of
exceptions through system services for the support of ANSI COBOL language
semantics, the user can specify the run-time option, TRAP(OFF), to enable the
exception handling semantics of the non-COBOL language.

Matching Data and Linkages


Some COBOL data types have C/C++ equivalents, but others do not. When you pass
data between COBOL and C/C++ functions, be sure to restrict data exchange to appro-
priate data types. For a detailed description of how COBOL programs can share data
with other programs, see Chapter 19, “Data Sharing” on page 336.

The following table shows the correspondence between the data types available in
COBOL and C/C++.

Chapter 18. Subprograms 329


Calling C/C++

C/C++ Data Types COBOL Data Types


wchar_t DISPLAY-1 (PICTURE N, G)
wchar_t is the processing code whereas DISPLAY-1 is the file code.
See Internationalization of AIX Software— A Programmer's Guide
(SC23-2431-00)
char PIC X
signed char No appropriate COBOL equivalent.
unsigned char No appropriate COBOL equivalent.
short signed int PIC S9-S9(4) COMP-5. Can be COMP, COMP-4, or BINARY if you use
the TRUNC(BIN) compiler option.
short unsigned int PIC 9-9(4) COMP-5. Can be COMP, COMP-4, or BINARY if you use the
TRUNC(BIN) compiler option.

long int PIC 9(5)-9(9) COMP-5. Can be COMP, COMP-4, or BINARY if you use the
TRUNC(BIN) compiler option.

long long int PIC 9(10)-9(18) COMP-5. Can be COMP, COMP-4, or BINARY if you use
the TRUNC(BIN) compiler option.
float COMP-1
double COMP-2
enumeration Equivalent to level 88, but not identical.
char(n) PICTURE X(n)
array pointer (*) to type No appropriate COBOL equivalent.
pointer(*) to function PROCEDURE-POINTER

Figure 76. Correspondence between COBOL and C/C++ Data Types

Example - Calling C/C++ Functions from a COBOL Program


The following COBOL program illustrates several concepts:
Ÿ C/C++ programs are called using the COBOL CALL statement. The CALL statement
does not indicate if the called program is written in COBOL or C/C++.
Ÿ COBOL supports calling programs with mixed-case names.
Ÿ Arguments can be passed to C/C++ programs in different ways (for example, CALL
BY REFERENCE, CALL BY VALUE, etc.).

Ÿ You must declare a function return value on the CALL statement that calls a C/C++
function.
Ÿ You must map COBOL data types to appropriate C/C++ data types.

These concepts are illustrated in the following COBOL source program, cobcallc.cbl:

330 COBOL Set for AIX Programming Guide


Calling C/C++

CBL PGMNAME(MIXED) CALLINT(OPTLINK)


\ These compiler options allow for
\ case-sensitive names for called programs
\ and set the call interface/linking
\ convention to that of the IBM C/C++ default.
\
IDENTIFICATION DIVISION.
PROGRAM-ID. "COBCALLC".
\
DATA DIVISION.
WORKING-STORAGE SECTION.
\
ð1 N4 PIC 9(4) COMP-5.
ð1 NS4 PIC S9(4) COMP-5.
ð1 N9 PIC 9(9) COMP-5.
ð1 NS9 PIC S9(9) COMP-5.
ð1 NS18 USAGE COMP-2.
ð1 D1 USAGE COMP-2.
ð1 D2 USAGE COMP-2.
ð1 R1.
ð2 NR1 PIC 9(8) COMP-5.
ð2 NR2 PIC 9(8) COMP-5.
ð2 NR3 PIC 9(8) COMP-5.
PROCEDURE DIVISION.
MOVE 123 TO N4
MOVE -567 TO NS4
MOVE 98765432 TO N9
MOVE -13579456 TO NS9
MOVE 222.22 TO NS18
DISPLAY "Call MyFun with n4=" N4 " ns4=" NS4 " N9=" n9
DISPLAY " ns9=" NS9 " ns18=" NS18
\
\ The following CALL illustrates several ways to pass
\ arguments.
\
CALL "MyFun" USING N4 BY VALUE NS4 BY REFERENCE N9 NS9 NS18
MOVE 1ð24 TO N4

Figure 77 (Part 1 of 2). cobcallc.cbl - A COBOL Program That Calls a C Program

Chapter 18. Subprograms 331


Calling C/C++

\
\ The following CALL returns the C function return value.
\
CALL "MyFunR" USING BY VALUE N4 RETURNING NS9
DISPLAY "n4=" N4 " and ns9= n4 times n4= " NS9
MOVE -35792568ð.25 TO D1
CALL "MyFunD" USING BY VALUE D1 RETURNING D2
DISPLAY "d1=" D1 " and d2= 2.ð times d2= " D2
MOVE 11111 TO NR1
MOVE 22222 TO NR2
MOVE 33333 TO NR3
CALL "MyFunV" USING R1
STOP RUN.

Figure 77 (Part 2 of 2). cobcallc.cbl - A COBOL Program That Calls a C Program

The COBOL default is that arguments are passed BY REFERENCE. If an argument is


passed BY REFERENCE, C gets a pointer to the argument. If you pass an argument BY
VALUE in the CALL statement, COBOL passes the actual argument. BY VALUE can be
used only for the following data types:
Ÿ Alphanumeric DISPLAY items
Ÿ BINARY
Ÿ COMP
Ÿ COMP-1
Ÿ COMP-2
Ÿ COMP-4
Ÿ COMP-5
Ÿ OBJECT REFERENCE
Ÿ POINTER
Ÿ PROCEDURE-POINTER

For a detailed description of the CALL statement, see the IBM COBOL Language Refer-
ence.

Example - C Programs That are Called by and Call COBOL Programs


The following C program illustrates that a CALLed C function receives arguments in the
order in which they were passed in the COBOL CALL statement. It also shows how a
C program can call a COBOL program (in this case, a program named tprog1, see
Figure 79 on page 334).

332 COBOL Set for AIX Programming Guide


Calling C/C++

The file MyFun.c contains the following C source code:

#include <stdio.h>

extern void TPROG1(double \);

void
MyFun(short \ps1, short s2, long \k1, long \k2, double \m)
{
double x;

x = 2.ð\(\m);
printf("MyFun got s1=%d s2=%d k1=%d k2=%d x=%f\n",
\ps1, s2, \k1, \k2, x);
}

long
MyFunR(short s1)
{
return(s1 \ s1);
}

double
MyFunD(double d1)
{
double z;

/\ example of C calling COBOL \/


z = 1122.3344;
(void) TPROG1(&z);
/\ example of C returning a value to COBOL \/
return(2.ð \ d1);
}

void
MyFunV(long \pn)
{
printf("MyFunV got %d %d %d\n", \pn, \(pn+1), \(pn+2));
}

Figure 78. MyFun.C - A C Program That Calls and is Called by COBOL Programs

MyFun.c consists of the following functions:


MyFun Illustrates passing a variety of arguments.
MyFunR Illustrates how to pass and return a long variable.
MyFunD Illustrates C calling a COBOL program and it also illustrates how to pass
and return a double variable.
MyFunV Illustrates passing a pointer to a record and accessing the items of the
record in a C program.

Chapter 18. Subprograms 333


Calling C/C++

Example - COBOL Program Called by a C Program


In Figure 77 on page 331, you find a COBOL program that calls C functions. In
Figure 78 on page 333, you find a C program that is called by a COBOL program and
calls a COBOL program. The following example illustrates how to write COBOL pro-
grams that are called by C programs.

The file tprog1.cbl is called by the C function MyFunD in the C program MyFun.c (see
Figure 78 on page 333). The called COBOL program contains the following source
code:

\
IDENTIFICATION DIVISION.
PROGRAM-ID. TPROG1.
\
DATA DIVISION.
LINKAGE SECTION.
\
ð1 X USAGE COMP-2.
\
PROCEDURE DIVISION USING X.
DISPLAY "TPROG1 got x= " X
GOBACK.

Figure 79. tprog1.cbl - A COBOL Program Called by a C Program

Pre-Initializing the COBOL Environment


If your main program is written in C and makes multiple calls to a COBOL program, you
should pre-initialize the COBOL environment in your C program. For example, if your C
program repeatedly calls a COBOL program to carry out I/O tasks, you will probably
want the COBOL program to remain in its last-used state.

For additional information, see Chapter 26, “Pre-initializing the COBOL Run-Time
Environment” on page 415.

Results of Running COBCALLC


Compile and link the COBOL programs cobcallc.cbl and tprog.cbl and the C
program MyFun.c and run cobcallc using the following commands:
1. xlc -c MyFun.c
2. cob2 cobcallc MyFun.o tprog1.cbl -o cobcallc

Run the program by entering cobcallc.

334 COBOL Set for AIX Programming Guide


Calling C/C++

The results are as follows:

call MyFun with n4=ðð123 ns4=-ðð567 n9=ðð13579456


ns9=ðð98765432 ns18=ððððð123456789ð2468
MyFun got s1=123 s2=-567 k1=13579456 k2=98765432 x=123456789ð2468
n4=ð1ð24 and ns9= n4 times n4= ððð1ð48576
TPROG1 got x= .11223344ðððððððððE+ð4
d1=-.35792568ð25ððððððE+ð9 and d2= 2.ð times d2= -.71585136ð5ðððððððE+ð9
MyFunV got 11111 22222 33333

Figure 80. Result Compiling and Running the Examples in This Chapter

Chapter 18. Subprograms 335


Passing Data

Chapter 19. Data Sharing


When a run unit consists of several, separately-compiled programs that call each other,
the programs must be able to communicate with each other. They also usually need to
have access to common data.

This chapter will describe how to write programs that can share data with other pro-
grams. For the purposes of this discussion, a “subprogram” is any program called by
another program.

Passing Data
Data can be passed between programs in three ways:
BY REFERENCE The subprogram refers to and processes the data items in
storage of the calling program rather than working on a copy of
the data.
BY CONTENT The calling program passes only the contents of the literal, or
identifier. With a CALL . . . BY CONTENT, the called program
cannot change the value of the literal or identifier in the calling
program, even if it modifies the variable in which it received the
literal or identifier.
BY VALUE The calling program or method is passing the value of the literal,
or identifier, not a reference to the sending data item.

Whether you pass data items BY REFERENCE, BY CONTENT, or BY VALUE depends on


what you want your program to do with the data:
Ÿ If you want the definition of the argument of the CALL statement in the calling
program and the definition of the parameter in the called program to share the
same memory, use:
CALL . . . BY REFERENCE identifier.
Any changes made by the subprogram to the parameter affects the argument in
the calling program.
Ÿ If you want to pass the address of a record area to a called program, use:
CALL . . . BY CONTENT ADDRESS OF record-name.
The subprogram receives the ADDRESS special register for the record-name you
specify.
You must define the record-name as a level-01 or level-77 item in the LINKAGE
SECTION of the called and calling programs. A separate ADDRESS special reg-
ister is provided for each record in the LINKAGE SECTION.
Ÿ If you do not want the definition of the argument of the CALL statement in the
calling program and the definition of the parameter in the called subprogram to
share the same memory, use:

336  Copyright IBM Corp. 1996, 1998


Passing Data

CALL . . . BY CONTENT identifier.


Ÿ If you want to pass a literal value to a called program, use:
CALL . . . BY CONTENT literal.
The called program cannot change the value of the literal.
Ÿ If you want to pass the length of a data item, use:
CALL . . . BY CONTENT LENGTH OF identifier.
The calling program passes the length of the identifier from its LENGTH special reg-
ister.
Ÿ If you want to pass both a data item and its length to a subprogram, use a combi-
nation of BY REFERENCE and BY CONTENT, for example:
CALL 'ERRPROC' USING BY REFERENCE A
BY CONTENT LENGTH OF A
Ÿ If you want to pass data to C programs that expect the value of the arugment, use:
CALL . . . BY VALUE
that expect a reference (pointer) to the argument, use:
CALL . . . BY REFERENCE
or
CALL . . . BY CONTENT
Use BY REFERENCE if you want the C program to be able to modify the value of
the argument. Use BY CONTENT if you do not want the C program to modify the
value of the argument.
Parameters must be of certain data types to be passed BY VALUE. See the IBM
COBOL Language Reference.
Ÿ If you want to return a value, use:
CALL . . . RETURNING

Describing Arguments in the Calling Program


In the calling program, the arguments are described in the DATA DIVISION in the same
manner as other data items in the DATA DIVISION. Data items in a calling program can
be described in the LINKAGE SECTION of all the programs it calls directly or indirectly.

Here, storage for these items is allocated in the highest outermost program. That is,
program A calls program B, which calls program C. Data items in program A can be
described in the LINKAGE sections of programs B and C, and the one set of data can
be made available to all three programs.

If you reference data in a file, the file must be open when the data is referenced.

Code the USING clause of the CALL statement to pass the arguments.

Chapter 19. Data Sharing 337


PROCEDURE DIVISION in Subprograms

Describing Parameters in the Called Program


You must know what is being passed from the calling program and describe it in the
LINKAGE SECTION of the called program.

Code the USING clause after the PROCEDURE-DIVISION header to receive the parame-
ters.

LINKAGE SECTION
The number of data-names in the identifier list of a called program must not be greater
than the number of data-names in the identifier list of the calling program. There is a
one-to-one positional correspondence; that is, the first identifier of the calling program is
passed to the first identifier of the called program, and so forth. The compiler does not
try to match arguments and parameters.

See Figure 81 for an example.

Calling Program Description Called Program Description

WORKING─STORAGE SECTION. LINKAGE SECTION.


┌───────────────────────────┐ ┌──────────────────────────┐
│ð1 PARAM─LIST. │ │ð1 USING─LIST. │
│ ð5 PARTCODE PIC A. ├─────────5│ 1ð PART─ID PIC X(5). │
│ ð5 PARTNO PIC X(4). │ │ 1ð SALES PIC 9(5). │
│ ð5 U─SALES PIC 9(5). │ │ │
└──────────────────────┬────┘ └────────────────────┬─────┘
. │ . │
. │ . │
. │ . │
│ │
PROCEDURE DIVISION. │ PROCEDURE DIVISION 6
. │ ┌───────────┐
. │ USING │USING─LIST.│
. │ └───────────┘

CALL "CALLED─PROG" 6
┌───────────┐
USING │PARAM─LIST.│ In the called program, the code
└───────────┘ for parts and the part number
are combined into one data item
In the calling program, the code (PART─ID). In the called
for parts (PARTCODE) and the part program, a reference to PART─ID
number (PARTNO) are referred to is the only valid reference to
separately. them.

Figure 81. Common Data Items in Subprogram Linkage

PROCEDURE DIVISION
If an argument was passed BY VALUE, the PROCEDURE DIVISION header of the subpro-
gram must indicate that:
PROCEDURE DIVISION USING BY VALUE.
If an argument was passed BY REFERENCE or BY CONTENT, the PROCEDURE DIVISION
header does not need to indicate how the argument was passed.

338 COBOL Set for AIX Programming Guide


PROCEDURE DIVISION in Subprograms

The header can either be:


PROCEDURE DIVISION USING
or:
PROCEDURE DIVISION USING BY REFERENCE

Grouping Data to Be Passed


Think about grouping all the data items you want to pass between programs and
putting them under one level-01 item. If you do this, you can pass a single level-01
record between programs. For an example of this method, see Figure 81 on
page 338.

To make the possibility of mismatched records even smaller, put the level-01 record in
a COPY library, and copy it in both programs. (That is, copy it in the
WORKING-STORAGE SECTION of the calling program and in the LINKAGE SECTION of the
called program.)

Null-Terminated Strings
Null-terminated strings are supported using syntax shown in the IBM COBOL Language
Reference. You can manipulate null-terminated strings passed from a C program, for
example, by using string handling mechanisms such as those found below:
ð1 L pic X(2ð) value z'ab'.
ð1 M pic X(2ð) value z'cd'.
ð1 N pic X(2ð).
ð1 N-Length pic 99 value zero.
ð1 Y pic X(13) value 'Hello, World!'.

\ Display null-terminated string


Inspect N tallying N-length
for characters before initial x'ðð'
Display 'N: ' N(1:N-length) ' Length: ' N-length

\ Move null-terminated string to alphanumeric, strip null


Unstring N delimited by X'ðð' into X

\ Create null-terminated string


String Y delimited by size
X'ðð' delimited by size
into N.

\ Concatenate two null-terminated strings


String L delimited by x'ðð'
M delimited by x'ðð'
X'ðð' delimited by size
into N.

Chapter 19. Data Sharing 339


PROCEDURE DIVISION in Subprograms

Using Pointers to Process a Chained List


You can manipulate pointer data items, which are a special type of data item to hold
addresses, when you want to pass and receive addresses of record areas. Pointer
data items are data items that are either defined with the USAGE IS POINTER clause, or
are ADDRESS special registers. A typical application for using pointer data items is in
processing a chained list (a series of records where each one points to the next).

For this example, picture a chained list of data that is composed of individual salary
records. Figure 82 shows one way to visualize how these records are linked in
storage:

┌─────────┐ ┌──────────┐
│ │ │ │
SALARY RECORD 6 │ 6 │ 6
┌───────────┴─┐ ┌──────────┴─┐ ┌─────────────┐
PTR─NEXT─REC │addr of next │ │ │ │NULL invalid │
│rec │ │ │ │addr │
NAME ├─────────────┤ ├────────────┤ . . . ├─────────────┤
│ │ │ │ │ │
SALARY ├─────────────┤ ├────────────┤ ├─────────────┤
│ │ │ │ │ │
└─────────────┘ └────────────┘ └─────────────┘

Figure 82. Representation of a Chained List Ending with NULL

The first item in each record points to the next record, except for the last record. The
first item in the last record contains a null value instead of an address, to indicate that it
is the last record.

The high-level logic of an application that processes these records might look some-
thing like this:
OBTAIN ADDRESS OF FIRST RECORD IN CHAINED LIST FROM ROUTINE
CHECK FOR END OF THE CHAINED LIST
DO UNTIL END OF THE CHAINED LIST
PROCESS RECORD
GO ON TO THE NEXT RECORD
END

Figure 83 on page 341 contains an outline of the processing program, LISTS, used in
this example of processing a chained list.

340 COBOL Set for AIX Programming Guide


PROCEDURE DIVISION in Subprograms

IDENTIFICATION DIVISION.
PROGRAM-ID. LISTS.
ENVIRONMENT DIVISION.
DATA DIVISION.
\\\\\\
WORKING-STORAGE SECTION.
77 PTR-FIRST POINTER VALUE IS NULL.
77 DEPT-TOTAL PIC 9(4) VALUE IS ð.
\\\\\\
LINKAGE SECTION.
ð1 SALARY-REC.
ð2 PTR-NEXT-REC POINTER.
ð2 NAME PIC X(2ð).
ð2 DEPT PIC 9(4).
ð2 SALARY PIC 9(6).
ð1 DEPT-X PIC 9(4).
\\\\\\
PROCEDURE DIVISION USING DEPT-X.
\\\\\\
\ FOR EVERYONE IN THE DEPARTMENT RECEIVED AS DEPT-X,
\ GO THROUGH ALL THE RECORDS IN THE CHAINED LIST BASED ON THE
\ ADDRESS OBTAINED FROM THE PROGRAM CHAIN-ANCH
\ AND CUMULATE THE SALARIES.
\ IN EACH RECORD, PTR-NEXT-REC IS A POINTER TO THE NEXT RECORD
\ IN THE LIST; IN THE LAST RECORD, PTR-NEXT-REC IS NULL.
\ DISPLAY THE TOTAL.
\\\\\\
CALL "CHAIN-ANCH" USING PTR-FIRST
SET ADDRESS OF SALARY-REC TO PTR-FIRST
\\\\\\
PERFORM WITH TEST BEFORE UNTIL ADDRESS OF SALARY-REC = NULL
IF DEPT = DEPT-X
THEN ADD SALARY TO DEPT-TOTAL
ELSE CONTINUE
END-IF
SET ADDRESS OF SALARY-REC TO PTR-NEXT-REC
END-PERFORM
\\\\\\
DISPLAY DEPT-TOTAL
GOBACK.

Figure 83. Program for Processing a Chained List

Passing Addresses between Programs


To obtain the address of the first SALARY-REC record area, the LISTS program calls the
program CHAIN-ANCH:
CALL "CHAIN-ANCH" USING PTR-FIRST

Chapter 19. Data Sharing 341


PROCEDURE DIVISION in Subprograms

PTR-FIRST is defined in WORKING-STORAGE in the calling program (LISTS) as a pointer


data item:
WORKING-STORAGE SECTION.
ð1 PTR-FIRST POINTER VALUE IS NULL.

On return from the call to CHAIN-ANCH, PTR-FIRST contains the address of the first
record in the chained list.

PTR-FIRST is initially defined as having a null value as a logic check. If something goes
amiss with the call, and PTR-FIRST never receives the value of the address of the first
record in the chain, a null value remains in PTR-FIRST and, according to the logic of the
program, the records will not be processed.

NULL is a figurative constant used to assign the value of an invalid address (non-
numeric 0) to pointer items. It can be used in the VALUE IS NULL clause, in the SET
statement, and as one of the operands of a relation condition with a pointer data item.

The LINKAGE SECTION of the calling program contains the description of the records in
the chained list. It also contains the description of the department code that is passed,
using the USING clause of the CALL statement.
LINKAGE SECTION.
ð1 SALARY-REC.
ð2 PTR-NEXT-REC POINTER.
ð2 NAME PIC X(2ð).
ð2 DEPT PIC 9(4).
ð2 SALARY PIC 9(6).
ð1 DEPT-X PIC 9(4).

To base the record description SALARY-REC on the address contained in PTR-FIRST,


use a SET statement:
CALL "CHAIN-ANCH" USING PTR-FIRST
SET ADDRESS OF SALARY-REC TO PTR-FIRST

Checking for the End of the Chained List


The chained list in this example is set up so the last record contains an invalid address.
To do this, the pointer data item in the last record would be assigned the value NULL.

A pointer data item can be assigned the value NULL in two ways:
Ÿ A pointer data item can be defined with a VALUE IS NULL clause in its data defi-
nition.
Ÿ NULL can be the sending field in a SET statement.

In the case of a chained list in which the pointer data item in the last record contains a
null value, the code to check for the end of the list would be:

342 COBOL Set for AIX Programming Guide


PROCEDURE DIVISION in Subprograms

IF PTR-NEXT-REC = NULL
.
.
.(logic for end of chain)

If you haven't reached the end of the list, process the record and move on to the next
record.

In the program LISTS, this check for the end of the chained list is accomplished with a
DO WHILE structure:
PERFORM WITH TEST BEFORE UNTIL ADDRESS OF SALARY-REC = NULL
IF DEPT = DEPT-X
THEN ADD SALARY TO DEPT-TOTAL
ELSE CONTINUE
END-IF
SET ADDRESS OF SALARY-REC TO PTR-NEXT-REC
END-PERFORM

Continuing Processing the Next Record


To move on to the next record, set the address of the record in the LINKAGE-SECTION
to be equal to the address of the next record. This is accomplished through the pointer
data item sent as the first field in SALARY-REC:
SET ADDRESS OF SALARY-REC TO PTR-NEXT-REC

Then repeat the record-processing routine, which will process the next record in the
chained list.

A Variation: Incrementing Addresses Received from Another


Program
The data passed from a calling program might contain header information that you want
to ignore (for example, in data received from a CICS application that is not migrated to
the command level).

Because pointer data items are not numeric, you cannot directly perform arithmetic on
them. However, you can use the SET verb to increment the passed address in order to
bypass header information.

Chapter 19. Data Sharing 343


Using Procedure Pointers

You could set up the LINKAGE SECTION like this:


LINKAGE SECTION.
ð1 RECORD-A.
ð2 HEADER PIC X(12).
ð2 REAL-SALARY-REC PIC X(3ð).
.
.
.
ð1 SALARY-REC.
ð2 PTR-NEXT-REC POINTER.
ð2 NAME PIC X(2ð).
ð2 DEPT PIC 9(4).
ð2 SALARY PIC 9(6).

Within the Procedure Division, “base” the address of SALARY-REC on the address of
REAL-SALARY-REC:
SET ADDRESS OF SALARY-REC TO ADDRESS OF REAL-SALARY-REC

SALARY-REC is now based on the address of RECORD-A + 12.

Using Procedure Pointers


Procedure pointers are data items defined with the USAGE IS PROCEDURE-POINTER
clause. You can set procedure-pointer data items to contain entry addresses of (or
pointers to) these entry points:
Ÿ Another COBOL program that is not nested.
Ÿ An alternate entry point in another COBOL program (as defined in an ENTRY
statement).
Ÿ A program written in another language. For example, to receive the entry address
of a C function, call the function with the CALL RETURNING format of the CALL
statement. It will return a pointer that you can convert to a procedure-pointer using
a form of the SET statement.

Rules for Using Procedure Pointers


A procedure-pointer data item can be set only using the SET statement. For example:
CALL 'MyCFunc' RETURNING ptr.
SET proc-ptr TO ptr.
CALL proc-ptr USING dataname.

Therefore, if you set your procedure-pointer item to an entry address in a load module
called using CALL-identifier and your program subsequently CANCELs that called
module, then your procedure-pointer item becomes undefined, and reference to it there-
after is not reliable.

For a complete definition of the USAGE IS PROCEDURE-POINTER clause and the SET
statement, refer to the IBM COBOL Language Reference.

344 COBOL Set for AIX Programming Guide


Passing Return Code Information
You can use the RETURN-CODE special register to pass and receive return codes
between programs. Methods do not return information in the RETURN-CODE special
register, but they can check the register after a CALL to a program.

You can also use the RETURNING phrase on the PROCEDURE DIVISION header in your
method to return information to an invoking program or method. If you use PROCE-
DURE DIVISION. . .RETURNING with CALL. . .RETURNING, the RETURN-CODE register will
not be set.

RETURN-CODE Special Register


When a COBOL program returns to its caller, the contents of the RETURN-CODE special
register are set according to the value of the RETURN-CODE of the program returning to
the caller.

Setting of the RETURN-CODE by the called program is limited to calls between COBOL
programs. For example, if your COBOL program calls a C program, you can't expect
the calling program's RETURN-CODE to be set.

For equivalent functionality between COBOL and C programs, have your COBOL
program call the C program with the RETURNING option. If the C program (function)
correctly declares a function value, the RETURNING value of the calling COBOL
program will be set.
INVOKE Note: The RETURN-CODE special register is not set by use of the INVOKE
statement.

PROCEDURE DIVISION RETURNING . . .


You can use the RETURNING phrase on the PROCEDURE DIVISION header of you
program to return information to the calling program:
PROCEDURE DIVISION RETURNING dataname2

Upon successful return from the called program to its caller, the value in data-name-2 is
stored into the identifier specified in the CALL-RETURNING phrase:
CALL . . . RETURNING dataname2

CALL . . . RETURNING
The RETURNING phrase on the CALL statement can be specified for calls to functions
written in C/C++ or subroutines written in COBOL.

It has the following format:


CALL . . . RETURNING dataname2
The return value of the called program is stored into dataname2.

Chapter 19. Data Sharing 345


Sharing Files between Programs

dataname2 must be defined in the DATA DIVISION of the calling COBOL program. The
data type of the return value declared in the target function must be identical to the
data type of dataname2.

Sharing Data Using the EXTERNAL Clause


Separately compiled programs and methods (including programs in a batch sequence)
can share data items by using EXTERNAL clause.

EXTERNAL is coded on the 01-level data description in the WORKING-STORAGE


SECTION of a program or method, and the following rules apply:

Ÿ Items subordinate to an EXTERNAL group item are themselves EXTERNAL.


Ÿ The name used for the data item cannot be used on another EXTERNAL item in the
same program.
Ÿ The VALUE clause cannot be coded for any group item, or subordinate item, that is
EXTERNAL.

Any COBOL program or method in the run unit, having the same data description for
the item as the program containing the item, can access and process the data item.
For example, if program A had the following data description:
ð1 EXT-ITEM1 EXTERNAL PIC 99.
program B could access that data item by having the identical data description in its
WORKING-STORAGE SECTION.

Remember, any program that has access to an EXTERNAL data item can change its
value. Do not use this clause for data items you need to protect.

Sharing Files between Programs (EXTERNAL Files)


Using the EXTERNAL clause for files allows separately compiled programs or methods
in the run unit to have access to common files.

The rules for using EXTERNAL files are described in the IBM COBOL Language Refer-
ence. In addition, it is recommended that:
Ÿ The data-name in the FILE STATUS clause of all the programs that will check the
file status code must match.
Ÿ For all programs that want to check the same file status field, the EXTERNAL clause
should be coded on the level-01 data definition for the file status field in each
program.

Advantages of EXTERNAL Files


The example on page 348, shows some of the advantages of using EXTERNAL files:
Ÿ The main program can reference the record area of the file, although the main
program does not contain any I/O statements.

346 COBOL Set for AIX Programming Guide


Sharing Files between Programs

Ÿ Each subprogram can control a single I/O function, such as OPEN or READ.
Ÿ Each program has access to the file.

Example Using EXTERNAL Files


The following table gives the names and describes the function of the main program
and subprograms used in the example shown in Figure 85 on page 348.

Figure 84. Program Names for Input-Output Using EXTERNAL Files


Name Function
ef1 This is the main program. It calls all the subprograms, and then verifies the
contents of a record area.
ef1openo This program opens the external file for output and checks the File Status
Code.
ef1write This program writes a record to the external file and checks the File Status
Code.
ef1openi This program opens the external file for input and checks the File Status Code.
ef1read This program reads a record from the external file and checks the File Status
Code.
ef1close This program closes the external file and checks the File Status Code.

Additionally, COPY statements ensure that each subprogram contains an identical


description of the file.

Each program in the example declares a data item with the EXTERNAL clause in its
WORKING-STORAGE SECTION. This item is used for checking file status codes, and is
also placed using the COPY statement.

Each program uses three copy library members:


Ÿ The first is named efselect and is placed in the File-Control paragraph.
Select ef1
Assign To ef1
File Status Is efs1
Organization Is Sequential.
Ÿ The second is named effile and is placed in the FILE SECTION.
Fd ef1 Is External
Record Contains 8ð Characters
Recording Mode F.
ð1 ef-record-1.
ð2 ef-item-1 Pic X(8ð).
Ÿ The third is named efwrkstg and is placed in the WORKING-STORAGE SECTION.
ð1 efs1 Pic 99 External.

Chapter 19. Data Sharing 347


Sharing Files between Programs

Identification Division.
Program-Id.
ef1.
\
\ This is the main program that controls the external file
\ processing.
\
Environment Division.
Input-Output Section.
File-Control.
Copy efselect.
Data Division.
File Section.
Copy effile.
Working-Storage Section.
Copy efwrkstg.
Procedure Division.
Call "ef1openo"
Call "ef1write"
Call "ef1close"
Call "ef1openi"
Call "ef1read"
If ef-record-1 = "First record" Then
Display "First record correct"
Else
Display "First record incorrect"
Display "Expected: " "First record"
Display "Found : " ef-record-1
End-If
Call "ef1close"
Goback.
End Program ef1.

Figure 85 (Part 1 of 4). Input-Output Using EXTERNAL Files

348 COBOL Set for AIX Programming Guide


Sharing Files between Programs

Identification Division.
Program-Id.
ef1openo.
\
\ This program opens the external file for output.
\
Environment Division.
Input-Output Section.
File-Control.
Copy efselect.
Data Division.
File Section.
Copy effile.
Working-Storage Section.
Copy efwrkstg.
Procedure Division.
Open Output ef1
If efs1 Not = ð
Display "file status " efs1 " on open output"
Stop Run
End-If
Goback.
End Program ef1openo.
Identification Division.
Program-Id.
ef1write.
\
\ This program writes a record to the external file.
\
Environment Division.
Input-Output Section.
File-Control.
Copy efselect.
Data Division.
File Section.
Copy effile.
Working-Storage Section.
Copy efwrkstg.
Procedure Division.
Move "First record" to ef-record-1
Write ef-record-1
If efs1 Not = ð
Display "file status " efs1 " on write"
Stop Run
End-If
Goback.
End Program ef1write.

Figure 85 (Part 2 of 4). Input-Output Using EXTERNAL Files

Chapter 19. Data Sharing 349


Sharing Files between Programs

Identification Division.
Program-Id.
ef1openi.
\
\ This program opens the external file for input.
\
Environment Division.
Input-Output Section.
File-Control.
Copy efselect.
Data Division.
File Section.
Copy effile.
Working-Storage Section.
Copy efwrkstg.
Procedure Division.
Open Input ef1
If efs1 Not = ð
Display "file status " efs1 " on open input"
Stop Run
End-If
Goback.
End Program ef1openi.
Identification Division.
Program-Id.
ef1read.
\
\ This program reads a record from the external file.
\
Environment Division.
Input-Output Section.
File-Control.
Copy efselect.
Data Division.
File Section.
Copy effile.
Working-Storage Section.
Copy efwrkstg.
Procedure Division.
Read ef1
If efs1 Not = ð
Display "file status " efs1 " on read"
Stop Run
End-If
Goback.
End Program ef1read.

Figure 85 (Part 3 of 4). Input-Output Using EXTERNAL Files

350 COBOL Set for AIX Programming Guide


Run-Time Arguments

Identification Division.
Program-Id.
ef1close.
\
\ This program closes the external file.
\
Environment Division.
Input-Output Section.
File-Control.
Copy efselect.
Data Division.
File Section.
Copy effile.
Working-Storage Section.
Copy efwrkstg.
Procedure Division.
Close ef1
If efs1 Not = ð
Display "file status " efs1 " on close"
Stop Run
End-If
Goback.
End Program ef1close.

Figure 85 (Part 4 of 4). Input-Output Using EXTERNAL Files

Command Line Arguments

Without -host Option


AIX calls all main programs with the following arguments, except when the -host option
is specified:

Number of command line arguments plus one


Pointer to the name of the program
Pointer to the first argument
Pointer to the second argument
..
.
Pointer to the nth argument

Figure 86 on page 352 shows how to read the command line arguments:

Chapter 19. Data Sharing 351


Run-Time Arguments

..
.
IDENTIFICATION DIVISION.
PROGRAM-ID. "targaix".
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
DATA DIVISION.
WORKING-STORAGE SECTION.
\
linkage section.
ð1 PARM-LEN PIC S9(9) COMP.
ð1 OS-PARM.
ð2 PARMPTR-TABLE OCCURS 1 TO 1ðð TIMES DEPENDING ON PARM-LEN.
ð3 PARMPTR POINTER.
ð1 PARM-STRING PIC XX.
\
PROCEDURE DIVISION USING BY VALUE PARM-LEN BY REFERENCE OS-PARM.
display "parm-len=" parm-len
SET ADDRESS OF PARM-STRING TO PARMPTR(2).
DISPLAY "parm-string= '" PARM-STRING "'";
EVALUATE PARM-STRING
when "ð1" display "case one"
when "ð2" display "case two"
when "95" display "case ninety five"
when other display "case unknown"
end-evaluate
GOBACK.

Figure 86. targaix — An Example of Command Line Arguments

The result of compiling and running the program:


cob2 targaix.cbl
a.out 95
is:
parm-len=ðððððððð2
parm-string= '95'
case ninety five

With -host Option


AIX calls all main programs with an EBCDIC character string that gives the command
line arguments when the -host option is specified. Figure 87 on page 353 shows how
to read the command line arguments:

352 COBOL Set for AIX Programming Guide


Run-Time Arguments

..
.
IDENTIFICATION DIVISION.
PROGRAM-ID. "testarg".
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
DATA DIVISION.
WORKING-STORAGE SECTION.
\
linkage section.
ð1 os-parm.
ð5 parm-len pic s999 comp.
ð5 parm-string.
1ð parm-char pic x occurs ð to 1ðð times
depending on parm-len.
\
PROCEDURE DIVISION using os-parm.
display "parm-len=" parm-len
display "parm-string='" parm-string "'"
evaluate parm-string
when "ð1" display "case one"
when "ð2" display "case two"
when "95" display "case ninety five"
when other display "case unknown"
end-evaluate
GOBACK.

Figure 87. testarg — An Example of Command Line Arguments

The result of compiling and running the program:


cob2 testarg.cbl
a.out "95"
is:
parm-len=ðð2
parm-string='95'
case ninety five
Note: The command line arguments must be entered as a single string enclosed in
double quotes ("). To pass a double quote character in the string precede it by the
escape backslash (\").

Chapter 19. Data Sharing 353


Co-Processor Options

Chapter 20. Programming for a DB2 Environment


In general, the coding for your COBOL program will be the same whether or not you
want it to access a DB2 database. However, to retrieve, update, insert, and delete DB2
data and use other DB2 services, you must use SQL statements.

To communicate with DB2, you need to do the following:


Ÿ Delimit SQL statements with EXEC SQL and END-EXEC STATEMENTS
Ÿ Declare a communications area (SQLCA) in the WORKING-STORAGE SECTION
Ÿ Declare all host variables used in SQL statements in the WORKING-STORAGE OR
LINKAGE sections

Ÿ Code any SQL statements you need


Ÿ Start DB2 if it is not already started
Ÿ Compile with the SQL compiler option
Ÿ Check the return code from DB2 in the SQLCA to handle exceptional conditions that
are indicated

These basics of coding SQL in a COBOL program are described in detail in the DB2
Application Programming Guide and the DB2 SQL Reference.

Compiling with the DB2 Co-Processor


Your source program containing embedded SQL statements is handled by the compiler
without your having to use a separate pre-processor. When the compiler encounters
SQL statements and at significant points in the source program, it interfaces with the
DB2 co-processor, which processes the SQL statements by taking appropriate actions
and indicating to the compiler what native COBOL statements to generate at that point.

Because the compiler is working in conjunction with the DB2 co-processor, DB2 must
be started before you compile your program. To be connected to the target database
for the compile, you can connect before you start the compile or have the compiler
make the connection for you by specifying the database either using the DATABASE
suboption in the SQL option or by naming it in the DB2DBDFT environment variable.

Options for the DB2 Co-Processor


The option string that you provide on the SQL compiler option is made available to the
DB2 co-processor. The content of the string is viewed solely by the DB2 co-processor
and not by the compiler. The following cob2 command will pass the database name
“SAMPLE” and the DB2 option “BLOCKING ALL” to the co-processor:
cob2 -q"sql('database sample blocking all')" mysql.cbl...

The SQL options that you include in the suboption string are cumulative. See the DB2
Command Reference for information on these options.

354  Copyright IBM Corp. 1996, 1998


Co-Processor Options

How Options Are Accumulated


The options specified from multiple sources are concatenated in the order of the specifi-
cations.

For example, the command


cob2 mypgm.cbl -q"SQL('string')"
and the mypgm.cbl source file with
cbl ... SQL("string2") ...
cbl ... SQL("string3") ...
will result in the SQL option string passed to the DB2 co-processor to be
"string1 string2 string3"

Note that the concatenated strings are delimited with single spaces. When multiple
instances of the same SQL suboptions are found, the last specification of that sub-
option in the concatenated string will be in effect.

This concatenation of multiple SQL option specifications allows you to separate SQL
suboptions which may not fit into a single CBL statement into multiple CBL statements.

The compiler limits the length of the concatenated DB2 option string to 4K bytes.

Package and Bind File Names


Two of the suboptions that you can specify with the SQL option are package name and
bind file name. If you do not specify these options, default names are constructed for
them based on the source file name for a non-batch compilation and on the first
program for a batch compilation. For subsequent, non-nested, programs of a batch
compilation, the names are based on the PROGRAM ID of each program.

Package Name
The base name (the source file name or the PROGRAM ID) is modified as follows:
Ÿ Names longer than eight characters are truncated to eight characters
Ÿ Letters are folded to upper case
Ÿ Any character other than A-Z, 0-9, or _ (under score) is changed to 0
Ÿ If the first character is not alphabetic, it is changed to A

Thus, if the base name is 9123aB-cd, the package name would be A123AB0C.

Bind File Name


The extension .BND is added to the base name.

Unless explicitly specified, the file name is relative to the current directory.

Chapter 20. Programming for a DB2 Environment 355


SQL and COBOL

Ignored Options
The following options, which were meaningful to and used by the pre-processor, are
ignored by the co-processor:
MESSAGES
NOLINEMACRO
OPTLEVEL
OUTPUT
SQLCA
TARGET
WCHARTYPE

SQL INCLUDE Statement


An SQL INCLUDE statement is treated identically to a native COBOL COPY statement,
including the path search and the file extensions used.

For example,
EXEC SQL INCLUDE name
is treated identically to
COPY name.

The name on an SQL INCLUDE statement follows the same rules as those for the copy
text-name and is processed identically to a COPY statement with that text-name without
a REPLACING clause. See “Compiler Environment Variables” on page 129 and the dis-
cussion on the COPY statement in the “Compiler-Directing Statements” on page 187
section for details.

COBOL does not use the DB2 environment variable DB2INCLUDE for SQL INCLUDE
processing.

If you have been using DB2INCLUDE for your SQL INCLUDE processing, you can simply
concatenate it with the setting of the COBOL SYSLIB environment variable in the
.profile file in your home directory or at the prompt presented in an AIX command
shell. For example, export SYSLIB=$DB2INCLUDE:$SYSLIB

COBOL Language Usage with SQL


Some restrictions on the use of COBOL language that applied when the pre-processor
was used are lifted with the use of the co-processor.

Specifically the following are permitted:


Ÿ EXEC SQL BEGIN DECLARE SECTION and EXEC SQL END DECLARE SECTION statements
are no longer required to identify host variables used on SQL statements
Ÿ Batch compilation is supported: the source file may contain multiple non-nested
COBOL programs

356 COBOL Set for AIX Programming Guide


Testing the DB2 Return Code

Ÿ The source program may contain nested programs


Ÿ The source program may contain object-oriented COBOL language extensions

It is recommended that binary data items that are specified in an SQL statement be:
Ÿ Declared as USAGE COMP-5 or
Ÿ Used with the TRUNC(BIN) option if USAGE BINARY, COMP or COMP-4 item is speci-
fied
If you specify a BINARY, COMP, or COMP-4 item with option TRUNC(OPT) or TRUNC(STD)
in effect, it will be accepted by the compiler but may invalidate the data due to the
application of the decimal truncation rule. It is your responsibility to insure that trun-
cation does not affect the validity of the data.

For information about using SQL with System/390 host data types, see Appendix B,
“System/390 Host Data Type Considerations” on page 469.

Level of SQL Support


SQL statements are supported at the level of DB2 for AIX Single-User, Version 2,
including:
Ÿ Large Objects (BLOB, CLOB, ...)
Ÿ Compound SQL
Limit: The size of large objects is currently limited to 16M bytes for a group or ele-
mentary data item.

Testing the Return Code


In general, when DB2 finishes processing an SQL statement, DB2 sends back a return
code in the SQLCODE OF SQLCA and SQLSTATE OF SQLCA fields. Your program should
test the SQLCODE and/or SQLSTATE fields and take any necessary action depending on
whether the operation succeeded or failed.

Chapter 20. Programming for a DB2 Environment 357


CICS Overview

Chapter 21. Programming for a CICS Environment


When you develop programs to run under the Customer Information Control System
(CICS), be aware of the steps you must take as well as certain COBOL language
restrictions. A discussion of these coding considerations follows. For additional infor-
mation about developing COBOL programs to run under CICS, consult the CICS Appli-
cation Programming Guide.

An Overview of COBOL in a CICS Environment


CICS applications can be written in COBOL and run on the AIX workstation using CICS
for AIX.

The following list outlines the 8 general steps involved in preparing a COBOL applica-
tion that runs under CICS:
1. Initialize the CICS environment. Note that the environment variables for CICS are
set when the CICS region is started. The system administrator sets the values in
the file /var/cics_regions/xxx/environment (where xxx is the name of the region)
and then starts the region. Your system administrator should set the environment
variables necessary for you to access programs, mapsets, copybooks, and files.
2. Create your COBOL application. For CICS-specific COBOL programming consid-
erations, see “Preparing COBOL Applications to Run under CICS” on page 359.
Specifically, use an editor to do the following:
Ÿ Code your program using COBOL statements and CICS commands
Ÿ Create COBOL copybooks
Ÿ Create CICS screen maps used by your program
For a detailed description of COBOL programming under CICS, see the CICS
Application Programming Guide.
3. Process the CICS screen maps using the cicsmap command.
4. Use the CICS command CICSTCL to:

Translate CICS commands will be translated into valid COBOL statements.

Compile The COBOL compiler will be invoked and the program will be com-
piled.

Link The compiled COBOL program will be linked to create a module


with the file extension .ibmcob.

5. Define your application's resources, such as transactions, programs, and files, to


the CICS region to which you have access. See the CICS Administration Guide for
details about defining these resources. (CICS administrator authority is required to
perform these actions).
6. Logon to DCE using dce_login and obtain access to available CICS regions using
the cicsterm command.

358  Copyright IBM Corp. 1996, 1998


CICS Application Prep

7. Select the CICS region where your resources are defined. Depending on how your
system is configured, you may have to first sign into CICS using the supplied trans-
action CESN.
8. Run the application by entering its 4-character CICS transaction-id.

Preparing COBOL Applications to Run under CICS


In general, the COBOL language is supported in a CICS environment. However, there
are certain restrictions and considerations you should be aware of when preparing
COBOL applications to run on CICS.

CICS has a Special Reserved Word Table


COBOL provides an alternate reserved word table (IGYCCICS) specifically for CICS
application programs. If you use the compiler option WORD(CICS), COBOL words not
recommended under CICS are flagged by the compiler with an error message.

In addition to the COBOL words restricted by the IBM-supplied default reserved word
table, the IBM-supplied CICS reserved word table restricts the following COBOL words:

ACCEPT FILE-CONTROL RERUN


CLOSE INPUT-OUTPUT REWRITE
DELETE I-O-CONTROL SD
DISPLAY MERGE SORT
FD OPEN START
FILE READ WRITE

Additional Language Restrictions


The following guidelines should be followed when coding COBOL programs that run
under CICS:
Ÿ Do not use EXEC, CICS, DLI, or END-EXEC for variable names.
Ÿ It is recommended that you do not use the FILE-CONTROL entry in the ENVIRON-
MENT DIVISION.

Ÿ It is recommended that you do not use the FILE SECTION of the DATA DIVISION.
Ÿ Do not use user-specified parameters to the main program.
Ÿ It is recommended that you do not use USE declaratives (except USE FOR DEBUG-
GING).

Ÿ The following COBOL language statements are not recommended for use in a
CICS environment:
| – ACCEPT (Format 1 or 2— see “System Date under CICS” on page 361)
– CLOSE
– DELETE
– DISPLAY
– MERGE
– OPEN
– READ

Chapter 21. Programming for a CICS Environment 359


CICS Application Prep

– REWRITE
– SORT
– START
– STOP literal
– WRITE
| Attention: Apart from some forms of the ACCEPT statement, mainframe CICS
does not support any of the COBOL language elements in the preceding
list. If you use any of these COBOL language elements, be aware that:
– The application is not completely portable to the mainframe CICS envi-
ronment.
– In the case of a CICS failure, a backout (restoring the resources asso-
ciated with the failed task) will not be possible.
Ÿ When coding nested (contained) programs, pass DFHEIBLK and DFHCOMMAREA as
parameters to any nested programs that contain EXEC commands and/or refer-
ences to the EIB. The same parameters must also be passed to any program that
forms part of the control hierarchy between such a program and its top level
program.

Selecting Compiler Options


TRUNC(BIN) is the recommended option under CICS. However, if you are certain that
the non-truncated values of BINARY, COMP, or COMP-4 data items conform to PICTURE
specifications, using TRUNC(OPT) may improve program performance.

COMP-5 can be used instead of BINARY, COMP, or COMP-4 as EXEC CICS command
arguments. COMP-5 is treated with the behavior of BINARY, COMP, or COMP-4 as if
BINARY(NATIVE) and TRUNC(BIN) were in effect, regardless of explicitly setting those
options.

WORD(CICS) is recommended if you want those COBOL language elements not sup-
ported under CICS to be flagged at compile time.

The PGMNAME(MIXED) option must be used for applications that use CICS Client.

The following options should be avoided when compiling programs to run in a CICS
environment:
Ÿ DYNAM
Ÿ NOLIB
Ÿ TRUNC(STD) or TRUNC(OPT)

All other COBOL compiler options are supported. For detailed information on individual
compiler options, see Chapter 10, “Compiler Options” on page 147.

For additional information about CICS access and System/390 host data types, see
Appendix B, “System/390 Host Data Type Considerations” on page 469.

360 COBOL Set for AIX Programming Guide


CICS Application Prep

Selecting Run-Time Options


Use the FILESYS run-time option to specify the file system used for files when no spe-
cific file selection has been made on the ASSIGNment name. For a detailed
description of FILESYS, see Chapter 11, “Run-Time Options” on page 193.

Planning for ASCII-EBCDIC Differences


If your CICS program is running on an ASCII platform (such as OS/2 or AIX), and you
access EBCDIC data, be aware that the neither CICS nor the COBOL run time will
automatically convert the data to the ASCII collating sequence.

Some data access methods (such as VSAM) can carry out such conversions automat-
ically, but you should not assume that the data will be converted. If your program is
designed to access mainframe data, you might want to add logic to your program to
test whether or not the data is EBCDIC and, if necessary, carry out an explicit collating
sequence conversion.

| System Date under CICS


| You should not use a Format 1 ACCEPT statement in a CICS program. Format 2
| ACCEPT is supported with the 4-digit year options; that is:
| ACCEPT identifier FROM DATE YYYYMMDD
| ACCEPT identifier FROM DAY YYYYDDD
| The recommended ways of retrieving the system date in a CICS program are these
| forms of the ACCEPT statement, and the CURRENT-DATE intrinsic function. These
| methods work in both CICS and non-CICS environments.
| Note: The following forms of the ACCEPT statement to receive 2-digit year dates are
| not supported under CICS:
| ACCEPT identifier FROM DATE
| ACCEPT identifier FROM DAY

Dynamic Calls under CICS


Dynamic calls work in the CICS environment, however you have to be careful to set the
COBPATH environment correctly. You also must make sure the called module has the
correct name. Consider the following example.

The program contains


WORKING-STORAGE SECTION.
ð1 WS-COMMAREA PIC 9 VALUE ZERO.
77 SUBPNAME PIC X(8) VALUE SPACES
...
PROCEDURE DIVISION.
MOVE 'alpha' TO SUBPNAME.
CALL SUBPNAME USING DFHEIBLK, DFHCOMMAREA, WS-COMMAREA.
...

Notice that since alpha is a COBOL program containing CICS statements, CICS control
blocks DFHEIBLK and DFHCOMMAREA must be passed to alpha. The source for alpha

Chapter 21. Programming for a CICS Environment 361


CICS Application Prep

is in the file ALPHA.ccp. The CICS command cicstcl is used to translate, compile, and
link ALPHA.ccp, and it produces ALPHA.ibmcob. Notice that COBOL defaults to upper
case names (you can change this by using the PGMNAME(MIXED) option), so it is impor-
tant to name the source ALPHA.ccp (not alpha.ccp) in order to produce ALPHA.ibmcob
and not alpha.ibmcob.

Suppose the CICS region is called green, then ALPHA.ibmcob needs to be copied to
/var/cics_regions/green/bin and the AIX SMIT tool has to be used to define ALPHA
as a CICS program.

Your installation staff have to add


COBPATH=/var/cics_regions/green/bin
to the file /var/cics_regions/green/environment and then they must shut down the
CICS green region and restart it. If you put dynamically called programs in some other
directory, make sure that your installation staff add the directory to COBPATH and
make sure the CICS servers have permission to access the directory.

| DLL Considerations
| The same DLL containing COBOL program(s) should not be used in more than one run
| unit within the same CICS transaction, or the results will be unpredictable. For
| example, Figure 88 shows a CICS transaction where the same subprogram is called
| from two different run units.

| ┌────────────────┐
| │ Program A │
| │ │
| │ │
| │ │
| │ CALL ──────────┼─────────────────────────────┐
| │ │ │
| │ │ │
| │ │ ┌────────────────┐ │
| │ EXEC CICS LINK ├──────5│ Program B │ │
| │ │ │ │ │
| └────────────────┘ │ │ │ ┌─────────────────┐
| │ │ │ │ C.DLL │
| │ │ │ ├──────────────┐ │
| │ │ └──────5│ Program C │ │
| │ CALL ──────────┼───────────5│ │ │
| │ │ │ │ │
| │ │ │ │ │
| │ │ ├──────────────┘ │
| └────────────────┘ │ │
| │ │
| │ │

| Figure 88. CICS Transaction with Two Run Units

| In this example:
| Ÿ Program A CALLs Program C (in C.DLL)
| Ÿ Program A LINKs to Program B using an EXEC CICS LINK command. This
| becomes a new run unit within the same transaction.
| Ÿ Program B CALLs Program C (in C.DLL)

362 COBOL Set for AIX Programming Guide


OO Under CICS

| Programs A and B are sharing the same copy of Program C, and any changes to its
| state will affect both. In the CICS environment, programs in a DLL are initialized (both
| the WSCLEAR compiler option and VALUE clause initialization) only on the first call
| within a run unit. If a COBOL subprogram is called more than once, from either the
| same or different main programs, the subprogram will be initialized only on the first call.

| If you need the subprogram initialized on the first call from each main program, you
| should statically link a separate copy of the subprogram with each calling program.

| If you need the subprogram initialized on every call, you should use one of the following
| methods:
| Ÿ Put data to be reinitialized in the subprogram's Local-Storage Section, rather than
| Working-Storage. Note that this affects initialization by the VALUE clause only, not
| by the WSCLEAR compiler option.
| Ÿ CANCEL the subprogram after each use, so the next call will be to the program in
| its initial state.
| Ÿ Add the INITIAL attribute to the subprogram.

Accessing SFS Data


You can access SFS (the default file system used by CICS for AIX) through VSAM.
For more information, consult the SMARTdata Utilities for AIX publications (see
“SMARTdata Utilities for AIX” on page 562).

Calls between COBOL and C++ under CICS


Be aware of three rules governing calls between COBOL and C/C++ programs under
CICS:
1. COBOL programs which contain CICS commands can call C/C++ programs as long
as the called C/C++ programs do not contain any CICS commands.
2. C/C++ Programs which contain CICS commands can call COBOL programs as
long as the called COBOL programs do not contain any CICS commands.
3. COBOL programs can EXEC CICS LINK or EXEC CICS XCTL to a C/C++ program
regardless of whether or not the C/C++ program contains CICS commands.

Therefore, if your COBOL program invokes a C/C++ program that contains CICS com-
mands (or vice versa), use EXEC CICS LINK or EXEC CICS XCTL rather than the COBOL
CALL statement.

Object-Oriented COBOL Support Under CICS


IBM COBOL supports object-oriented programming through methods. In a CICS appli-
cation program written in IBM COBOL, methods, which are also written in IBM COBOL,
can be accessed using the INVOKE statement. Methods cannot be accessed using
CICS commands, such as EXEC CICS LINK, and may not contain CICS commands.
However, they may access other COBOL programs using the CALL statement and may
access other COBOL methods using the INVOKE statement.

Chapter 21. Programming for a CICS Environment 363


OO Under CICS

If an invoked COBOL method calls another COBOL program that is processed by the
CICS translator (because it contains CICS commands), the CALL statement must pass
the addresses of DFHEIBLK and DFHCOMMAREA as the first two parameters. This
requires the invoker of the COBOL method to pass the addresses of DFHEIBLK and
DFHCOMMAREA as the first two parameters on the INVOKE statement. It further
requires the PROCEDURE DIVISION statement of the COBOL method to include
DFHEIBLK and DFHCOMMAREA as the first two parameters in its USING list.

In summary, let COBPGM1 and COBPGM2 denote two COBOL programs and let
COBCLASS denote an object-oriented COBOL class with METHOD1 and METHOD2 as its
methods. To prepare and run an application program that consists of COBPGM1,
COBPGM2, and COBCLASS under CICS AIX, consider the following:

Ÿ COBPGM1 and COBPGM2 can contain EXEC CICS commands. If they do, they
should be translated before compilation.
Ÿ COBCLASS methods METHOD1 and METHOD2 cannot contain EXEC CICS com-
mands.
Ÿ COBPGM1 and COBPGM2 can access methods METHOD1 and METHOD2 using the
INVOKE statement.

Ÿ COBPGM1 and COBPGM2 cannot access methods METHOD1 and METHOD2 using
the CALL statement.
Ÿ COBPGM1 and COBPGM2 cannot use the EXEC CICS LINK or the EXEC CICS XCTL
command to access methods METHOD1 and METHOD2.
Ÿ DFHEIBLK and DFHCOMMAREA should be passed to methods METHOD1 and
METHOD2 if they call a COBOL program that contains CICS commands.

For example, the following is possible:


1. COBPGM1 invokes METHOD1 and passes DFHEIBLK and DFHCOMMAREA as the first
two parameters.
2. METHOD1 calls COBPGM2 and passes DFHEIBLK and DFHCOMMAREA as the first
two parameters.
3. COBPGM2 issues EXEC CICS commands.
4. COBPGM2 Invokes METHOD2.

Examples of Object-Oriented COBOL Support Under CICS AIX


The following examples show object-oriented COBOL support under CICS AIX:
Ÿ Program Client - File a.ccp
Ÿ Class Hello - File b.cbl
Ÿ Program Client2 - File C.CCP

Program Client - File a.ccp:

364 COBOL Set for AIX Programming Guide


OO Under CICS

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Program Client - File a.ccp \
\ \
\ A simple COBOL program which issues CICS commands and invokes \
\ COBOL method sayHello. Since sayHello will call another COBOL \
\ program (Client2), Client passes DFHEIBLK and DFHCOMMAREA on \
\ the INVOKE statement to sayHello. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification Division.
Program-id. Client.
Environment Division.
Configuration Section.
Repository.
Class Hello.
Data Division.
Working-Storage Section.
ð1 H usage object reference Hello.
77 Msg1 Pic X(3ð) Value "About to invoke a method".
77 Msg2 Pic X(3ð) Value "Returned from invoked method".
Procedure Division.
Invoke Hello "somNew" returning H
EXEC CICS SEND FROM(Msg1) LENGTH(3ð) ERASE END-EXEC.
Invoke H "sayHello" Using DFHEIBLK DFHCOMMAREA
EXEC CICS SEND FROM(Msg2) LENGTH(3ð) ERASE END-EXEC.
Invoke H "somFree"
EXEC CICS RETURN END-EXEC.
GOBACK.
End Program Client.

Class Hello - File b.cbl:


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Class Hello - File b.cbl \
\ \
\ A simple COBOL class with several methods. Methods may not \
\ contain any CICS commands. The sayHello method calls COBOL \
\ program Client2. Since Client2 will issue CICS commands, \
\ sayHello passes DFHEIBLK and DFHCOMMAREA to it on the CALL \
\ statement. Notice that sayHello expects these parameters on \
\ its PROCEDURE DIVISION statement. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification Division.
Class-id. Hello Inherits SOMObject.
Environment Division.
Configuration Section.
Repository.
Class SOMObject is "SOMObject".
Data Division.
Working-Storage Section.
ð1 Msg Pic X(2ð).
Procedure Division.

Identification Division.

Chapter 21. Programming for a CICS Environment 365


OO Under CICS

Method-id. sayHello.
Data Division.
Linkage Section.
ð1 DFHEIBLK Pic X.
ð1 DFHCOMMAREA Pic X.
Procedure Division Using DFHEIBLK DFHCOMMAREA.
Display "Hello, World!".
Call "Client2" Using DFHEIBLK DFHCOMMAREA.
End Method sayHello.

Identification Division.
Method-id. sayMsg.
Procedure Division.
Display Msg.
End Method sayMsg.

Identification Division.
Method-id. "_Set_Msg".
Data Division.
Linkage Section.
ð1 In-Msg Pic X(2ð).
Procedure Division Using In-Msg.
Move In-Msg to Msg.
End Method "_Set_Msg".

Identification Division.
Method-id. "_Get_Msg".
Data Division.
Linkage Section.
ð1 Out-Msg Pic X(2ð).
Procedure Division Returning Out-Msg.
Move Msg to Out-Msg.
End Method "_Get_Msg".

End Class Hello.

Program Client2 - File C.CCP:


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ Program Client2 - File c.ccp \
\ \
\ A simple COBOL program which issues CICS commands and invokes \
\ COBOL methods _Set_Msg and sayMsg. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Identification Division.
Program-id. Client2.
Environment Division.
Configuration Section.
Repository.
Class Hello.
Data Division.
Working-Storage Section.
ð1 H usage object reference Hello.

366 COBOL Set for AIX Programming Guide


OO Under CICS

77 Client2-Msg Pic X(2ð) Value "Client2 Successful".


Procedure Division.
Invoke Hello "somNew" returning H
Invoke H "_Set_Msg" Using By Content "Hello World Again!"
Invoke H "sayMsg"
Invoke H "somFree"
EXEC CICS SEND FROM(Client2-Msg)
LENGTH(Length of Client2-Msg) ERASE END-EXEC.
EXEC CICS RETURN END-EXEC.
End Program Client2.

Preparing the Examples to Run under CICS AIX


The following steps describe the activities involved in preparing the above examples to
run under CICS for AIX:
1. Translate and compile program client2 (file c.ccp):
cicstran -lIBMCOB -qQUOTE c.ccp

cob2_r -c -qQUOTE -qLIB -I/usr/lpp/cics/include c.cbl


At the completion of this step, the object file c.o will be generated.
2. Compile class Hello (file b.cbl):
cob2_r -c -qQUOTE b.cbl
At the completion of this step, the object file b.o will be generated.
3. Translate and compile program client (file a.ccp), then produce an executable load
module:
cicstran -e -lIBMCOB -qQUOTE a.ccp

cob2_r -qQUOTE -qLIB -I/usr/lpp/cics/include \


-bI:/usr/lpp/cics/lib/cicsprIBMCOB.exp -e _iwz_cobol_main \
-L/usr/lib/dce -ldcelibc_r -ldcepthreads \
-o a.ibmcob a.cbl b.o c.o
At the completion of this step, the object file a.o will be generated and then linked
with b.o, c.o, and required library routines to produce the executable load module
a.ibmcob.
4. Add module a.ibmcob to desired CICS region:
Use the cicsadd command to define the application program module a.ibmcob to a
desired CICS region. See the CICS Administration Reference for more information
about the cicsadd command.
5. Add a transaction-id to the CICS region:
Use the cicsadd command to define a 4-character transaction-id for the application
program a.ibmcob in the same CICS region as the application program. See the
CICS Administration Reference for more information about the cicsadd command.
6. Run the transaction:

Chapter 21. Programming for a CICS Environment 367


OO Under CICS

Use the cicsterm command to select the CICS region and access a CICS terminal.
Enter the 4-character transaction-id at the CICS terminal.

You may want to create a shell script that accepts several arguments, such as each
element of an application program, and performs the above steps in one invocation.

Debugging CICS Programs


Before you debug your CICS programs, you need to translate them into COBOL. Then
you debug CICS programs the same way you would debug any other COBOL program.
For an overview of COBOL language-based debugging techniques, see Chapter 12,
“Debugging Techniques” on page 197.

Alternatively, you can debug CICS programs using the graphical debugger shipped with
the product. See the CICS documentation for instructions about how to invoke the
graphical debugger under CICS. Be sure to instruct the compiler to produce symbolic
information used by the graphical debugger (see “Compiling and Linking Programs” on
page 135).

368 COBOL Set for AIX Programming Guide


Introducing ODBC

Chapter 22. Open Database Connectivity


This chapter contains information to help you use the Open Database Connectivity
(ODBC) interface in your COBOL applications. With ODBC, not only can you access
data from a variety of databases and file systems that support the ODBC interface, but
you can do so dynamically.

Your COBOL applications that use embedded SQL for database access must be proc-
essed by a preprocessor or coprocessor for a particular database and have to be
recompiled if the target database changes. Because ODBC is a call interface, there is
no compile-time designation of the target database as there is with embedded SQL.
Not only can you avoid having multiple versions of your application for multiple data-
bases, but your application can dynamically determine which database to target.

Introducing ODBC
ODBC is a specification for an application program interface (API) that enables applica-
tions to access multiple database management systems using Structured Query Lan-
guage (SQL).

ODBC permits maximum interoperability: a single application can access many dif-
ferent database management systems. This enables you to develop, compile, and ship
an application without targeting a specific type of data source. Users can then add the
database drivers, which link the application to the database management systems of
their choice.

Background
The X/Open Company and the SQL Access Group jointly developed a specification for
a callable SQL interface, referred to as the X/Open Call Level Interface. The goal of
this interface is to increase portability of applications by enabling them to become inde-
pendent of any one database vendor's programming interface.

ODBC was originally developed by Microsoft for Microsoft operating systems based on
a preliminary draft of X/Open CLI. Since this time, other vendors have provided ODBC
drivers that run on other platforms, such as OS/2 and UNIX systems.

| The descriptions and examples in this chapter apply to ODBC Version 3.0. However,
| Version 2.x support is also provided. If you are developing your application for Version
| 2.x ODBC, you will need to use the Version 2.x copybooks instead of the Version 3.0
| copybooks listed here. For details, see “Using the Supplied Copybooks” on page 371.

ODBC Driver Manager


When you use the ODBC interface, your application makes calls through a Driver
Manager. The Driver Manager dynamically loads the necessary driver for the database
server to which the application connects. The driver, in turn, accepts the call, sends
the SQL to the specified data source (database), and returns any result.

 Copyright IBM Corp. 1996, 1998 369


ODBC APIs from COBOL

Choosing Embedded SQL or ODBC


Embedded SQL and ODBC have advantages particular to them. Some of the advan-
tages of embedded SQL are:
Ÿ Static SQL usually provides better performance than dynamic SQL. It does not
have to be prepared at run time, thus reducing both processing and network traffic.
Ÿ With static SQL, database administrators have to grant users access to a package
only rather than access to each table or view that will be used.

Some of the advantages of ODBC are:


Ÿ It provides a consistent interface regardless of what kind of database server is
used.
Ÿ You can have more than one concurrent connection.
Ÿ Applications do not have to be bound to each database on which they will execute.
Although IBM COBOL Set for AIX does this bind for you automatically, it binds
automatically to only one database. If you want to choose which database to
connect to dynamically at run time, you must take extra steps to bind to a different
database.

Using the ODBC Drivers


To enable ODBC for data access in IBM COBOL Set for AIX, you must:
1. Install the ODBC Driver Manager and drivers
2. Add the ODBC database drivers necessary for your installation.
3. Install the RDBMS client (for example, Oracle 7 SQL*NET, DB2 CAE, etc.).

ODBC APIs from COBOL


Included with IBM COBOL Set for AIX are copybooks that make it easier for you to
access data bases with ODBC drivers using ODBC calls from your COBOL programs.
This section describes the supplied copybooks, how ODBC API argument types map to
COBOL data descriptions, and additional COBOL functions and considerations appli-
cable to ODBC APIs.

For details on the ODBC APIs, see the on-line help for the ODBC product that you
have installed.

For specific information related to an ODBC driver, such as the ODBC level or exten-
sions supported by that driver, please refer to the specifications available with that
driver.

The following illustrate how to access ODBC from COBOL programs:


“CALL Interface Convention” on page 371
“Using the Supplied Copybooks” on page 371

370 COBOL Set for AIX Programming Guide


ODBC APIs from COBOL

“Mapping of ODBC C Types” on page 373


“Passing a Pointer as an Argument” on page 373
“Accessing Function Return Values” on page 376
“Testing Bits with a Bit Mask” on page 376

CALL Interface Convention


Programs making ODBC calls must be compiled with the PGMNAME(MIXED) compiler
option.

Using the Supplied Copybooks


| The copybooks described and listed here are for ODBC Version 3.0. However, Version
| 2.x copybooks are also supplied, and you can substitute them for the Version 3.0
| copybooks if you need to develop applications for ODBC Version 2.x. The names of
| the copybooks are as listed in Figure 89.

| Figure 89. Supplied copybooks for ODBC


| Version 3.0 Version 2.x Description
| odbc3.cpy odbc2.cpy Symbols and constants
| odbc3d.cpy odbc2d.cpy Data Division definitions
| odbc3p.cpy odbc2p.cpy Procedure Division statements
| odbc3eg.cbl odbc2eg.cbl Sample program

| The supplied copybook, odbc3.cpy, defines the symbols for constant values described
for ODBC APIs, mapping constants used in calls to ODBC APIs to symbols specified in
ODBC guides so that argument (input and output) and function return values can be
specified and tested.

Some COBOL-specific adaptations have been made:


Ÿ Underscores, “_”, are replaced with hyphens, “-” in the copybook. For example,
SQL_SUCCESS is specified as SQL-SUCCESS.

| Ÿ Names longer than 30 characters are truncated or abbreviated to 30 characters.


| Figure 90 shows the names that are longer than 30 characters, and their corre-
| sponding COBOL names.

| Figure 90 (Page 1 of 2). ODBC Names Truncated or Abbreviated for COBOL


| ODBC C #define symbol > 30 characters long Corresponding COBOL name
| SQL_AD_ADD_CONSTRAINT_DEFERRABLE SQL-AD-ADD-CONSTRAINT-DEFER
| SQL_AD_ADD_CONSTRAINT_INITIALLY_DEFERRED SQL-AD-ADD-CONSTRAINT-INIT-DEF
| SQL_AD_ADD_CONSTRAINT_INITIALLY_IMMEDIATE SQL-AD-ADD-CONSTRAINT-INIT-IMM
| SQL_AD_ADD_CONSTRAINT_NON_DEFERRABLE SQL-AD-ADD-CONSTRAINT-NON-DEFE
| SQL_AD_CONSTRAINT_NAME_DEFINITION SQL-AD-CONSTRAINT-NAME-DEFINIT
| SQL_AT_CONSTRAINT_INITIALLY_DEFERRED SQL-AT-CONSTRAINT-INITIALLY-DE
| SQL_AT_CONSTRAINT_INITIALLY_IMMEDIATE SQL-AT-CONSTRAINT-INITIALLY-IM

Chapter 22. Open Database Connectivity 371


ODBC APIs from COBOL

| Figure 90 (Page 2 of 2). ODBC Names Truncated or Abbreviated for COBOL


| ODBC C #define symbol > 30 characters long Corresponding COBOL name
| SQL_AT_CONSTRAINT_NAME_DEFINITION SQL-AT-CONSTRAINT-NAME-DEFINIT
| SQL_AT_CONSTRAINT_NON_DEFERRABLE SQL-AT-CONSTRAINT-NON-DEFERRAB
| SQL_AT_DROP_TABLE_CONSTRAINT_CASCADE SQL-AT-DROP-TABLE-CONSTRAINT-C
| SQL_AT_DROP_TABLE_CONSTRAINT_RESTRICT SQL-AT-DROP-TABLE-CONSTRAINT-R
| SQL_C_INTERVAL_MINUTE_TO_SECOND SQL-C-INTERVAL-MINUTE-TO-SECON
| SQL_CA_CONSTRAINT_INITIALLY_DEFERRED SQL-CA-CONSTRAINT-INIT-DEFER
| SQL_CA_CONSTRAINT_INITIALLY_IMMEDIATE SQL-CA-CONSTRAINT-INIT-IMMED
| SQL_CA_CONSTRAINT_NON_DEFERRABLE SQL-CA-CONSTRAINT-NON-DEFERRAB
| SQL_CA1_BULK_DELETE_BY_BOOKMARK SQL-CA1-BULK-DELETE-BY-BOOKMAR
| SQL_CA1_BULK_UPDATE_BY_BOOKMARK SQL-CA1-BULK-UPDATE-BY-BOOKMAR
| SQL_CDO_CONSTRAINT_NAME_DEFINITION SQL-CDO-CONSTRAINT-NAME-DEFINI
| SQL_CDO_CONSTRAINT_INITIALLY_DEFERRED SQL-CDO-CONSTRAINT-INITIALLY-D
| SQL_CDO_CONSTRAINT_INITIALLY_IMMEDIATE SQL-CDO-CONSTRAINT-INITIALLY-I
| SQL_CDO_CONSTRAINT_NON_DEFERRABLE SQL-CDO-CONSTRAINT-NON-DEFERRA
| SQL_CONVERT_INTERVAL_YEAR_MONTH SQL-CONVERT-INTERVAL-YEAR-MONT
| SQL_CT_CONSTRAINT_INITIALLY_DEFERRED SQL-CT-CONSTRAINT-INITIALLY-DE
| SQL_CT_CONSTRAINT_INITIALLY_IMMEDIATE SQL-CT-CONSTRAINT-INITIALLY-IM
| SQL_CT_CONSTRAINT_NON_DEFERRABLE SQL-CT-CONSTRAINT-NON-DEFERRAB
| SQL_CT_CONSTRAINT_NAME_DEFINITION SQL-CT-CONSTRAINT-NAME-DEFINIT
| SQL_DESC_DATETIME_INTERVAL_CODE SQL-DESC-DATETIME-INTERVAL-COD
| SQL_DESC_DATETIME_INTERVAL_PRECISION SQL-DESC-DATETIME-INTERVAL-PRE
| SQL_DL_SQL92_INTERVAL_DAY_TO_HOUR SQL-DL-SQL92-INTERVAL-DAY-TO-H
| SQL_DL_SQL92_INTERVAL_DAY_TO_MINUTE SQL-DL-SQL92-INTERVAL-DAY-TO-M
| SQL_DL_SQL92_INTERVAL_DAY_TO_SECOND SQL-DL-SQL92-INTERVAL-DAY-TO-S
| SQL_DL_SQL92_INTERVAL_HOUR_TO_MINUTE SQL-DL-SQL92-INTERVAL-HR-TO-M
| SQL_DL_SQL92_INTERVAL_HOUR_TO_SECOND SQL-DL-SQL92-INTERVAL-HR-TO-S
| SQL_DL_SQL92_INTERVAL_MINUTE_TO_SECOND SQL-DL-SQL92-INTERVAL-MIN-TO-S
| SQL_DL_SQL92_INTERVAL_YEAR_TO_MONTH SQL-DL-SQL92-INTERVAL-YR-TO-MO
| SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES1 SQL-FORWARD-ONLY-CURSOR-ATTR1
| SQL_FORWARD_ONLY_CURSOR_ATTRIBUTES2 SQL-FORWARD-ONLY-CURSOR-ATTR2
| SQL_GB_GROUP_BY_CONTAINS_SELECT SQL-GB-GROUP-BY-CONTAINS-SELEC
| SQL_ISV_CONSTRAINT_COLUMN_USAGE SQL-ISV-CONSTRAINT-COLUMN-USAG
| SQL_ISV_REFERENTIAL_CONSTRAINTS SQL-ISV-REFERENTIAL-CONSTRAINT
| SQL_MAXIMUM_CATALOG_NAME_LENGTH SQL-MAXIMUM-CATALOG-NAME-LENGT
| SQL_MAXIMUM_COLUMN_IN_GROUP_BY SQL-MAXIMUM-COLUMN-IN-GROUP-B
| SQL_MAXIMUM_COLUMN_IN_ORDER_BY SQL-MAXIMUM-COLUMN-IN-ORDER-B
| SQL_MAXIMUM_CONCURRENT_ACTIVITIES SQL-MAXIMUM-CONCURRENT-ACTIVIT
| SQL_MAXIMUM_CONCURRENT_STATEMENTS SQL-MAXIMUM-CONCURRENT-STAT
| SQL_SQL92_FOREIGN_KEY_DELETE_RULE SQL-SQL92-FOREIGN-KEY-DELETE-R
| SQL_SQL92_FOREIGN_KEY_UPDATE_RULE SQL-SQL92-FOREIGN-KEY-UPDATE-R
| SQL_SQL92_NUMERIC_VALUE_FUNCTIONS SQL-SQL92-NUMERIC-VALUE-FUNCTI
| SQL_SQL92_RELATIONAL_JOIN_OPERATORS SQL-SQL92-RELATIONAL-JOIN-OPER
| SQL_SQL92_ROW_VALUE_CONSTRUCTOR SQL-SQL92-ROW-VALUE-CONSTRUCTO
| SQL_TRANSACTION_ISOLATION_OPTION SQL-TRANSACTION-ISOLATION-OPTI

372 COBOL Set for AIX Programming Guide


ODBC APIs from COBOL

A COPY statement to include this copybook should be specified in the DATA DIVISION as
follows:
Ÿ For a program, the COPY statement should be specified in the WORKING-STORAGE
SECTION, in the outer-most program if programs are nested.

Ÿ For a method, the COPY statement should be specified in the WORKING-STORAGE


SECTION of the method (not the WORKING-STORAGE SECTION of the CLASS defi-
nition). This must be done for each method that makes ODBC calls.

Mapping of ODBC C Types


The data types specified in ODBC APIs are defined in terms of ODBC C types in the
API definitions. The following table shows corresponding COBOL declarations for the
indicated ODBC C types of the arguments.

| Figure 91. Mapping of ODBC C Type to COBOL Data Declarations


| ODBC C type COBOL form Description
| SQLSMALLINT COMP-5 PIC Signed short integer (2 byte binary)
| S9(4)
| SQLUSMALLINT COMP-5 PIC 9(4) Unsigned short integer (2 byte binary)
| SQLINTEGER COMP-5 PIC Signed long integer (4 byte binary)
| S9(9)
| SQLUINTEGER COMP-5 PIC 9(9) Unsigned long integer (4 byte binary)
| SQLREAL COMP-1 Floating point (4 bytes)
| SQLFLOAT COMP-2 Floating point (8 bytes)
| SQLDOUBLE COMP-2 Floating point (8 bytes)
| SQLCHAR * POINTER (See Pointer to unsigned character.
| Note)
| SQLHDBC POINTER Connection handle
| SQLHENV POINTER Environment handle
| SQLHSTMT POINTER Statement handle
| SQLHWND POINTER Window handle
| Note: This is a pointer to a null-terminated string. The target (of the pointer) item can be defined
| with PIC X(n), where n is large enough to represent the null terminated field. See “Manipulating
| Null-Terminated Strings” on page 78 for additional considerations on handling null terminated
| strings in COBOL.

Passing a Pointer as an Argument


If an argument is specified as a pointer to one of the above data types, then you need
to do one of the following:
Ÿ Pass the target item of the pointer BY REFERENCE, or
Ÿ Define a pointer data item that will point to the target item and pass that BY
VALUE, or

Chapter 22. Open Database Connectivity 373


ODBC APIs from COBOL

Ÿ Pass the ADDRESS OF the target item BY VALUE.

To illustrate, assume the function is defined as


RETCODE SQLSomeFunction(PSomeArgument)
where PSomeArgument is defined as an argument pointing to SomeArgument.

The argument may be passed to SQLSomeFunction in one of the following ways:


1. Pass SomeArgument BY REFERENCE:
CALL "SQLSomeFunction" USING BY REFERENCE SomeArgument
USING BY CONTENT SomeArgument, may be used instead if SomeArgument is an input
argument.
2. Define a pointer data item PSomeArgument to point to SomeArgument:
SET PSomeArgument TO ADDRESSS OF SomeArgument
CALL "SQLSomeFunction" USING BY VALUE PSomeArgument
3. Pass ADDRESS OF SomeArgument BY VALUE:
CALL "SQLSomeFunction" USING BY VALUE ADDRESS OF SomeArgument

Note that the last approach can be used only if the target argument, SomeArgument, is a
level 01 item in the LINKAGE SECTION. If SomeArgument is a level 01 item in the
LINKAGE SECTION, the addressibility to SomeArgument can be set in one of the following
ways:
1. Explicitly via
SET ADDRESS OF SomeArgument TO a-pointer-data-item
or
SET ADDRESS OF SomeArgument to ADDRESS OF an-identifier
or
2. Implicitly by having SomeArgument passed in as an argument to the program from
which the ODBC function call is being made.

| The following shows a fragment of a sample program invoking the SQLAllocHandle


| function:

374 COBOL Set for AIX Programming Guide


ODBC APIs from COBOL

| ...
| WORKING-STORAGE SECTION.
| COPY ODBC3.
| ...
| ð1 SQL-RC COMP-5 PIC S9(4).
| ð1 Henv POINTER.
| ...
| PROCEDURE DIVISION.
| ...
| CALL "SQLAllocHandle"
| USING
| By VALUE sql-handle-env
| sql-null-handle
| By REFERENCE Henv
| RETURNING SQL-RC
| IF SQL-RC NOT = (SQL-SUCCESS or SQL-SUCCESS-WITH-INFO)
| THEN
| DISPLAY "SQLAllocHandle failed."
| ...
| ELSE
| ...

The above is further illustrated using SQLConnect function. Any one of the following
| examples can be used for calling the SQLConnect function:
| Example 1:
| ...
| CALL "SQLConnect" USING BY VALUE ConnectionHandle
| BY REFERENCE ServerName
| BY VALUE SQL-NTS
| BY REFERENCE UserIdentifier
| BY VALUE SQL-NTS
| BY REFERENCE AuthentificationString
| BY VALUE SQL-NTS
| RETURNING SQL-RC
| ...

| Example 2:
| ...
| SET Ptr-to-ServerName TO ADDRESS OF ServerName
| SET Ptr-to-UserIdentifier TO ADDRESS OF UserIdentifier
| SET Ptr-to-AuthentificationString TO ADDRESS OF AuthentificationString
| CALL "SQLConnect" USING BY VALUE ConnectionHandle
| Ptr-to-ServerName
| SQL-NTS
| Ptr-to-UserIdentifier
| SQL-NTS
| Ptr-to-AuthentificationString
| SQL-NTS
| RETURNING SQL-RC
| ...

Chapter 22. Open Database Connectivity 375


ODBC APIs from COBOL

| Example 3:
| ...
| CALL "SQLConnect" USING BY VALUE ConnectionHandle
| ADDRESS OF ServerName
| SQL-NTS
| ADDRESS OF UserIdentifier
| SQL-NTS
| ADDRESS OF AuthentificationString
| SQL-NTS
| RETURNING SQL-RC
| ...

| In Example 3, Servername, UserIdentifier, and AuthentificationString must be


| defined as level 01 items in the LINKAGE SECTION.

Note that the BY REFERENCE or BY VALUE phrase applies to all arguments until over-
ridden by another BY REFERENCE, BY VALUE, or BY CONTENT phrase.

Accessing Function Return Values


The function return values for an ODBC call should be specified using the RETURNING
phrase on the CALL statement:
CALL "SQLAllocEnv" USING BY VALUE Phenv RETURNING SQL-RC
IF SQL-RC NOT = SQL-SUCCESS
THEN
DISPLAY "SQLAllocEnv failed."
...
ELSE
...
END-IF
...

Testing Bits with a Bit Mask


Some of the ODBC APIs require you to set bit masks and to query bits. A callable
library routine, iwzODBCTestBits, is supplied for your use for querying bits.

This routine may be called as follows:

CALL "iwzODBCTestBits" USING identifier-1, identifier-2


RETURNING identifier-3

identifier-1
This is the field being tested. It must be a 2-or 4-byte binary number field, that is,
USAGE COMP-5 PIC 9(4) or PIC 9(9).

identifier-2
This is the bit mask field to select the bits to be tested. It must be defined with the
same USAGE and PICTURE as identifier-1.

376 COBOL Set for AIX Programming Guide


Sample Program

identifier-3
This is the return value for the test and has the following return values:

0 None of the bits indicated by identifier-2 is ON in identifier-1.


1 All the bits selected by identifier-2 are ON in identifier-1.
-1 One or more bits are ON and one or more bits are OFF among the bits
selected by identifier-2 for identifier-1.
-100 Invalid input argument found (such as an 8-byte binary number field is
used as identifier-1).

It must be defined with USAGE COMP-5 with PIC S9(4).

Multiple bits can be set in a field using COBOL arithmetic expressions with the bit
masks defined in the ODBCCOB copybook. For example, the bits for SQL-CVT-CHAR,
SQL-CVT-NUMERIC, and SQL-CVT-DECIMAL can be set in the InfoValue field by:
COMPUTE InfoValue = SQL-CVT-CHAR + SQL-CVT-NUMERIC + SQL-CVT-DECIMAL

After setting InfoValue, it can be passed to the iwzTestBits function as the second
argument.

Note that the operands of the arithmetic expression above represent disjoint bits from
each other as defined for each of such bit mask symbols in ODBCCOB copybook. You
should be careful not to repeat the same bit in an arithmetic expression for this purpose
(since the operations are arithmetic additions not logical ORs). For example,
COMPUTE InfoValue = SQL-CVT-CHAR + SQL-CVT-NUMERIC + SQL-CVT-DECIMAL
+ SQL-CVT-CHAR
will result in InfoValue not having the SQL-CVT-CHAR bit on.

| Null-Terminated Character Strings


| Some ODBC APIs require you to pass null-terminated character strings as arguments.
| For information on how to construct and manipulate null-terminated strings in COBOL,
| see “Manipulating Null-Terminated Strings” on page 78.

Sample Program Using Supplied Copybooks


Two other copybooks are supplied for your optional use, if you want to use prepared
COBOL statements for commonly used functions for ODBC initialization, error handling,
and clean-up (SQLAllocEnv, SQLAllocConnect, SQLAllocStmt, SQLFreeStmt,
SQLDisconnect, SQLFreeConnect, and SQLFreeEnv). These copybooks may be used
with or without modifications.

| In addition to the odbc3.cpy copybook, the two other copybooks are odbc3d.cpy and
| odbc3p.cpy. Also a skeleton sample program, odbc3eg.cbl, illustrating the use of these
copybooks is included.

| odbc3p.cpy includes COBOL procedure statements that can be performed for initializa-
tion, termination, and error processing.

Chapter 22. Open Database Connectivity 377


Sample Program

| odbc3d.cpy contains data declarations used by odbc3p.cpy in the WORKING-STORAGE


SECTION (or LOCAL-STORAGE SECTION).

Example Notes:
1. The PGMNAME(MIXED) compiler option should be used; the ODBC entry points are
case sensitive.
2. System/390 host data type options should not be used; ODBC APIs expect their
parameters to be in native format.
| 3. The sample code (odbc3eg.cbl, odbc3p.cpy, and odbc3d.cpy) is located in the
| samples/odbc subdirectory under the main COBOL install directory.
| 4. odbc3.cpy is in the include subdirectory under the main COBOL install directory.
5. Including these two subdirectories in your SYSLIB environment variable will ensure
that the copybooks are available to the compiler.

The following illustrates the use of the copybooks:

| cbl pgmname(mixed)
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \ ODBC3EG.CBL \
| \----------------------------------------------------------------\
| \ Sample program using ODBC3, ODBC3D and ODBC3P COPY books \
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| IDENTIFICATION DIVISION.
| PROGRAM-ID. "ODBC3EG".
| DATA DIVISION.

| WORKING-STORAGE SECTION.
| \ copy ODBC API constant definitions
| COPY "odbc3.cpy" SUPPRESS.

| \ copy additional definitions used by ODBC3P procedures


| COPY "odbc3d.cpy".

| \ arguments used for SQLConnect


| ð1 ServerName PIC X(1ð) VALUE Z"Oracle7".
| ð1 ServerNameLength COMP-5 PIC S9(4) VALUE 1ð.
| ð1 UserId PIC X(1ð) VALUE Z"TEST123".
| ð1 UserIdLength COMP-5 PIC S9(4) VALUE 1ð.
| ð1 Authentification PIC X(1ð) VALUE Z"TEST123".
| ð1 AuthentificationLength COMP-5 PIC S9(4) VALUE 1ð.

| Figure 92 (Part 1 of 2). Example of Using the ODBC Copybooks

378 COBOL Set for AIX Programming Guide


Sample Program

| PROCEDURE DIVISION.
| Do-ODBC SECTION.
| Start-ODBC.
| DISPLAY "Sample ODBC 3.ð program starts"

| \ allocate henv & hdbc


| PERFORM ODBC-Initialization

| \ connect to data source


| CALL "SQLConnect" USING BY VALUE Hdbc
| BY REFERENCE ServerName
| BY VALUE ServerNameLength
| BY REFERENCE UserId
| BY VALUE UserIdLength
| BY REFERENCE Authentification
| BY VALUE AuthentificationLength
| RETURNING SQL-RC

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLConnect" to SQL-stmt
| MOVE SQL-HANDLE-DBC to DiagHandleType
| SET DiagHandle to Hdbc
| PERFORM SQLDiag-Function
| END-IF

| \ allocate hstmt
| PERFORM Allocate-Statement-Handle

| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \ add application specific logic here \
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

| \ clean-up environment
| PERFORM ODBC-Clean-Up.

| \ End of sample program execution


| DISPLAY "Sample COBOL ODBC program ended"
| GOBACK.

| \ copy predefined COBOL ODBC calls which are performed


| COPY "odbc3p.cpy".
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \ End of ODBC3EG.CBL: Sample program for ODBC 3.ð \
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

| Figure 92 (Part 2 of 2). Example of Using the ODBC Copybooks

| The following shows the copybook odbc3d.cpy:

Chapter 22. Open Database Connectivity 379


Sample Program

| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \ ODBC3D.CPY (ODBC Ver 3.ð) \
| \----------------------------------------------------------------\
| \ Data definitions to be used with sample ODBC function calls \
| \ and included in WORKING-STORAGE or LOCAL-STORAGE SECTION \
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \ ODBC Handles
| ð1 Henv POINTER VALUE NULL.
| ð1 Hdbc POINTER VALUE NULL.
| ð1 Hstmt POINTER VALUE NULL.

| \ Arguments used for GetDiagRec calls


| ð1 DiagHandleType COMP-5 PIC 9(4).
| ð1 DiagHandle POINTER.
| ð1 DiagRecNumber COMP-5 PIC 9(4).
| ð1 DiagRecNumber-Index COMP-5 PIC 9(4).
| ð1 DiagSQLState.
| ð2 DiagSQLState-Chars PIC X(5).
| ð2 DiagSQLState-Null PIC X.
| ð1 DiagNativeError COMP-5 PIC S9(9).
| ð1 DiagMessageText PIC X(511) VALUE SPACES.
| ð1 DiagMessageBufferLength COMP-5 PIC S9(4) VALUE 511.
| ð1 DiagMessageTextLength COMP-5 PIC S9(4).

| \ Misc declarations used in sample function calls


| ð1 SQL-RC COMP-5 PIC S9(4) VALUE ð.
| ð1 Saved-SQL-RC COMP-5 PIC S9(4) VALUE ð.
| ð1 SQL-stmt PIC X(3ð).

| \\\\\\\\\\\\\\\\\\\\\\\\\
| \ End of ODBC3D.CPY \
| \\\\\\\\\\\\\\\\\\\\\\\\\

| Figure 93. Supplied Copybook odbc3d.cpy

| The following shows the copybook odbc3p.cpy:

380 COBOL Set for AIX Programming Guide


Sample Program

| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \ ODBC3P.CPY \
| \----------------------------------------------------------------\
| \ Sample ODBC initialization, clean-up and error handling \
| \ procedures (ODBC Ver 3.ð) \
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \\\ Initialization functions SECTION \\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| ODBC-Initialization SECTION.
| \
| Allocate-Environment-Handle.
| CALL "SQLAllocHandle" USING
| BY VALUE SQL-HANDLE-ENV
| BY VALUE SQL-NULL-HANDLE
| BY REFERENCE Henv
| RETURNING SQL-RC

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLAllocHandle for Env" TO SQL-stmt
| MOVE SQL-HANDLE-ENV to DiagHandleType
| SET DiagHandle to Henv
| PERFORM SQLDiag-Function
| END-IF.
| \
| Set-Env-Attr-to-Ver3ð-Behavior.
| CALL "SQLSetEnvAttr" USING
| BY VALUE Henv
| BY VALUE SQL-ATTR-ODBC-VERSION
| BY VALUE SQL-OV-ODBC3
| \ or SQL-OV-ODBC2 \
| \ for Ver 2.x behavior \
| BY VALUE SQL-IS-UINTEGER
| RETURNING SQL-RC

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLSetEnvAttr" TO SQL-stmt
| MOVE SQL-HANDLE-ENV to DiagHandleType
| SET DiagHandle to Henv
| PERFORM SQLDiag-Function
| END-IF.
| \
| Allocate-Connection-Handle.
| CALL "SQLAllocHandle" USING
| By VALUE SQL-HANDLE-DBC
| BY VALUE Henv
| BY REFERENCE Hdbc
| RETURNING SQL-RC

| Figure 94 (Part 1 of 5). Supplied Copybook odbc3p.cpy:

Chapter 22. Open Database Connectivity 381


Sample Program

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLAllocHandle for Connection" to SQL-stmt
| MOVE SQL-HANDLE-ENV to DiagHandleType
| SET DiagHandle to Henv
| PERFORM SQLDiag-Function
| END-IF.

| \\\ SQLAllocHandle for statement function SECTION \\\\\\\\\\\\\\\


| Allocate-Statement-Handle SECTION.
| Allocate-Stmt-Handle.
| CALL "SQLAllocHandle" USING
| By VALUE SQL-HANDLE-STMT
| BY VALUE Hdbc
| BY REFERENCE Hstmt
| RETURNING SQL-RC

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLAllocHandle for Stmt" TO SQL-stmt
| MOVE SQL-HANDLE-DBC to DiagHandleType
| SET DiagHandle to Hdbc
| PERFORM SQLDiag-Function
| END-IF.

| \\\ Cleanup Functions SECTION \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


| ODBC-Clean-Up SECTION.
| \
| Free-Statement-Handle.
| CALL "SQLFreeHandle" USING
| BY VALUE SQL-HANDLE-STMT
| BY VALUE Hstmt
| RETURNING SQL-RC

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLFreeHandle for Stmt" TO SQL-stmt
| MOVE SQL-HANDLE-STMT to DiagHandleType
| SET DiagHandle to Hstmt
| PERFORM SQLDiag-Function
| END-IF.
| \

| Figure 94 (Part 2 of 5). Supplied Copybook odbc3p.cpy:

382 COBOL Set for AIX Programming Guide


Sample Program

| SQLDisconnect-Function.
| CALL "SQLDisconnect" USING
| BY VALUE Hdbc
| RETURNING SQL-RC

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLDisconnect" TO SQL-stmt
| MOVE SQL-HANDLE-DBC to DiagHandleType
| SET DiagHandle to Hdbc
| PERFORM SQLDiag-Function
| END-IF.
| \
| Free-Connection-Handle.
| CALL "SQLFreeHandle" USING
| BY VALUE SQL-HANDLE-DBC
| BY VALUE Hdbc
| RETURNING SQL-RC
| IF SQL-RC NOT = SQL-SUCCESS
| MOVE "SQLFreeHandle for DBC" TO SQL-stmt
| MOVE SQL-HANDLE-DBC to DiagHandleType
| SET DiagHandle to Hdbc
| PERFORM SQLDiag-Function
| END-IF.
| \
| Free-Environment-Handle.
| CALL "SQLFreeHandle" USING
| BY VALUE SQL-HANDLE-ENV
| BY VALUE Henv
| RETURNING SQL-RC

| IF SQL-RC NOT = SQL-SUCCESS


| MOVE "SQLFreeHandle for Env" TO SQL-stmt
| MOVE SQL-HANDLE-ENV to DiagHandleType
| SET DiagHandle to Henv
| PERFORM SQLDiag-Function
| END-IF.

| \\\ SQLDiag function SECTION \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


| SQLDiag-Function SECTION.
| SQLDiag.
| MOVE SQL-RC TO SAVED-SQL-RC
| DISPLAY "Return Value = " SQL-RC

| IF SQL-RC = SQL-SUCCESS-WITH-INFO
| THEN
| DISPLAY SQL-stmt " successful with information"
| ELSE
| DISPLAY SQL-stmt " failed"
| END-IF

| Figure 94 (Part 3 of 5). Supplied Copybook odbc3p.cpy:

Chapter 22. Open Database Connectivity 383


Sample Program

| \ - get number of diagnostic records - \


| CALL "SQLGetDiagField"
| USING
| BY VALUE DiagHandleType
| DiagHandle
| ð
| SQL-DIAG-NUMBER
| BY REFERENCE DiagRecNumber
| BY VALUE SQL-IS-SMALLINT
| BY REFERENCE OMITTED
| RETURNING SQL-RC

| IF SQL-RC = SQL-SUCCESS or SQL-SUCCESS-WITH-INFO


| THEN

| \ - get each diagnostic record - \


| PERFORM WITH TEST AFTER
| VARYING DiagRecNumber-Index FROM 1 BY 1
| UNTIL DiagRecNumber-Index > DiagRecNumber
| or SQL-RC NOT =
| (SQL-SUCCESS or SQL-SUCCESS-WITH-INFO)

| \ - get a diagnostic record - \


| CALL "SQLGetDiagRec"
| USING
| BY VALUE DiagHandleType
| DiagHandle
| DiagRecNumber-Index
| BY REFERENCE DiagSQLState
| DiagNativeError
| DiagMessageText
| BY VALUE DiagMessageBufferLength
| BY REFERENCE DiagMessageTextLength
| RETURNING SQL-RC

| Figure 94 (Part 4 of 5). Supplied Copybook odbc3p.cpy:

384 COBOL Set for AIX Programming Guide


Sample Program

| IF SQL-RC = SQL-SUCCESS OR SQL-SUCCESS-WITH-INFO


| THEN
| DISPLAY "Information from diagnostic record number"
| " " DiagRecNumber-Index " for "
| SQL-stmt ":"
| DISPLAY " SQL-State = " DiagSQLState-Chars
| DISPLAY " Native error code = " DiagNativeError
| DISPLAY " Diagnostic message = "
| DiagMessageText (1:DiagMessageTextLength)
| ELSE
| DISPLAY "SQLGetDiagRec request for " SQL-stmt
| " failed with return code of: " SQL-RC
| " from SQLError"
| PERFORM Termination
| END-IF
| END-PERFORM

| ELSE
| \ - indicate SQLGetDiagField failed - \
| DISPLAY "SQLGetDiagField failed with return code of: "
| SQL-RC
| END-IF

| MOVE Saved-SQL-RC to SQL-RC


| IF Saved-SQL-RC NOT = SQL-SUCCESS-WITH-INFO
| PERFORM Termination
| END-IF.

| \\\ Termination Section\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\


| Termination Section.
| Termination-Function.
| DISPLAY "Application being terminated with rollback"
| CALL "SQLTransact" USING BY VALUE henv
| hdbc
| SQL-ROLLBACK
| RETURNING SQL-RC

| IF SQL-RC = SQL-SUCCESS
| THEN
| DISPLAY "Rollback successful"
| ELSE
| DISPLAY "Rollback failed with return code of: "
| SQL-RC
| END-IF
| STOP RUN.

| \\\\\\\\\\\\\\\\\\\\\\\\\
| \ End of ODBC3P.CPY \
| \\\\\\\\\\\\\\\\\\\\\\\\\

| Figure 94 (Part 5 of 5). Supplied Copybook odbc3p.cpy:

Chapter 22. Open Database Connectivity 385


Shared Library Overview

Chapter 23. Building Shared Libraries


By using linking you can have a program call another program which is not contained in
the calling program's source code. Before or during execution, the calling program's
object module is linked with the called program's object module.

Before you begin creating COBOL shared libraries, you should understand the differ-
ences between static linking and shared libraries.

Static Linking Overview


Static linking involves a calling program being linked to a called program module,
resulting in a single executable module. The result of statically linking programs is an
executable module or subprogram in a shared library that contains the executable code
for multiple programs. This may include both the calling program and the called
program. When the program is loaded, the operating system attempts to place a single
file containing the executable code and data into memory.

The primary advantage of static linking is that you can create self-contained, inde-
pendent programs. In other words, the executable program consists of one part that
you need to keep track of. The disadvantages of static linking are as follows:
Ÿ Linked external programs are built into the executable files, making these files
larger.
Ÿ The behavior of executable files cannot be changed without re-linking.
Ÿ External called programs cannot be shared, requiring duplicate copies of programs
to be loaded in memory if more than one calling program needs to access them.

To overcome these disadvantages, use shared libraries.

Shared Library Overview


Shared libraries allow several programs to use a single copy of an executable module.
The executable module is completely separate from the programs that use it. Several
subprograms can be built into a shared library, and calling programs can use these
subprograms as if they were part of the calling program's own executable code. You
can change the shared library subprograms without recompiling or relinking the calling
program.

Shared libraries are typically used to provide common functions that can be used by a
number of programs. For example, shared libraries can be used to implement subpro-
gram packages, subsystems, and interfaces to other programs. Shared libraries are
also used to create object-oriented class libraries (see Chapter 13, “Writing Object-
Oriented Programs” on page 222).

You can dynamically link with the supplied run-time shared libraries as well as with your
own COBOL shared libraries.

386  Copyright IBM Corp. 1996, 1998


Creating a Shared Library

Terminology Notes
If you are new to AIX, you might find the terminology used to discuss shared libraries
confusing.

Keep in mind that a shared library is, above all, a library of functions. Even if there is
only one function provided by the shared library (as in the example provided in this
chapter), a shared library's purpose is to serve as a repository of frequently-used func-
tions.

In COBOL terms, a shared library is a collection of outermost programs. While these


outermost programs may contain nested programs, only the outermost programs
(known as entry points) are callable by programs external to the shared library. Just as
you can compile and link several COBOL programs together as a single executable
module, you link one or more compiled outermost COBOL programs together to create
a shared library.

Because outermost programs in the shared library are part of a library of programs,
each program is referred to as a subprogram in the shared library. Even if a shared
library provides only one program, that program is considered a subprogram of the
shared library.

How the Linker Resolves References to Shared Libraries


When you compile a program, the compiler generates an object module for the code in
the program. If you use any subprograms (“functions” as described in C, “subroutines”
in other languages) that are in an external object module, the compiler adds an external
program reference to your program's object module.

The linker resolves these external references. If it finds a reference to external subpro-
grams in an import file, the code for the external subprogram is in a shared library. To
resolve external reference to shared libraries, the linker adds information to the execut-
able file that tells the loader where to find the shared library code when the executable
file is loaded.

Not all references to shared libraries by COBOL calls are resolved by the linker: CALL
identifier and CALL literal with the DYNAM option are resolved by COBOL when the
CALL is executed.

Creating a Shared Library


Consider the following simple example: there are three files, alpha.cbl, beta.cbl, and
gamma.cbl, each containing a COBOL program.

Chapter 23. Building Shared Libraries 387


Creating a Shared Library

---------------- alpha.cbl ---------------

IDENTIFICATION DIVISION.
PROGRAM-ID. alpha.
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 hello1 pic x(3ð) value is "message from alpha to beta".
ð1 hello2 pic x(3ð) value is "message from alpha to gamma".
\
\
PROCEDURE DIVISION.
display "alpha begins"
call "beta" using hello1
display "alpha after beta"
call "gamma" using hello2
display "alpha after gamma"
goback.

---------------- beta.cbl ---------------

IDENTIFICATION DIVISION.
PROGRAM-ID. beta.
\
ENVIRONMENT DIVISION.
\
DATA DIVISION.
WORKING-STORAGE SECTION.
\
Linkage section.
ð1 msg pic x(3ð).
\
PROCEDURE DIVISION using msg.
DISPLAY "beta gets msg=" msg.
goback.

Figure 95 (Part 1 of 2). Example Programs for Creating a Shared Library

388 COBOL Set for AIX Programming Guide


Creating a Shared Library

---------------- gamma.cbl ---------------

IDENTIFICATION DIVISION.
PROGRAM-ID. gamma.
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
DATA DIVISION.
WORKING-STORAGE SECTION.
\
Linkage section.
ð1 msg pic x(3ð).
\
PROCEDURE DIVISION using msg.
DISPLAY "gamma gets msg=" msg.
goback.

Figure 95 (Part 2 of 2). Example Programs for Creating a Shared Library

The simplest method of running these programs is to compile them into a single module
using the command
cob2 -o m_abg alpha.cbl beta.cbl gamma.cbl

We can run the program by issuing the command


m_abg
The result is:
alpha begins
beta gets msg=message from alpha to beta
alpha after beta
gamma gets msg=message from alpha to gamma
alpha after gamma

We will repeat this example, but this time we put beta and gamma in a shared library
and alpha in a module that uses the library.

The first step is to create a file which we call bg.exp that defines the symbols the
shared library exports:
--------------------- bg.exp --------------------------
#!
\ symbols exported by shared library libbg.a
BETA
GAMMA

These names have to be given in upper case since the COBOL default is to use upper
case names for external symbols. The compile time option PGMNAME(MIXED) can be
used if mixed case names are needed.

Chapter 23. Building Shared Libraries 389


Creating a Shared Library

Now we combine beta and gamma into a shared object called sh_bg:
cob2 -o sh_bg beta.cbl gamma.cbl -bE:bg.exp -bM:SRE -bnoentry

-o sh_bg beta.cbl gamma.cbl are the usual arguments to cob2 to name the output
module sh_bg and to compile and link beta.cbl and gamma.cbl.
-bE:bg.exp is an instruction to the link command to export the symbols named in
bg.exp.
-bM:SRE tells the link command to make the output module a shared re-entrant
object.
-bnoentry tells the linker that this object does not have a main entry point (it will be
entered at BETA and GAMMA).

sh_bg can be used immediately but you may have several of these shared objects and
it is convenient to put them in a library:
ar qv libbg.a sh_bg

Now you can re-compile alpha, this time using the shared library:
cob2 -o m_alpha alpha.cbl -L. libbg.a
or alternatively you can use
cob2 -o m_alpha alpha.cbl -L. -lbg
-lxxx is a standard AIX convention for libxxx.c. The -L. tells the linker that libbg.a
is in the current directory. It is safer to specify the directory in full, for example
cob2 -o m_alpha alpha.cbl -L/usr/jane/libraries -lbg
The -L. form only works if m_alpha and libbg.a are both in the current directory.

Figure 96 on page 391 shows a makefile that combines these commands.

390 COBOL Set for AIX Programming Guide


Creating a Shared Library

---------------------- Makefile -----------------------------

#
#
all: m_abg libbg.a m_alpha

# Create m_abg containing alpha beta and gamma

m_abg: alpha.cbl beta.cbl gamma.cbl


cob2 -o m_abg alpha.cbl beta.cbl gamma.cbl

# Create libbg.a containing beta and gamma


# sh_bg.o is a shared object that exports the symbols defined in bg.exp
# libbg.a is a shared library containing one shared object
# additional objects could be added to the library

libbg.a: beta.cbl gamma.cbl bg.exp


rm -rf libbg.a
cob2 -o sh_bg beta.cbl gamma.cbl -bE:bg.exp -bM:SRE -bnoentry
ar qv libbg.a sh_bg
rm -f sh_bg

# Create m_alpha containing alpha and using library libbg.a


m_alpha: alpha.cbl
cob2 -o m_alpha alpha.cbl -L. libbg.a

clean:
rm -f m_abg m_alpha sh_bg libbg.a \.lst

-------------------------------------------------------------------------

Figure 96. Makefile for Shared Library Example

We included an rm command to remove the old copy of libbg.a and to remove sh_bg
once we are finished with it.

Executing the command m_abg or the command m_alpha gives the same output.

Note that shared libraries are widely used in AIX. The COBOL run-time is in several
shared libraries. The C run-time is in several shared libraries. Shared libraries pro-
vided a convenient and efficient way of packaging applications.

If you intend to use shared libraries, you should read the relevant parts of the AIX
online or printed documents.
Ÿ See the section on Shared Libraries in AIX Version 4.1, General Programming
Concepts; Writing and Debugging Programs (SC23-2533)
Ÿ Further information in the AIX Commands Reference

Chapter 23. Building Shared Libraries 391


Example of CALL Identifier

See the ar command which describes how to build libraries.


See the ld command which describes how to create shared objects.
See the dump command with the -H option (dump -H libbg.a) which shows the
contents of libbg.a and the libraries it invokes.
See also the map sub-command in dbx. It shows what shared libraries are
loaded.

Example of CALL Identifier


The following examples further illustrate creating and running executable modules that
use CALL identifier to call shared libraries.

COBOL Main Program Using CALL identifier


Like the example in “Creating a Shared Library” on page 387, this example has a
COBOL main program that dynamically calls another COBOL program. The example
consists of two programs:
dl1.cbl COBOL main program that does call identifier to DL1A.
dl1a.cbl COBOL program called by dl1.

Figure 97 on page 393 and Figure 98 on page 393 show the source code for the two
programs.

392 COBOL Set for AIX Programming Guide


Example of CALL Identifier

\ dl1: simple dyn call to dl1a

Identification Division.
Program-id. dl1.
\
Environment Division.
Configuration Section.
Input-Output Section.
File-control.
\
Data Division.
File Section.
Working-storage Section.
ð1 var pic x(1ð).
Linkage Section.
\
Procedure Division.
move "Dl1A" to var.
display "Calling " var.
call var.
move "dl1a " to var.
display "Calling " var.
call var.
stop run.
End program dl1.

Figure 97. Source Code for dl1.cbl

\ Called by dl1.cbl by call identifier.

IDENTIFICATION DIVISION.
PROGRAM-ID. dl1a.
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
OBJECT-COMPUTER. ANY-THING.
\
DATA DIVISION.
WORKING-STORAGE SECTION.
77 num pic 9(4) binary value is zero.
\
PROCEDURE DIVISION.
LA-START.
display "COBOL DL1A function." upon console.
add 11 to num.
display "num = " num
goback.

Figure 98. Source Code for dl1a.cbl

Chapter 23. Building Shared Libraries 393


Example of CALL Identifier

To create and run the example, perform the following steps:


1. Enter cob2 dl1.cbl -o dl1 to generate the executable module dl1.
2. Enter cob2 dl1a.cbl -o DL1A to generate the executable module DL1A.
3. Enter the command export COBPATH=. to set the directories to be searched for a
dynamic call. In this case, the current directory would be searched.
4. Enter dl1 to run the program.
Note that DL1A is in upper-case characters. Unless you use the PGMNAME(MIXED) com-
piler option, the program name is changed to upper-case characters.
Restrictions on Run-time Loading: If you plan to make a call to a shared library
using COBOL CALL identifier or COBOL CALL literal with the DYNAM option, you are
restricted as follows:
Ÿ You can export only one name.
Ÿ The exported name must be the same as the name of the shared library.
Ÿ If the shared library is a COBOL shared library, you must link with the same
COBOL library as was the shared library: libcob2s.a or libcob2_r.a.17

Since the target file name of a CALL identifier must match the name of the program,
you have to generate the executable module in the above example as DL1A, not dl1a.

COBOL Main Program Using COBOL and C Shared Libraries


This example has a COBOL main program that dynamically calls both a COBOL
program and a C function. The example consists of three programs:
dl6.cbl COBOL main program that does call identifier to dl6a and dl6b.
dl6a.c C function called by dl6.
dl6b.cbl COBOL program called by dl6.

Figure 99 on page 395, Figure 100 on page 395, and Figure 101 on page 396 show
the source code for the programs.

17 The default library is determined by the -lcob2s and -lcob2_r command flags. Flag -lcob2_r tells the linker to use libcob2s.a;
-lcob2_r tells the linker to use libcob2_r.a.

394 COBOL Set for AIX Programming Guide


Example of CALL Identifier

cbl pgmname(longmixed)
\ dl6:
\ - call C function - dl6a executable
\ - call "dl6b" with pgmname(mixed)
Identification Division.
Program-id. dl6.
\
Environment Division.
Configuration Section.
Input-Output Section.
File-control.
\
Data Division.
File Section.
Working-storage Section.
ð1 var pic x(1ð).
Linkage Section.
\
Procedure Division.
move "dl6a" to var.
display "Calling " var.
call var.
move "dl6a" to var.
display "Calling " var.
call var.
move "dl6b" to var.
display "Calling " var.
call var.
move "dl6b" to var.
display "Calling " var.
call var.
stop run.
End program dl6.

Figure 99. Source Code for dl6.cbl

void dl6a() {
static int n = 123;
printf("C dl6a function.\n");
n = n \ 1ð;
printf("n = %d\n", n);
}

Figure 100. Source Code for dl6a.c

Chapter 23. Building Shared Libraries 395


Example of CALL Identifier

cbl pgmname(longmixed)
IDENTIFICATION DIVISION.
PROGRAM-ID. "dl6b".
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
OBJECT-COMPUTER. ANY-THING.
\
DATA DIVISION.
WORKING-STORAGE SECTION.
77 num pic 9(4) binary value is zero.
\
PROCEDURE DIVISION.
LA-START.
display "COBOL dl6b function." upon console.
add 111 to num.
display "num = " num
goback.

Figure 101. Source Code for dl6b.cbl

To create and run the example, perform the following steps:


1. Enter cob2 dl6.cbl -o dl6 to generate the executable module dl6.
2. Enter cob2 dl6b.cbl -o dl6b to generate the executable module dl6b.
3. Enter xlc -o dl6a -edl6a dl6a.c to generate the executable module dl6a with an
entry point dl6a.
4. Enter the command export COBPATH=. to set the directories to be searched for a
dynamic call. In this case, the current directory would be searched.
5. Enter dl6 to run the program.

396 COBOL Set for AIX Programming Guide


Multithreading

Chapter 24. Preparing COBOL Programs for Multithreading


In the AIX environment, programs may run within the threads of processes. COBOL
supports multithreaded execution by means of the THREAD compiler option (see
“THREAD” on page 179). In order to understand this chapter's discussion of COBOL
support for multithreading, you need to be familiar with the following terms:
Process
The operating system and multithreading applications can handle execution flow
within a process. Multiple processes can run concurrently, and programs run
within a process can share resources. Processes can be manipulated (for
example, they can be given a high or low priority in terms of the amount of time
the system devotes to running the process).
Thread
Within a process, an application can initiate one or more threads. Within the
thread, control is transferred between executing programs.
Run-unit
In a multithreaded environment, a COBOL run-unit is defined as the portion of the
process including threads with actively executing COBOL programs. The COBOL
run-unit continues until no COBOL program is active in the execution stack for
any of the threads (for example, a called COBOL program contains a GOBACK
statement and returns control to a C program). Within the run-unit, COBOL pro-
grams can call non-COBOL programs, and vice versa.
Program Invocation Instance
Within a thread, control is transferred between separate COBOL and non-COBOL
programs. For example, a COBOL program can CALL another COBOL program
or a C program. Each separately invoked (as in, CALLed) program is a program
invocation instance. Program invocation instances of a particular program might
exist in multiple threads within a given process.

The following illustration shows the relationships between processes, threads, run-units,
and program invocation instances.

 Copyright IBM Corp. 1996, 1998 397


Multithreading

A Process Another Concurrent Process

Thread 1 Thread 2 Thread 1


C
program C PL/I C
program program program

Thread 1 Thread 2
COBOL PL/I COBOL
program A program program A
COBOL COBOL Program
program program invocation
A X instances
COBOL C COBOL
program B program program B

COBOL COBOL
program program COBOL COBOL COBOL
B Y program C program A program C
same
• program
• • runs in • •
• • • •
• separate • •
threads
COBOL
run-unit

Figure 102. Schematic Illustration of Multithreading Concepts

COBOL does not directly support initiating or managing program threads. However,
COBOL programs can run as threads in multithreaded environments. In other words,
COBOL programs can be invoked by other applications such that they are running in
multiple threads within a process or as multiple program invocation instances within a
thread. This enables COBOL programs to run in multithreading environments like the
Distributed Computing Environment (DCE).

This remainder of this chapter contains information that will help you prepare your
COBOL programs for multithreaded environments.
Caution: Do not confuse multiprocessing or multithreading with “multitasking,” which is
generally used to describe the external behavior of applications. That is, the operating
system appears to be running more than one application simultaneously. Multitasking
has no relevance in this discussion.

How Language Elements Are Interpreted in a Multithreaded Environment


Because your COBOL programs can be run as separate threads within a process, be
aware that language elements might be interpreted in two ways:
Run-unit scope
The language element persists for the duration of the COBOL run-unit execution
and is available to other programs within the thread.

398 COBOL Set for AIX Programming Guide


Multithreading

Program invocation instance scope


The language element persists only within a particular program invocation
instance.

These two types of scope are important in two contexts:


Reference
Describes where an item can be referenced from. For example, if a data item
has run-unit reference scope, any program invocation instance in the run-unit can
reference the data item.
State
Describes how long an item persists in storage. For example, if a data item has
program invocation instance state scope, it will remain in storage only while the
program invocation instance is running.

The following table summarizes the reference and state scope of various COBOL lan-
guage elements.

Figure 103. Reference and State Scope for Language Elements in a Multithreading Environment
Language Element Reference Scope State Scope
ADDRESS-OF special register Same as associ- Program invocation
ated record instance
Files Run-unit Run-unit
Index data Program Program invocation
instance
LENGTH of special register Same as associ- Same as associated
ated identifier identifier
LINAGE-COUNTER special register Run-unit Run-unit
LINKAGE-SECTION data Run-unit Based on scope of
underlying data.
LOCAL-STORAGE data Within the thread Program invocation
instance
RETURN-CODE Run-unit Program invocation
instance
SORT-CONTROL, SORT-CORE-SIZE, Run-unit Program invocation
SORT-RETURN, TALLY special registers instance
WHEN-COMPILED special register Run-unit Run-unit
WORKING-STORAGE data Run-unit Run-unit

Chapter 24. Preparing COBOL Programs for Multithreading 399


Multithreading

Working with Run-Unit Scoped Elements


If you have resources with run-unit scope (such as GLOBAL data declared in the
WORKING-STORAGE section), it is your responsibility to synchronize access to that
data from multiple threads using logic in the application. You can do one or both of the
following:
Ÿ Structure the application such that run-unit scoped resources are not accessed
simultaneously from multiple threads.
Ÿ If you are going to access resources simultaneously from separate threads, syn-
chronize access using facilities provided by C or by platform functions.

If you have resources with run-unit scope, and you want those resources to be isolated
within an individual program invocation instance (for example, programs with individual
copies of data), define the data in the local storage section so that it will have program
invocation instance scope.

Working with Program Invocation Instance Scoped Elements


With these language elements, storage is allocated for each individual program invoca-
tion instance. Therefore, even if a program is invoked multiple times among multiple
threads, each time it is invoked it will be allocated separate storage. For example, if
program X is invoked in two or more threads, each program invocation instance of X
gets its own set of resources, such as storage.

Because the storage associated with these language elements is program invocation
instance scoped, data is protected from access across threads and you do not have to
concern yourself with access synchronization. However, this data cannot be shared
between invocations of programs unless it is explicitly passed.

Choosing THREAD for Multithreading Support


Select the THREAD compiler option for multithreading support. Choose THREAD only if
you think your program will be invoked more than once in a single process by an appli-
cation (such as a DCE server application.) Compiling with THREAD prepares the
COBOL run-time environment for threading support. However, compiling with THREAD
may reduce program performance. You must compile all of the programs in the run
unit with THREAD; you cannot mix programs compiled with THREAD and those com-
piled with NOTHREAD in one run unit.

The default option is NOTHREAD. For more information about the THREAD compiler
option, see “THREAD” on page 179.

Language Restrictions under THREAD


When THREAD is in effect, the following language elements are not supported and are
flagged by the compiler with error-level messages:
Ÿ ALTER statement
Ÿ DEBUG-ITEM special register
Ÿ GO TO statement without a procedure name

400 COBOL Set for AIX Programming Guide


Multithreading

Ÿ INITIAL PROGRAM
Ÿ RERUN
Ÿ Segmentation module
Ÿ STOP literal statement
Ÿ STOP RUN

Recursion with Threading


If a program is compiled with the THREAD compiler option, the program may be invoked
recursively in a threading or non-threading environment. This applies whether or not
the RECURSIVE phrase is specified in the PROGRAM-ID paragraph.

For considerations in using the LINKAGE SECTION with recursive calls, see “With
Recursion or Multithreading” on page 22.

Control Transfer within a Multithreaded Environment


Be aware of the following control transfer issues when writing COBOL programs for a
multithreaded environment:
CALL and CANCEL
As is the case in single-threaded environments, a program invoked is in its initial
state the first time it is called within a run unit and the first time it is called after a
CANCEL to the CALLED program.

EXIT PROGRAM
EXIT PROGRAM from the first program of a thread terminates that thread. EXIT
PROGRAM returns to the caller of the program without terminating the thread in all
other cases. EXIT PROGRAM from a main program is treated as a comment.
GOBACK
Same as EXIT PROGRAM, except that GOBACK from a main program terminates
the thread.
If it can be determined that there are no other COBOL programs active in the run
unit, the COBOL run unit termination process (including closing all open COBOL
files) is performed on the GOBACK from the first program of this thread. This
determination can be made if all COBOL programs invoked within the run unit
have returned to their invokers via GOBACK or EXIT PROGRAM.
Examples on when this determination cannot be made are:
Ÿ A thread with one or more active COBOL programs was terminated (for
example, because of an exception or via pthread_exit).
Ÿ A longjmp() was executed which resulted in collapsing active COBOL pro-
grams in the invocation stack.
In general, it is recommended that the programs initiating and managing multiple
threads use the COBOL pre-initialization interface.
Pre-initialization
If your program initiates multiple COBOL threads (for example, your C program
calls COBOL programs to carry out I/O), do not assume the COBOL programs

Chapter 24. Preparing COBOL Programs for Multithreading 401


Multithreading

will “clean up” their environment. Particularly, do not assume that files will be
automatically closed. You should pre-initialize the COBOL environment so that
your application can control the COBOL “clean-up” (see Chapter 26, “Pre-
initializing the COBOL Run-Time Environment” on page 415).
STOP RUN: There is no COBOL function that effectively does a STOP RUN in a
threaded environment. If you need this behavior, consider invoking the C exit()
function from your COBOL program and using _iwzCOBOLTerm after the run-unit
termination exit.

Limitations on COBOL in a Multithreaded Environment


Some COBOL applications depend on subsystems or other applications. In a multi-
threaded environment, these dependencies result in some limitations on COBOL
programs:
DB2
The DB2 application may be run in multiple threads. However, any necessary
synchronization for DB2 data access is the responsibility of the application.
SORT/MERGE
SORT and MERGE should only be active in one thread at a time. However, this
is not enforced by the COBOL run-time environment— it must be controlled by
the application.
VSAM file I/O
I/O for VSAM files should be active from only one thread at a time. However,
this is not enforced by the COBOL run-time environment— it must be controlled
by the application.

In general, synchronizing access to resources visible to an application within a run unit


is the responsibility of the application. The exceptions to this are DISPLAY and ACCEPT,
which can be executed from multiple threads without any synchronization by applica-
tions.

Example of Using COBOL in a Multithreaded Environment


This example consists of a C main program that creates two COBOL threads, waits for
the COBOL threads to finish, then exits.

Sample Code for the Multithreading Example


The example has three code samples:
thrcob.c A C main program that creates the COBOL threads, waits for them to
finish, then exits.
subd.cbl A COBOL program that is run by the thread created by thrcob.c.
sube.cbl A second COBOL program that is run by the thread created by thrcob.c.

402 COBOL Set for AIX Programming Guide


Multithreading

The sample code for thrcob.c is shown in Figure 104.

/\ Creates COBOL threads, SUBD and SUBE.


Threads must be created with undetached state for join to work. \/

typedef int (\PFN)();


#include <pthread.h>
#include <stdio.h>
#include <setjmp.h>

extern int errno;


extern void \SUBD(void \);
extern void \SUBE(void \);

extern void _iwzCOBOLInit(int fcode, PFN StopFun, int \err_code, void \StopArg);
extern void _iwzCOBOLTerm(int fcode, int \err_code);

jmp_buf Jmpbuf;

int
StopFun(long \stoparg)
{
printf("Inside StopFun. Got stoparg = %d\n", \stoparg);
\stoparg = 123;
longjmp(Jmpbuf,1);
}

long StopArg = ð;

void
testrc(int rc, const char \s)
{
if (rc != ð){
printf("%s: Fatal error rc=%d\n",s,rc);
exit(-1);
}

Figure 104 (Part 1 of 2). Source Code for thrcob.c

Chapter 24. Preparing COBOL Programs for Multithreading 403


Multithreading

void
pgmy()
{
pthread_t t1, t2;
int rc;
long i;
long j;
void \r1, \r2;
pthread_attr_t attr;

_iwzCOBOLInit(1, StopFun, &rc, &StopArg);


printf( "_iwzCOBOLinit got %d\n",rc);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_UNDETACHED);

i = 2ððð;
rc = pthread_create( &t1, &attr, &SUBD, &i);
testrc(rc,"create 1");
j = 1ððð;
rc = pthread_create( &t2, &attr, &SUBE, &j);
testrc(rc,"create 2");
printf("threads are %x and %x\n",t1, t2);

rc = pthread_join(t1, &r1);
printf("join %x got %d\n",t1,rc);
rc = pthread_join(t2, &r2);
printf("join %x got %d\n",t2,rc);

_iwzCOBOLTerm(1, &rc);
printf( "_iwzCOBOLTerm got expect rc=ð, got rc=%d\n",rc);
}

main()
{
if (setjmp(Jmpbuf) ==ð) {
pgmy();
}
}

Figure 104 (Part 2 of 2). Source Code for thrcob.c

The sample code for subd.cbl is shown in Figure 105 on page 405.

404 COBOL Set for AIX Programming Guide


Multithreading

IDENTIFICATION DIVISION.
PROGRAM-ID. "subd".
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
DATA DIVISION.
LOCAL-STORAGE SECTION.
ð1 N2 PIC 9(8) comp-5 value ð.
\
LINKAGE SECTION.
ð1 N1 PIC 9(8) comp-5.
\
PROCEDURE DIVISION using by reference n1.
perform n1 times
DISPLAY "subd gets " n1 " " n2
compute n2 = n2 + 1
end-perform
DISPLAY "subd goback with " n1 " " n2
GOBACK.

Figure 105. Source Code for subd.cbl

The sample code for sube.cbl is shown in Figure 106.

IDENTIFICATION DIVISION.
PROGRAM-ID. "sube".
\
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
\
DATA DIVISION.
LOCAL-STORAGE SECTION.
ð1 N2 PIC 9(8) comp-5 value ð.
\
LINKAGE SECTION.
ð1 N1 PIC 9(8) comp-5.
\
PROCEDURE DIVISION using by reference n1.
perform n1 times
DISPLAY "sube gets " n1 " " n2
compute n2 = n2 + 1
end-perform
DISPLAY "sube goback with " n1 " " n2
GOBACK.

Figure 106. Source Code for sube.cbl

Compiling, Linking, and Running the Multithreading Example


To create and run the multithreading example, follow these steps:
1. To compile thrcob.c, enter xlc_r -c thrcob.c at an AIX shell prompt
2. To compile subd.cbl, enter cob2_r -qthread -c subd.cbl

Chapter 24. Preparing COBOL Programs for Multithreading 405


Multithreading

3. To compile sube.cbl, enter cob2_r -qthread -c sube.cbl


4. To generate the executable thrcob, enter cob2_r -o thrcob thrcob.o subd.o
sube.o
5. To run the program thrcob, enter thrcob

406 COBOL Set for AIX Programming Guide


National Language Support Considerations

Chapter 25. National Language Support Considerations


This chapter provides an overview of things you need to know about National Language
Support (NLS) when using IBM COBOL Set for AIX.

The NLS support of this product includes the support for multiple code pages. The
characters represented in a supported code page can be used in COBOL names, data
definitions, literals, and in common entries.

The following list summarizes the double-byte character set (DBCS) and extended
UNIX code (EUC) code page support:
Ÿ User-defined names
DBCS and EUC names are supported.
Ÿ Data type
DBCS data items (with PIC G or N) are supported only if the current code page is a
DBCS code page. DBCS data items are diagnosed as errors if the code page in
effect is an ASCII or EUC code page.
Ÿ Literal
DBCS literals are supported.
You can specify EUC constants as alphanumeric literals (such as to display fields).
However, no semantics sensitive to multi-byte EUC characters are supported.
Ÿ Comments
DBCS and EUC comments are supported.
Ÿ Collating sequence
Collating sequences for single-byte character set (ASCII and DBCS data are locale
sensitive: that is, based on the collating sequence indicated by the locale, except
for ASCII compares with a non-NATIVE collating sequence in effect).
This collating sequence rule applies to the single-byte characters whether the
single-byte characters are from an ASCII, DBCS, or EUC code page.
Since the ANSI COBOL language elements dictate the knowledge of the collating
sequence at compile time, it is expected that the locale setting in effect at the
compile time and at the application execution time are consistent.
Locale: A locale is a collection of data that encodes information about a cultural envi-
ronment. Localization is an action that establishes a cultural environment for an appli-
cation by selecting the active locale. Only one locale can be active at one time. The
active locale affects the behavior on the locale-sensitive interfaces for the entire
program. This is called the global locale model.

The current locale is set using the LANG environment variable.

 Copyright IBM Corp. 1996, 1998 407


National Language Support Considerations

Locales and Code Sets Supported on AIX


For information about locales, code sets, and converters on AIX, refer to AIX Version
4.1, General Programming Concepts; Writing and Debugging Programs, SC23-2533.

DBCS and EUC User-Defined Word Support


You can form user-defined words using double-byte and EUC characters.

Usage Notes
The maximum number of characters for a user-defined word with one or more multi-
byte characters is as follows:
15 for DBCS code page.
10 for IBM_eucJP, IBM_eucKR, and IBM_eucCN.
7 for IBM_eucTW.

A DBCS or EUC user-defined word can contain both multi-byte and single-byte charac-
ters. When a character exists in both single-byte and multi-byte forms, its single-byte
and multi-byte representations will not be regarded as equivalent. For example, “A”
represented in double-bytes will not be considered to match “A” represented in a single
byte.

Alphabet-names, class-names, condition-names, data-names, file-names, mnemonic-


names, record-names, and symbolic characters must contain at least one single-byte
alphabetic character or one multi-byte character.

A user-defined word containing multi-byte characters may not be continued.

Restrictions on Specific User-Defined Words


The IBM COBOL compiler supports the level-number user-defined word only when
represented in SBCS digits.

Support for the library-name, program-name, and text-name user-defined words with
DBCS or EUC depends on the DBCS or EUC name support of the platform. IBM
COBOL will allow double-byte or EUC characters in these names.

DBCS Literal Support


There are two literal types to represent double-byte character constants: N'dbcs charac-
ters' and G'dbcs characters'.

Additionally, you can specify any character in one of the supported code pages using
the alphanumeric literal syntax. However, such a literal is treated as alphanumeric in
COBOL language semantics (that is, semantics appropriated for single-byte characters).

The literal delimiters can be apostrophes or quotes depending on the APOST or QUOTE
compiler option setting.

408 COBOL Set for AIX Programming Guide


National Language Support Considerations

A non-numeric literal containing double-byte characters cannot be continued. The


maximum length of a N or G literal is 28 double-byte characters. The maximum length
of a N or G literal is limited only by the available space in Area B on a single source
line.

Figurative constant [ALL]SPACE and [ALL]SPACES represent space characters in SBCS


or DBCS.

The ALL literal represents all or part of the string generated by successive concat-
enations of the single-byte characters or double-byte characters comprising the literal.
The literal must be a non-numeric literal or a DBCS literal. The literal must not be a
figurative constant.

DBCS Data Type Support


The DBCS class and category are defined as shown in the following table.

Level of Item Class Category


Elementary Alphabetic Alphabetic
Numeric Numeric
Alphanumeric Numeric edited
Alphanumeric edited
Alphanumeric
DBCS DBCS
Nonelementary (Group) Alphanumeric Alphabetic
Numeric
Numeric edited
Alphanumeric edited
Alphanumeric
DBCS

If a data item is declared with PICTURE N or G, the selected locale must indicate a
DBCS code page. In all other cases, the PICTURE characters N and G and USAGE
DISPLAY-1 are flagged as errors.

Declaring DBCS Data


DBCS data is declared as follows:
PICTURE clause
A double-byte character position is represented by picture symbols N, G, or B.
A DBCS data item has the PICTURE character string with PICTURE symbols G, G and
B, or N. Each PICTURE symbol represents a DBCS character position. The number
of bytes occupied by each double-byte character is assumed to be two. That is,

Chapter 25. National Language Support Considerations 409


National Language Support Considerations

single-byte characters of a DBCS code page should not be included in a DBCS data
item.
Operations on DBCS strings not conforming to this rule might produce unpredictable
results, such as the truncation of a string at a byte position in the middle of a double-
byte character.
This rule will not be enforced at run time. For a code page with characters repres-
ented in double bytes, the following padding and truncation rules apply where
COBOL language semantics specify truncation or padding with spaces:
Ÿ Padding
For operations involving DBCS data items, the padding is done using the
double-byte space characters until the data area is filled. This is based on the
number of byte positions allocated for the data area.
Where the padding may not be in the multiple of the code page width (for
example, a group item moved to a DBCS data item), the padding is done with
single-byte space characters.
Ÿ Truncation
The truncation is done based on the size of the target data area on the byte
boundary of the end of that data area. It is the application program's responsi-
bility to ensure that such a truncation does not result in truncation of bytes
representing a partial double-type character.
USAGE clause
A DBCS data item is specified with USAGE DISPLAY-1. When you use PICTURE
symbol G, you must specify USAGE DISPLAY-1. When you use PICTURE symbol N,
USAGE DISPLAY-1 is implied and the USAGE clause may be omitted.

VALUE clause
The associated VALUE clause (if specified) must specify a DBCS literal or the figura-
tive constants SPACE OR SPACES.
Reference modification
For the purpose of handling reference modifications, each character in a DBCS data
item is considered to occupy the number of bytes corresponding to the code page
width (that is, 2).

DBCS Class Test


Kanji and DBCS class test are defined to be consistent with their IBM System/390 defi-
nitions. Both class tests are internally performed by converting the double-byte charac-
ters to the double-byte characters defined for IBM System/390. The converted
double-byte characters are tested for DBCS and Japanese graphic characters.

Kanji class test results in testing for valid Japanese graphic characters. This includes
Katakana, Hiragana, Roman, and Kanji character sets.

410 COBOL Set for AIX Programming Guide


National Language Support Considerations

The Kanji class test is done by checking the converted characters for X'41' - X'7E'
for the first byte and X'41' - X'FE' for the second byte plus the space character,
X'4040'.

DBCS class test results in testing for valid graphic characters for the code page.

The DBCS class test is done by checking the converted characters for X'41' - X'FE'
for both the first and second byte of each character plus the space character, X'4040'.

Collating Sequence
Considerations for DBCS and ASCII collating sequence are as described below. Any
comparison involving a group item will be handled based on the comparison of the byte
for byte positions in hex.

The following clauses in the SPECIAL-NAMES paragraph may be specified only if the
code page in effect is an ASCII code page:
Ÿ ALPHABET clause
Ÿ SYMBOLIC CHARACTER clause
Ÿ CLASS clause
These clauses, if specified with a DBCS or EUC code page in effect, will be diagnosed
and treated as comments.
DBCS Collating Sequence
Data items and literals of class DBCS can be used in a relation condition with any
relational operator. Each operand must be either of class DBCS, alphabetic, or
alphanumeric (elementary or group). Note that this allows, for example, a compar-
ison of a DBCS item with an alphanumeric item. No conversion or editing is done.
No distinction is made between items of category DBCS and items of category DBCS
edited.
DBCS comparisons are performed based on the rules for non-numeric comparisons.
The comparison is based on the locale setting for the collating sequence if the oper-
ands are elementary DBCS or alphanumeric data items.
The PROGRAM COLLATING SEQUENCE clause has no effect on comparisons involving
data items of class DBCS or DBCS literals.
ASCII Collating Sequence
The ANSI COBOL rules on the PROGRAM COLLATING SEQUENCE clause and the
COLLATING SEQUENCE clause on SORT and MERGE apply.

If the collating sequence in effect is NATIVE (which is default if neither the COLLATING
SEQUENCE clause nor the PROGRAM COLLATING SEQUENCE clause is specified),
the collating sequence is based on the locale setting. This applies to SORT or
MERGE statements as well as to the program collating sequence.

Note that the collating sequence impacts the processing of the alphabetic clause (for
example, literal-1 THRU literal-2), SYMBOLIC CHARACTERS specifications, and VALUE

Chapter 25. National Language Support Considerations 411


National Language Support Considerations

range specifications for Level 88 items as well as relation conditions and SORT and
MERGE statements.

Since the rules of the COBOL user-defined alphabet name and symbolic characters
assume a character-by-character collating sequence (not a collating sequence which
may depend on a sequence of multiple characters), the locale-sensitive collating is that
aspect that can be expressed by assigning a weight on each character in the code set.

Intrinsic Functions with Collating Sequence Sensitivity


The following intrinsic functions are dependent on the ordinal positions of characters.
These intrinsic functions are not supported for the DBCS data type (for example, sup-
ported for single-byte characters, alphabetic or numeric). For an ASCII code page,
these intrinsic functions are supported based on the collating sequence in effect. For a
DBCS or EUC code page, the ordinal positions of single-byte characters are assumed
to correspond to the hex representations of the single-byte characters. For example,
the ordinal positions for 'A' is 66 (X'41' + 1) and the ordinal position for '*' is 43 (X'2A' +
1).
Ÿ CHAR
Returns the character of the ordinal position given.
Ÿ MAX
Returns the contents of the argument that contains the maximum value. Note that
the arguments may be alphabetic or alphanumeric.
Ÿ ORD
Returns the ordinal position of the given character.
Ÿ ORD-MAX
Returns the highest ordinal position of the characters given. ORD-MAX with
numeric arguments are supported independent of the code page in effect.
Ÿ ORD-MIN
Returns the lowest ordinal position of the characters given. ORD-MIN with numeric
arguments are supported independent of the code page in effect.

Any comparisons involving a group item will be handled based on the comparison of
the byte-for-byte positions in hex.

Comments
Character strings that form comments may contain any characters, including DBCS and
EUC characters. A single DBCS or EUC character may not be split (and continued)
across multiple source lines.

412 COBOL Set for AIX Programming Guide


National Language Support Considerations

Messages Enabled for NLS


The following messages are NLS enabled and appropriate message text and formats
are used based on the locale setting:
Ÿ Compiler messages.
Ÿ Run-time messages.
Ÿ Compiler listing headers. This includes locale-sensitive date and time formats.
Ÿ Debugger user interface.

Cross-Reference Output Sequence


The cross-reference output is ordered in the collating sequence indicated by the locale
setting.

Locale Sensitivity
This product is sensitive to the locale setting for the following features:
Ÿ Code page selection
The locale in effect determines the code set for both compilation of source pro-
grams, including non-numeric literal values, and their execution. That is, the code
set used for compilation is based on the locale setting at compile time, and the
code set used for application program execution is based on the locale setting at
run time.
The EBCDIC code set is based on the current locale setting.
For information about locales, code sets, and converters on AIX, refer to AIX
Version 4.1, General Programming Concepts; Writing and Debugging Programs,
SC23-2533.
If more than one EBCDIC code set is applicable for the current locale, and you
want to use other than the default, then:
– Set the CHAR compiler option to EBCDIC; “CHAR” on page 151 discusses this
option.
– Set the EBCDIC_CODEPAGE to establish the EBCDIC code set applicable; see
page 131.
Ÿ Messages
This applies to the message text, the date and time format, and order for XREF for
the compiler listing output and to run-time message text. The compile-time locale
is used for compiler output, the run-time setting for run-time output.
Ÿ Collating sequence
Locale sensitivity for the collating sequence applies only when the collating
sequence is NATIVE; the locale has no impact on the collating sequence if
COLLSEQ(BIN) or COLLSEQ(EBCDIC) is in effect.

Chapter 25. National Language Support Considerations 413


National Language Support Considerations

The collating sequence for single-byte alphanumeric characters for the program
collating sequence is based on the compile-time or run-time locale. If the PRO-
GRAMMING COLLATING SEQUENCE clause is specified in the source program, the
collating sequence is set at compile-time and is used regardless of the run-time
locale. If the collating sequence is not set using this clause, but is set using the
COLLSEQ compiler option, the run-time locale takes precedence.

The collating sequence for SORT or MERGE statements is always based on the
run-time locale.
The run-time locale-based collating sequence is always applicable to DBCS and
EUC data, independent of the COBOL source-level collating sequence specification
(which applies to single-byte alphanumeric data), except for comparisons of literals.
Comparisons of DBCS literals are based on the compile-time locale. Thus, DBCS
literals should not be used in the source program within a statement with an
implied relational condition between two DBCS literals (such as VALUE G literal1
THRU G literal2) unless the intended run-time locale is the same as the compile-
time locale.
The compile-time and run-time locale settings are assumed to be the same for
other uses of the collating sequence.

The following are not affected by the locale setting, as the ANSI COBOL Standard
defines specific COBOL language elements for controlling these items:
Ÿ Decimal point and numeric separator
Ÿ Currency sign

414 COBOL Set for AIX Programming Guide


Preinitialization

Chapter 26. Pre-initializing the COBOL Run-Time Environment


Pre-initialization allows an application to initialize the COBOL run-time environment
once, perform multiple executions using the environment, and then explicitly terminate
the environment. Pre-initialization is used to invoke COBOL programs multiple times
from a non-COBOL (for example, C or C++) environment.
Note: Pre-initialization is not supported under CICS.

The pre-initialization has two primary benefits:


Ÿ Keeps the COBOL environment ready for program calls
Since the COBOL run unit is not terminated on return from first COBOL program in
the run unit, the COBOL programs invoked from a non-COBOL environment can
be invoked in its last-used state.
Ÿ Performance
Creating and taking down the COBOL run-time environment repeatedly uses a
great deal of overhead and can slow down your application's performance.

Use pre-initialization services for multilanguage applications where non-COBOL pro-


grams need to use a non-COBOL program in its last-used state. For example, a file
may be opened on a first call to a COBOL program, and the invoking program expects
subsequent calls to that program to find the file left open.

Use the interfaces described below to initialize and terminate a persistent COBOL run-
| time environment. Any DLL that contains a COBOL program used in a pre-initialized
| environment cannot be deleted until the pre-initialized environment is terminated.

If you plan to run your program in an OS/390 or VM environment, use the pre-
initialization interfaces described in IBM Language Environment for OS/390 & VM Pro-
gramming Guide.

Initialize Persistent COBOL Environment


Syntax
55──call──Init_routine──(──function_code──,──routine──,──error_code────5
5──,──token──)────────────────────────────────────────────────────────5%

call
Invocation of Init_routine, using language elements appropriate to the language
from which the call is being made.

Init_routine
The name of the initialization routine: _iwzCOBOLInit or IWZCOBOLINIT

 Copyright IBM Corp. 1996, 1998 415


Terminate COBOL Environment

function_code (input) — A 4-byte binary number, passed by value


function_code can be:
1 The first COBOL program invoked following this function invocation is
treated as a subprogram.

routine (input)
Address of the routine to be invoked if the run unit terminates. The token argu-
ment passed to this function will be passed on to the run unit termination exit
routine. This routine, when invoked on the run unit termination, must not return to
the invoker of the routine but rather do a longjmp() or exit().

error_code (output) — A 4-byte binary number


error_code can be:
0 pre-initialization was successful.
1 pre-initialization failed.

token (input)
4 byte token to be passed on to the exit routine specified in the earlier argument
when that routine is invoked on the run unit termination.

Terminate Pre-initialized COBOL Environment


Syntax
55──call──Term_routine──(──function_code──,──error_code──)────────────5%

call
Invocation of Term_routine, using language elements appropriate to the language
from which the call is being made.

Term_routine
The name of the initialization routine: _iwzCOBOLTerm or IWZCOBOLTERM

function_code (input), a 4-byte binary number, passed by value


function_code can be:
1 Clean up the pre-initialized COBOL run-time environment as if a
COBOL STOP RUN statement had been performed; for example, all
COBOL files are closed. However, the control returns to the caller of
this service, not to the invoker of the COBOL main program; the
routine named in the call to the pre-initialization routine is not invoked.
(See Figure 108 on page 418. StopFun does not get called.)

error_code (output), a 4-byte binary number


error_code can be:
0 termination was successful.
1 termination failed.

416 COBOL Set for AIX Programming Guide


Example of Pre-initializing

The first COBOL program called following the invocation of the pre-inialization routine is
treated as a subprogram. Thus, a GOBACK from this (initial) program does not trigger
run-unit termination semantics (such as the closing of files). Note that the run unit ter-
mination (such as with STOP RUN) does free the pre-initialized COBOL environment
prior to the invocation of the run unit exit routine.
If Not Active: If your program invokes the termination routine and the COBOL envi-
ronment is not already active, the termination routine invocation has no effect on the
execution and the control is returned to the invoker with an error code of 0.

Example of Pre-initializing the COBOL Environment


Figure 107 illustrates how the pre-initialized COBOL environment works. The example
shows a C program initializing the COBOL environment, calling COBOL programs, then
terminating the COBOL environment.

┌─5 C_PgmY
C_PgmX │ ┌────────────────────────────────┐
┌─────────────────────────┐ │ │ ... │
│ ... │ │ │ _iwzCOBOLInit ─┼──┐
│ if (setjmp(here) !=ð │ │ │ (1, C_StopIt, fdbk, here) │ │
│ { │ │ │ ... │ │
┌──┼──5 printf("STOP RUNed") │ │ │ COBOL-PgmA() ─┐ │ │
│ │ ... │ │ │ ... │ │ │
│ │ ... │ │ └───────────────┼────────────────┘ │
│ │ } │ │ │ 6
│ │ printf("setjmp done") │ │ COBOL-PgmA %──┘ _iwzCOBOLInit
│ │ C_PgmY(here) ─────────┼─┘ ┌────────────────────┐ ┌──────────────┐
│ │ ... │ │ ... │ │ ... │
│ └─────────────────────────┘ │ CALL COBOL-PgmB ─┼─┐ └──────────────┘
│ │ ... │ │
│ └────────────────────┘ │
│ COBOL-PgmB %─────────┘
│ ┌────────────┐
│ │ ... │
│ │ STOP RUN ──┼─┐
│ └────────────┘ │
│ │
│ C_StopIt %────────────────────┘
│ ┌───────────────┐
│ │ ... │
└───────────────┤ longjmp(here) │
└───────────────┘

Figure 107. Illustration of Pre-Initialized COBOL Environment

The following example shows the use of COBOL pre-initialization. A C main program
calls the COBOL program XIO several times. The first call to XIO opens the file, the
second call writes one record, and so on. The final call closes the file. The C program
then uses C-stream I/O to open and read the file. It assumes the use of VisualAge for
C++.

To test and run the program, enter the following commands from a command shell:

Chapter 26. Pre-initializing the COBOL Run-Time Environment 417


Example of Pre-initializing

xlc -c testinit.c
cob2 testinit.o xio.cbl
a.out

The result is:


_iwzCOBOLinit got ð
xio entered with x=ðððððððððð
xio entered with x=ððððððððð1
xio entered with x=ððððððððð2
xio entered with x=ððððððððð3
xio entered with x=ððððððððð4
xio entered with x=ðððððððð99
StopArg=ð
_iwzCOBOLTerm expects rc=ð and got rc=ð
FILE1 contains ----
11111
22222
33333
---- end of FILE1
Note that in this example, the run unit was not terminated by a COBOL STOP RUN; it
was terminated when the main program called _iwzCOBOLTerm.

The following C program is in the file testinit.c:

#ifdef _AIX
typedef int (\PFN)();
#define LINKAGE
#else
#include <os2.h>
#define LINKAGE _System
#endif

#include <stdio.h>
#include <setjmp.h>

Figure 108 (Part 1 of 2). Source Code for testinit.c

418 COBOL Set for AIX Programming Guide


Example of Pre-initializing

extern void _iwzCOBOLInit(int fcode, PFN StopFun, int \err_code, void \StopArg);
extern void _iwzCOBOLTerm(int fcode, int \err_code);
extern void LINKAGE XIO(long \k);

jmp_buf Jmpbuf;
long StopArg = ð;

int LINKAGE
StopFun(long \stoparg)
{
printf("inside StopFun\n");
\stoparg = 123;
longjmp(Jmpbuf,1);
}

main()
{
int rc;
long k;
FILE \s;
int c;

if (setjmp(Jmpbuf) ==ð) {
_iwzCOBOLInit(1, StopFun, &rc, &StopArg);
printf( "_iwzCOBOLinit got %d\n",rc);
for (k=ð; k <= 4; k++) XIO(&k);
k = 99; XIO(&k);
}
else printf("return after STOP RUN\n");
printf("StopArg=%d\n", StopArg);
_iwzCOBOLTerm(1, &rc);
printf("_iwzCOBOLTerm expects rc=ð and got rc=%d\n",rc);
printf("FILE1 contains ---- \n");
s = fopen("FILE1", "r");
if (s) {
while ( (c = fgetc(s) ) != EOF ) putchar(c);
}
printf("---- end of FILE1\n");
}

Figure 108 (Part 2 of 2). Source Code for testinit.c. A C program that shows the use of pre-
initialization.

Chapter 26. Pre-initializing the COBOL Run-Time Environment 419


Example of Pre-initializing

The following COBOL program is in the file xio.cbl:

IDENTIFICATION DIVISION.
PROGRAM-ID. xio.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT file1 ASSIGN TO FILE1
ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS file1-status.

DATA DIVISION.
FILE SECTION.
FD FILE1.
ð1 file1-id pic x(5).

WORKING-STORAGE SECTION.
ð1 file1-status pic xx value is zero.

LINKAGE SECTION.
\
ð1 x PIC S9(8) COMP-5.

PROCEDURE DIVISION using x.

display "xio entered with x=" x


if x = ð then
OPEN output FILE1
end-if

Figure 109 (Part 1 of 2). Source Code for xio.cbl

420 COBOL Set for AIX Programming Guide


Example of Pre-initializing

if x = 1 then
MOVE ALL "1" to file1-id
WRITE file1-id
end-if
if x = 2 then
MOVE ALL "2" to file1-id
WRITE file1-id
end-if
if x = 3 then
MOVE ALL "3" to file1-id
WRITE file1-id
end-if
if x = 99 then
CLOSE file1
end-if
GOBACK.

Figure 109 (Part 2 of 2). Source Code for xio.cbl. A COBOL program that shows the use of
pre-initialization.

Chapter 26. Pre-initializing the COBOL Run-Time Environment 421


Simplifying Coding

Chapter 27. Productivity and Tuning Techniques


This chapter provides techniques to improve programmer productivity using built-in
functions and services, and contains guidelines on performance optimization to help
you make the most of your COBOL applications.

Simplifying Complex Coding and Other Programming Tasks


By using COBOL intrinsic functions and Language Environment callable services, you
can avoid having to code a lot of arithmetic or other complex tasks.

Intrinsic Functions
COBOL provides various string- and number-manipulation capabilities that can help you
simplify your coding. For more information, see “Numeric Intrinsic Functions” on
page 39.

Date and Time Callable Services


With the date and time callable services, you can get the current local time and date in
several formats, as well as perform date and time conversions. Two callable services,
CEEQCEN and CEESCEN, provide a predictable way to handle 2-digit years, such as
91 for 1991 or 02 for 2002.

The following lists the date and time callable services available:
| CEECBLDY Converts character date value to COBOL integer date format. Day one
is 01 January 1601 and the value is incremented by one for each subse-
quent day. This service is similar to CEEDAYS, except that it provides
| an answer in COBOL integer date format, so that it is compatible with
ANSI COBOL intrinsic functions. The returned value from this service
should not be used with other date and time callable services.
CEEDATE Converts dates in the Lilian format back to character values.
CEEDATM Convert number of seconds to character timestamp.
CEEDAYS Convert character date values to the Lilian format. Day one is 15
October 1582 and the value is incremented by one for each subsequent
day.
CEEDYWK Provides day of week calculation.
CEEGMT Gets current Greenwich Mean Time (date and time).
CEEGMTO Gets difference between Greenwich Mean Time and local time.
CEEISEC Converts binary year, month, day, hour, second, and millisecond to a
number representing the number of seconds since 00:00:00 15 October
1582.
CEELOCT Gets current date and time.
| CEEQCEN Queries the callable services century window.

422  Copyright IBM Corp. 1996, 1998


Simplifying Coding

| CEESCEN Sets the callable services century window.


CEESECI Converts a number representing the number of seconds since 00:00:00
15 October 1582 to seven separate binary integers representing year,
month, day, hour, minute, second, and millisecond.
CEESECS Converts character timestamps (a date and time) to the number of
seconds since 00:00:00 15 October 1582.
CEEUTC Same as CEEGMT.

For details on individual date and time callable services, see Appendix E, “Date and
Time Callable Services Reference” on page 484.

All of the above date and time callable services allow source code compatibility with
COBOL for OS/390 & VM and COBOL for MVS & VM. There are, however, significant
differences in the way conditions are handled. See “Condition Handling” on page 424
for details.

How to Invoke Date and Time Callable Services


To invoke a date and time callable service, use a CALL statement with the correct
parameters for that particular service, for example:
CALL "CEEDATE" using argument, format, result, feedback-code.
You define the variables in the CALL statement in the DATA DIVISION of your program
with the data definitions required by the particular function you are calling:
77 argument pic s9(9) comp.
ð1 format.
ð5 format-length pic s9(4) comp.
ð5 format-string pic x(8ð).
77 result pic x(8ð).
77 feedback-code pic x(12) display.

In this example, the date and time callable service CEEDATE converts a number
representing a Lilian date in the variable argument to a date in character format which is
written to the variable result. The format of the conversion is controlled by the picture
string contained in the variable format. Information about the success or failure of the
call is returned in the variable feedback-code.

All of the date and time callable services allow the specification of a feedback code
parameter which is optional. Specify OMITTED for this parameter if you do not want the
date and time callable service to return information about the success or failure of the
call. However, if omitting this parameter, the program will abend if the callable service
does not complete successfully. See “Condition Handling” on page 424 for additional
information.

When calling a date and time callable service and you specify OMITTED for the feed-
back code, the RETURN-CODE special register is set to 0 if the service is successful but
is not altered if the service is unsuccessful. If the feedback code is not OMITTED, the
RETURN-CODE special register is always set to 0 regardless of whether the service
completed successfully.
Chapter 27. Productivity and Tuning Techniques 423
Simplifying Coding

For a description of the OMITTED phrase, see IBM COBOL Language Reference.

The date and time callable services must be invoked using the standard system linkage
convention. This can be achieved by either compiling the program using the
CALLINT(SYSTEM) compiler option (this is the default), or by using the
>>CALLINTERFACE SYSTEM compiler-directing statement.
| Note: The CALL statements used to invoke the date and time callable services must
| use a literal for the program name as opposed to an identifier. See IBM COBOL Lan-
guage Reference for details on the CALL statement.

Condition Handling
There is a significant difference in the condition handling between COBOL Set for AIX
and IBM Language Environment on the host. COBOL Set for AIX adheres to the native
COBOL condition handling scheme and does not provide the level of support in Lan-
guage Environment. If a feedback token is passed as an argument, it will simply be
returned after the appropriate information has been filled in. The caller can then
examine the contents and perform any actions, if necessary. The condition will not be
signaled. If a date and time callable service is called with the OMITTED phrase as a
substitute for the feedback code, the program will abend if the service does not com-
plete successfully.

A feedback token contains feedback information in the form of a condition token. The
condition token set by the service will be returned to the calling routine, indicating
whether the service was completed successfully or not. COBOL Set for AIX uses the
same feedback token as Language Environment which is defined as follows:
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
| ð4 Severity PIC S9(4) COMP.
| ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
| ð4 Class-Code PIC S9(4) COMP.
| ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
| ð2 I-S-Info PIC S9(9) COMP.

424 COBOL Set for AIX Programming Guide


Simplifying Coding

The following describes what each field will contain and identifies any differences with
IBM Language Environment on the host:
Severity This is the severity number with the following possible values:
0 Information only (or, if the entire token is zero, no information).
1 Warning - service completed, probably correctly.
2 Error detected - correction attempted; service completed, perhaps
incorrectly.
3 Severe error - service not completed.
4 Critical error - service not completed.
Msg-No This is the associated message number. See Appendix F, “Run-Time
Messages” on page 532 for additional information.
Case-Sev-Ctl This field will always contain the value 1.
Facility-ID This field will always contain the characters CEE.
I-S-Info This field will always contain the value 0.

A sample COPY file is provided which defines the condition tokens. The file name is
CEEIGZCT.CPY. The condition tokens contained herein are equivalent to those pro-
vided with Language Environment, except that character representations are in ASCII
instead of EBCDIC. This must be taken into account if comparing the condition tokens
with Language Environment.

The descriptions of the individual callable services include a listing of the possible sym-
bolic feedback codes that might be returned in the feedback code output field specified
on invocation of the service. In addition to these, the symbolic feedback code CEE0PD
might be returned for any callable service. See message IWZ0813S for details.

All date and time callable services are based on the Gregorian calendar. Date vari-
ables associated with this calendar have architectural limits. These limits are:
Starting Lilian date The beginning of the Lilian date range is Friday 15 October
1582, the date of adoption of the Gregorian calendar. Lilian
dates preceding this date are undefined. Therefore:
Ÿ Day zero is 00:00:00 14 October 1582
Ÿ Day one is 00:00:00 15 October 1582
All valid input dates must be after 00:00:00 15 October 1582.
End Lilian date The end Lilian date range is set to 31 December 9999. Lilian
dates following this date are undefined. The reason for this limit
is a 4-digit year.

Picture Character Terms and Strings


Picture character terms and strings are used to define the format of a date and/or time
field used by several of the date and time callable services. A picture string is a tem-
plate that indicates the format of the input of the data or the desired format of the

Chapter 27. Productivity and Tuning Techniques 425


Simplifying Coding

output. Figure 110 on page 426 and Figure 111 on page 427 define the supported
picture character terms and string values.

Figure 110 (Page 1 of 2). Picture Character Terms Used in Picture Strings for Date and Time Services
Picture
Terms Explanations Valid Values Notes
Y 1-digit year 0-9 Y valid for output only.
YY 2-digit year 00-99 YY assumes range set by
YYY 3-digit year 000-999 CEESCEN.
ZYY 3-digit year within era 1-999 YYY/ZYY used with <JJJJ>, <CCCC>
YYYY 4-digit year 1582-9999 and <CCCCCCCC>.
<JJJJ> Japanese era name in DBCS Heisei Affects YY field: if <JJJJ> speci-
characters (X'95BD9ðAC') fied, YY means the year within
Showa Japanese era, for example, 1988
(X'8FBA9861') equals Showa 63. See example
Taisho in Figure 111 on page 427.
(X'91E59ðB3')
Meiji
(X'96BE8EA1')
<CCCC> Republic of China (ROC) era MinKow Affects YY field: if <CCCC> speci-
<CCCCCCCC> name in DBCS characters (X'8D8196CD') fied, YY means the year within
ChuHwaMinKow ROC era, for example, 1988
(X'8C839ADC8D8196CD') equals Minkow 77. See example
in Figure 111 on page 427.
MM 2-digit month 01-12
ZM 1- or 2-digit month 1-12 For output, leading zero sup-
pressed. For input, ZM treated as
MM.
RRRR Roman numeral month I␣␣␣-XII␣ (Left justified) For input, source string is folded
RRRZ to uppercase. For output, upper-
case only. I=Jan, II=Feb, ...,
XII=Dec.
MMM 3-char month, uppercase JAN-DEC For input, source string always
Mmm 3-char month, mixed case Jan-Dec folded to uppercase. For output,
MMMM...M 3-20 char mo., uppercase JANUARY␣␣-DECEMBER␣ M generates uppercase and m gen-
Mmmm...m 3-20 char mo., mixed case January␣␣-December␣ erates lowercase. Output is
MMMMMMMMMZ trailing blanks suppressed JANUARY-DECEMBER padded with blanks (␣) (unless Z
Mmmmmmmmmz trailing blanks suppressed January-December specified) or truncated to match
the number of Ms, up to 20.
DD 2-digit day of month 01-31 For output, leading zero is always
ZD 1- or 2-digit day of mo. 1-31 suppressed. For input, ZD treated
DDD Day of year (Julian day) 001-366 as DD.
HH 2-digit hour 00-23
ZH 1- or 2-digit hour 0-23 For output, leading zero sup-
pressed. For input, ZH treated as
HH. If AP specified, valid values
are 01-12.
MI Minute 00-59
SS Second 00-59
9 Tenths of a second 0-9 No rounding.
99 Hundredths of a second 00-99
999 Thousandths of a second 000-999

426 COBOL Set for AIX Programming Guide


Simplifying Coding

Figure 110 (Page 2 of 2). Picture Character Terms Used in Picture Strings for Date and Time Services
Picture
Terms Explanations Valid Values Notes
AP AM/PM indicator AM or PM AP affects HH/ZH field. For input,
ap am or pm source string always folded to
A.P. A.M. or P.M. uppercase. For output, AP gener-
a.p. a.m. or p.m. ates uppercase and ap generates
lowercase.
W 1-char day-of-week S, M, T, W, T, F, S For input, Ws are ignored. For
WWW 3-char day, uppercase SUN-SAT output, W generates uppercase
Www 3-char day, mixed case Sun-Sat and w generates lowercase.
WWW...W 3-20 char day, uppercase SUNDAY␣␣␣-SATURDAY␣ Output padded with blanks
Www...w 3-20 char day, mixed case Sunday␣␣␣-Saturday␣ (unless Z specified) or truncated
WWWWWWWWWZ Trailing blanks suppressed SUNDAY-SATURDAY to match the number of Ws, up to
Wwwwwwwwwz Trailing blanks suppressed Sunday-Saturday 20.
All others Delimiters X'01'-X'FF' For input, treated as delimiters
(X'00' is reserved for “internal” between the month, day, year,
use by the date and time callable hour, minute, second, and fraction
services) of a second. For output, copied
exactly as is to the target string.
Note:
Blank characters are indicated by the symbol ␣.

Figure 111 (Page 1 of 2). Examples of Picture Strings Recognized by Date and Time Services
Picture Strings Examples Notes
YYMMDD 880516
YYYYMMDD 19880516
YYYY-MM-DD 1988-05-16 1988-5-16 would also be valid input.
<JJJJ> YY.MM.DD Showa 63.05.16 Showa is a Japanese Era name. Showa 63
equals 1988.
<CCCC> YY.MM.DD MinKow 77.05.16 MinKow is an ROC Era name. MinKow 77
equals 1988.
MMDDYY 050688
MM/DD/YY 05/06/88
ZM/ZD/YY 5/6/88
MM/DD/YYYY 05/06/1988
MM/DD/Y 05/06/8 1-digit year format (Y) valid for output only
DD.MM.YY 09.06.88
DD-RRRR-YY 09-VI -88
DD MMM YY 09 JUN 88
DD Mmmmmmmmmm YY 09 June 88
ZD Mmmmmmmmmz YY 9 June 88 Z suppresses zeros/blanks
Mmmmmmmmmz ZD, YYYY June 9, 1988
ZDMMMMMMMMzYY 9JUNE88
YY.DDD 88.137 Julian date
YYDDD 88137
YYYY/DDD 1988/137

Chapter 27. Productivity and Tuning Techniques 427


Simplifying Coding

Figure 111 (Page 2 of 2). Examples of Picture Strings Recognized by Date and Time Services
Picture Strings Examples Notes
YYMMDDHHMISS 880516204229 Timestamp—valid only for CEESECS and
YYYYMMDDHHMISS 19880516204229 CEEDATM. If used with CEEDATE, time
YYYY-MM-DD HH:MI:SS.999 1988-05-16 20:42:29.046 positions are filled with zeros. If used with
WWW, ZM/ZD/YY HH:MI AP MON, 5/16/88 08:42 PM CEEDAYS, HH, MI, SS, and 999 fields are
Wwwwwwwwwz, DD Mmm YYYY, Monday, 16 May 1988, 8:42 PM ignored.
ZH:MI AP
Note: Lowercase characters must be used only for alphabetic picture terms.

Figure 112. Japanese Eras Used by Date/Time Services when <JJJJ> Specified
First Date of Era Name in Japanese
Japanese Era Era Name DBCS Code Valid Year Values
1868-09-08 Meiji X'96BE8EA1' 01-45
1912-07-30 Taisho X'91E59ðB3' 01-15
1926-12-25 Showa X'8FBA9861' 01-64
1989-01-08 Heisei X'95BD9ðAC' 01-999 (01 = 1989)

Figure 113. Republic of China Eras Used by Date/Time Services when <CCCC> or <CCCCCCCC> Specified
First Date of Era Name in Chinese
ROC Era Era Name DBCS Code Valid Year Values
1912-01-01 MinKow X'96BE8EA1' 01-999 (77 = 1988)
ChuHwaMinKow X'8C839ADC8D8196CD'

Performing Calculations
The date and time callable services store dates as fullword binary integers and
timestamps as doubleword floating-point values, formats that permit you to perform
arithmetic calculations on date and time values in a simple and efficient manner. This
eliminates the need to write special subroutines that use services outside of the lan-
guage library for your application in order to perform these calculations. The following
is a generic example of how you can use date and time callable services to convert a
date to a different format and perform a simple calculation on the formatted date:
CALL CEEDAYS USING dateof_hire, 'YYMMDD', doh_lilian, fc.
CALL CEELOCT USING todayLilian, today_seconds, today_Gregorian, fc.
COMPUTE servicedays = today_Lilian - doh_Lilian.
COMPUTE serviceyears = service_days / 365.25.

In the example, you want to calculate the number of years of service for an employee
in your organization, and are using the original date of hire in the format YYMMDD to
make the calculations. Use the CEEDAYS (Convert Date to Lilian Format) service to
convert these dates to a Lilian format.

428 COBOL Set for AIX Programming Guide


Simplifying Coding

The CEELOCT (Get Current Local Time) service is called next to get the current local
time. doh_Lilian is then subtracted from today_Lilian (the number of days from the
beginning of the Gregorian calendar to the current local time) to calculate the employ-
ee's total number of days of employment. The final calculation divides that number by
365.25 to get the number of service years.

The Century Window Concept


To process 2-digit years in the year 2000 and beyond, the date and time callable ser-
vices employ a sliding scheme by which all 2-digit years are assumed to lie within a
100-year interval starting 80 years before the current system date:
1917 1997 2ð16
│ │ │
└───────────────────────┼──────────┘

System Date

One hundred years, in 1997 spanning from 1917 to 2016, is the default century window
for the date and time callable services. For example, in 1997 years 17 through 99 are
recognized as 1917-1999, and years 00 through 16 are recognized as 2000-2016. In
1998, years 18 through 99 are recognized as 1918-1999, and years 00 through 17 are
recognized as 2000-2017.

By year 2080, all 2-digit years would be recognized as 20xx. In 2081, 00 would be
recognized as year 2100.

Some applications may need to set up a different 100-year interval. For example,
banks often deal with 30-year bonds, which could be due 01/31/20. The CEESCEN
callable service (see Appendix E, “Date and Time Callable Services Reference” on
page 484) allows you to change the century window.

A companion service, CEEQCEN, queries the current century window. This allows a
subroutine, for example, to use a different interval for date processing than the parent
routine. Before returning, the subroutine would reset the interval back to the way it was
previously, as shown in Figure 114 on page 430.

Chapter 27. Productivity and Tuning Techniques 429


Simplifying Coding

.
.
.
WORKING-STORAGE SECTION
77 OLDCEN PIC S9(9) COMP.
77 TEMPCEN PIC S9(9) COMP.
77 QCENFC PIC X(12).

77 SCENFC1 PIC X(12).


77 SCENFC2 PIC X(12).

PROCEDURE DIVISION.

\\ Call CEEQCEN to retrieve and save current century window


CALL "CEEQCEN" USING OLDCEN , QCENFC.

\\ Call CEESCEN to temporarily change century window to 3ð


MOVE 3ð TO TEMPCEN.
CALL "CEESCEN" USING TEMPCEN , SCENFC1.

\\ Perform date processing with 2-digit years...


.
.
.
\\ Call CEESCEN again to reset century window
CALL "CEESCEN" USING OLDCEN , SCENFC2.

GOBACK.

Figure 114. Example of Querying and Changing the Century Window

Example Using Date and Time Callable Services


Many callable services offer the COBOL programmer entirely new function that would
require extensive coding using previous versions of COBOL. Two such services are
CEEDAYS and CEEDATE, which you can use effectively when you want to format
dates for output.

Figure 115 on page 431 shows a sample COBOL program that uses date and time
callable services to format and display a date from the results of a COBOL ACCEPT
statement.

430 COBOL Set for AIX Programming Guide


Optimization

CBL QUOTE
ID DIVISION.
PROGRAM-ID. HOHOHO.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ FUNCTION: DISPLAY TODAY'S DATE IN THE FOLLOWING FORMAT: \
\ WWWWWWWWW, MMMMMMMM DD, YYYY \
\ \
\ For example: MONDAY, MARCH 1ð, 1997 \
\ \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.

ð1 CHRDATE.
ð5 CHRDATE-LENGTH PIC S9(4) COMP VALUE 1ð.
ð5 CHRDATE-STRING PIC X(1ð).
ð1 PICSTR.
ð5 PICSTR-LENGTH PIC S9(4) COMP.
ð5 PICSTR-STRING PIC X(8ð).

77 LILIAN PIC S9(9) COMP.


77 FORMATTED-DATE PIC X(8ð).

PROCEDURE DIVISION.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\ USE DATE/TIME CALLABLE SERVICES TO PRINT OUT \
\ TODAY'S DATE FROM COBOL ACCEPT STATEMENT. \
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
ACCEPT CHRDATE-STRING FROM DATE.

MOVE "YYMMDD" TO PICSTR-STRING.


MOVE 6 TO PICSTR-LENGTH.
CALL "CEEDAYS" USING CHRDATE , PICSTR , LILIAN , OMITTED.

MOVE " WWWWWWWWWZ, MMMMMMMMMZ DD, YYYY " TO PICSTR-STRING.


MOVE 5ð TO PICSTR-LENGTH.
CALL "CEEDATE" USING LILIAN , PICSTR , FORMATTED-DATE ,
OMITTED.

DISPLAY "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\".
DISPLAY FORMATTED-DATE.
DISPLAY "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\".

STOP RUN.

Figure 115. Example with Date and Time Callable Services

Optimization

Chapter 27. Productivity and Tuning Techniques 431


Optimization

The OPTIMIZE Compiler Option


This section discusses the benefits of the OPTIMIZE compiler option as well as other
compiler features affecting optimization.

The COBOL optimizer is activated when you use the OPTIMIZE compiler option. The
purpose of the OPTIMIZE compiler option is to do the following:
Ÿ Eliminate unnecessary transfers of control or simplify inefficient branches, including
those generated by the compiler that are not evident from looking at the source
program.
Ÿ Simplify the compiled code for a CALL statement to a contained (nested) program.
Where possible, the optimizer places the statements inline, eliminating the need for
linkage code. This optimization, known as procedure integration, is further dis-
cussed in “Contained Program Procedure Integration.” If procedure integration
cannot be done, the optimizer uses the simplest linkage possible (perhaps as few
as two instructions) to get to and from the called program.
Ÿ Eliminate duplicate computations (such as subscript computations and repeated
statements) that have no effect on the results of the program.
Ÿ Eliminate constant computations by performing them when the program is com-
piled.
Ÿ Eliminate constant conditional expressions.
Ÿ Aggregate moves of contiguous items (such as those that often occur with the use
of MOVE CORRESPONDING) into a single move. Both the source and target must
be contiguous for the moves to be aggregated.
Ÿ The FULL suboption requests that the compiler discard any unreferenced data
items from the DATA DIVISION, and suppress generation of code to initialize these
data items to their VALUE clauses.

To see how the optimizer works on your program, compile it with and without the OPTI-
MIZE option and then compare the generated code. (Use the LIST compiler option to
request the assembler language listing of the generated code.)

For unit testing your programs, you might find it easier to debug code that has not been
optimized. But when the program is ready for final test, specify OPTIMIZE, so that the
tested code and the production code are identical. You might also want to use the
option during development, if a program is used frequently without recompilation.
However, the overhead for OPTIMIZE might outweigh its benefits if you re-compile fre-
quently, unless you are using the assembler language expansion (LIST option) to fine
tune your program.

Contained Program Procedure Integration


Contained program procedure integration is the process where a CALL to a contained
program is replaced by the program code. The advantage here is that the resulting
program runs faster without the overhead of CALL linkage and with more linear control
flow.

432 COBOL Set for AIX Programming Guide


Compiler Options

Program Size: If the contained programs are invoked by several CALL statements and
replace each such CALL statement, the program may become larger. The optimizer
limits this increase to no more than 50 percent, after which it no longer uses procedure
integration. The optimizer then chooses the next best optimization for the CALL state-
ment; the linkage overhead can be as few as two instructions.

Unreachable Code Elimination: As a result of procedure integration, one contained


program might be repeated several times. As further optimization proceeds on each
copy of the program, portions might be found to be unreachable, depending on the
context into which the code was copied.

Other Compiler Features that Affect Optimization


Another compiler feature that might have a significant influence on the effects of the
optimizer option is the USE FOR DEBUGGING ON ALL PROCEDURES statement.

The ON ALL PROCEDURES option of the USE FOR DEBUGGING statement generates
extra code at each transfer to every procedure name. It can be very useful for debug-
ging, but can make the program significantly larger as well as substantially inhibit opti-
mization.

Additionally, compiler options can also have an effect (see “Compiler Options” for
details).

Compiler Options
You might have a customized system that requires certain options for optimum perform-
ance. Check with your systems programmer to ensure that installed options are not
required before changing defaults. You can see what your system defaults are by
issuing ERRMSG. For instructions on issuing ERRMSG, see “Generating a List of All
Compiler Error Messages” on page 145.

The tuning methods and performance information discussed here are intended to help
you select from various COBOL options for compiling your programs.

Important

Make sure that COBOL serves your needs. Please confer with system program-
mers on how you should tune your COBOL programs. Doing so will ensure that
the options you choose are appropriate for programs being developed at your site.

A brief description of each item is followed by performance advantages and disadvan-


tages, reference information, and usage notes where applicable. Refer to specified
pages for additional information.
DYNAM The DYNAM compiler option dynamically loads subprograms invoked
through the CALL statement at run time.

Chapter 27. Productivity and Tuning Techniques 433


Compiler Options

Performance advantages
Using DYNAM means easier subprogram maintenance because
the application will not have to be link-edited again if the sub-
program is changed.
When using the DYNAM option, you can free virtual storage
that is no longer needed by issuing the CANCEL statement.
Performance disadvantages
You pay a slight performance penalty using DYNAM because
the call must go through a Language Environment routine.
Reference information
For a description of the DYNAM option, see “DYNAM” on
page 156.
OPTIMIZE Use the OPTIMIZE compiler option to ensure your code is optimized for
better performance.
Performance advantages
Generally results in more efficient run-time code.
Performance disadvantages
OPTIMIZE requires more processing time for compiles than
NOOPTIMIZE.

Reference information
For further description of OPTIMIZE, see “The OPTIMIZE Com-
piler Option” on page 432. See “OPTIMIZE” on page 171 for
the OPTIMIZE syntax.
Usage notes
NOOPTIMIZE is generally used during program development
when frequent compiles are necessary, and it also allows for
easier debugging. For production runs, however, using OPTI-
MIZE is recommended.

SSRANGE The SSRANGE option verifies that all table references and reference modifi-
cation expressions are in proper bounds.
Performance advantages
No performance advantages.
Performance disadvantages
SSRANGE generates additional code for verifying table refer-
ences.
Reference information
For SSRANGE syntax, see “SSRANGE” on page 178.
Usage notes
In general, if you only need to verify the table references a few
times in the application instead of at every reference, coding
your own checks may be faster than using the SSRANGE com-
piler option. SSRANGE can be turned off at run time with the
CHECK(OFF) run-time option. For performance-sensitive appli-

434 COBOL Set for AIX Programming Guide


Compiler Options

cations, using the NOSSRANGE compiler option is recom-


mended.
TEST The TEST option produces object code that can take full advantage of the
Interactive Debugger.
Performance advantages
No performance advantages.
Performance disadvantages
The TEST option causes a significant increase in the size of
the object file because debugging information is added to the
object file. When linking the program, the linker can be
directed to exclude the debugging information, resulting in
approximately the same size executable as would be created if
the modules were compiled with NOTEST. However, if the
debugging information is included in the executable, a slight
performance degradation might occur because the increased
size of the executable will take longer to load and might cause
increased paging activity.
Reference information
For TEST syntax, see “TEST” on page 179.
Usage notes
TEST forces the NOOPTIMIZE compiler option into effect. For
production runs, using NOTEST is recommended.
TRUNC This compiler option creates code that will truncate the receiving fields of
arithmetic operations.
Performance advantages
TRUNC(OPT) does not generate extra code and generally
improves performance.
Performance disadvantages
Both TRUNC(BIN) and TRUNC(STD) generate extra code when-
ever a BINARY data item is changed. TRUNC(BIN) is usually
the slowest of these options.
Reference information
For syntax and a more detailed explanation of the TRUNC
option, see “TRUNC” on page 180.
Usage notes
TRUNC(STD) conforms to the COBOL 85 Standard, whereas
TRUNC(BIN) and TRUNC(OPT) do not. When using
TRUNC(OPT), the compiler assumes that the data conforms to
the PICTURE and USAGE specifications. TRUNC(OPT) is recom-
mended where possible.

Chapter 27. Productivity and Tuning Techniques 435


Year 2000

Chapter 28. The "Year 2000" Problem


| This chapter provides some information on date processing problems associated with
| the year 2000, and recommends some solutions that you can adopt to help resolve
| them.

| Date Processing Problems


| Many applications use two digits rather than four to represent the year in date fields,
| and assume that these values represent years from 1900 to 1999. This compact date
| format works well for the 1900s, but it does not work for the year 2000 and beyond
| because these applications interpret “00” as 1900 rather than 2000, producing incorrect
| results.

| This chapter outlines a number of approaches you can adopt to resolve problems of
| this nature, and points to facilities available in the COBOL compiler and in the date and
| time callable services that can assist you.

| For more information on the new features of the COBOL language that can help
| resolve date-related problems, see Chapter 29, “Using the Millennium Language
| Extensions” on page 446.

| For more information about Year 2000 issues, and IBM software products that can help
| you identify and resolve their related problems, visit the website at:
| http://www.software.ibm.com/year2000.

Year 2000 Solutions


| There are several solutions to the Year 2000 problem. Many of these solutions refer to
| a “century window”. A century window is a 100-year interval, such as 1950–2049,
| within which any 2-digit year is unique. For example, with a century window of
| 1930–2029, 2-digit years would be interpreted as follows:
| Year values from 00 through 29 are interpreted as years 2000–2029
| Year values from 30 through 99 are interpreted as years 1930–1999

| The solutions outlined in this chapter are:


| Ÿ The Full Field Expansion Solution (the long-term approach)
| Ÿ The Internal Bridging Solution
Ÿ The Century Window Solution
Ÿ The Mixed Field Expansion and Century Window Solution
Ÿ The Century Encoding/Compression Solution
Ÿ The Integer Format Date Solution

Each of these is discussed in more detail below.

436  Copyright IBM Corp. 1996, 1998


Year 2000

The Full Field Expansion Solution


To take your programs through to the year 9999, you must eventually rewrite applica-
tions and rebuild databases and files to use 4-digit year fields rather than 2-digit year
fields.

The field expansion method is a long-term solution and is the recommended approach
| to addressing the Year 2000 problem. To achieve this field expansion, you need to
| develop a program to read in the old data, convert it, and write it back into a copy of
| the original file or data base that has been expanded to hold the 4-digit year data. All
| new data would then go into the new file or database. All of your application programs
| that use those files and databases need to be changed to act on the new 4-digit year
| date fields instead of the 2-digit year fields.

| Your conversion program needs to use a century window when expanding 2-digit years
| to 4 digits, to ensure that the output dates are correct.

| There are several ways to use COBOL Set for AIX to help convert your databases or
| files from 2-digit year dates to 4-digit year dates, with a century window being taken
| into account:
| DATEPROC processing
| Use the DATEPROC compiler option and the DATE FORMAT clause to define
| date fields, and use MOVE statements to expand the dates based on the
| century window specified by the YEARWINDOW compiler option. For example:
| ð5 Date-Short Pic x(6) Date Format yyxxxx.
||| ...
| ð5 Date-Long Pic x(8) Date Format yyyyxxxx.
|| ..
| .
| Move Date-Short to Date-Long.
| For more information, see Chapter 29, “Using the Millennium Language
| Extensions” on page 446.
| COBOL coding
| You can move a 2-digit year date field to an expanded receiving field, and “hard
| code” a century component as part of the move. For example:
| ð5 Date-Short Pic x(6) Date Format yyxxxx.
|| ..
| .
| ð5 Date-Long Pic x(8) Date Format yyyyxxxx.
|| ..
| .
| String "19" Date-Short Delimited by Size
| Into Date-Long.
| The hard-coded century component assumes a century window of 1900–1999 in
| this example, but you can add code to recognize different date ranges and
| assign a different century based on the value of Date-Short. For example, the
| following code expands the date based on a century window of 1930–2029:

Chapter 28. The "Year 2000" Problem 437


Year 2000

| ð5 Date-Short Pic x(6) Date Format yyxxxx.


|| ..
| .
| ð5 Date-Long Pic x(8) Date Format yyyyxxxx.
|| ..
| .
| 77 Century Pic x(2).
||| ...
| If Date-Short Less than "3ððððð" Then
| Move "2ð" to Century
| Else
| Move "19" to Century
| End-If.
| String Century Date-Short Delimited by Size
| Into Date-Long.
| Intrinsic functions
| Three intrinsic functions are available to expand 2-digit year dates into 4-digit
| year dates, with the window being specified as an argument to the function.
| The functions are:
| DATE-TO-YYYYMMDD
| Expand a Gregorian date with a 2-digit year to the same date with a
| 4-digit year.
| DAY-TO-YYYYDDD
| Expand a Julian date with a 2-digit year to the same date with a 4-digit
| year.
| YEAR-TO-YYYY
| Expand a 2-digit year to a 4-digit year.
| With these functions, you specify the century window to be used when
| expanding the year. For full details and syntax of these functions, see IBM
| COBOL Language Reference.
| Callable services
| The date and time callable services can help you manipulate and convert dates.
| Some of these services can accept a date with a 2-digit year as input, and in
| this case, the callable services will apply their own century window. The fol-
| lowing services either affect or can be affected by this century window:
| CEECBLDY Convert a date to a COBOL integer number of days.
| CEEDAYS Convert a date to a Lilian integer number of days.
| CEEQCEN Query the callable services century window.
| CEESCEN Change the callable services century window.
| CEESECS Convert a date and time stamp into a number of Lilian seconds.
| For full details on these and other callable services, see Appendix E, “Date and
| Time Callable Services Reference” on page 484.
For additional information about the century window feature of the date and time
callable services, see “The Century Window Concept” on page 429.

438 COBOL Set for AIX Programming Guide


Year 2000

Advantages:
Ÿ The code changes are straightforward.
Ÿ Minimum testing is required and possibly no need for simulation of future dates on
dedicated machines.
Ÿ Faster resulting code.
Ÿ The issue is addressed once and for all.
Ÿ Maintenance will become cheaper.

Disadvantages:
Ÿ Databases and files must be changed.

| The Internal Bridging Solution


| This solution involves keeping the dates in your files and databases as 2-digit year
| dates, and expanding them into other data items in your program.

| In your application progams, you need to add some data items to hold the 4-digit year
| dates, and some processing logic to expand and contract the date fields. The resultant
| program will be structured like this:
| 1. Read the input files with 2-digit year dates.
| 2. Declare “shadow” data items that contain 4-digit year dates, and expand the 2-digit
| year fields into these work fields.
| 3. Use the 4-digit year dates for all date processing in the program.
| 4. Copy (window) the 4-digit year date fields back to 2-digit format for the output
| process.
| 5. Write the 2-digit year dates to the output files.

| There are several ways to use COBOL Set for AIX to achieve the field expansion and
| windowing needed for this solution.

| For date field expansion:


| Ÿ Use the DATEPROC compiler option and the DATE FORMAT clause to define the
| dates in the input records as windowed date fields, and the work fields as
| expanded date fields. Perform expanded MOVEs or stores using MOVE or
| COMPUTE statements.
| Ÿ Use the intrinsic functions DATE-TO-YYYYMMDD, DAY-TO-YYYYDDD, and
| YEAR-TO-YYYY to copy and expand date fields from the input records to work
| fields.
| Ÿ Use the date and time callable services CEEDAYS and CEEDATE.

| For date windowing:


| Ÿ Simply MOVE the last 2 digits of the year back to the 2-digit year date fields. You
| should also add some code to check that the date is still within the century window,

Chapter 28. The "Year 2000" Problem 439


Year 2000

| and take some error action if it is not. For example, if the 4-digit year field contains
| 2010 and the century window is 1905–2004, the date is outside the century
| window, and to simply store the last 2 digits would be incorrect.
| Ÿ With the DATEPROC compiler option and the DATE FORMAT clause, copy the
| expanded date fields back to windowed date fields. If you use a COMPUTE state-
| ment to do this, you can use the ON SIZE ERROR phrase to ensure that the date
| remains within the century window, or to take some action if it doesn't. For details,
| see “ON SIZE ERROR Phrase” on page 456.

| Advantages:
| Ÿ Databases and files need not be changed.
| Ÿ The code changes are straightforward.
| Ÿ Good interim step towards a full field expansion solution.
| Ÿ Faster resulting code.

| Disadvantages:
| Ÿ Some risk of data corruption.
| Ÿ Short- to medium-term solution only.

The Century Window Solution


The century window solution allows 2-digit years to be interpreted in a 100-year window
(because each 2-digit number can only occur once in any 100-year period).

| There are several ways to use COBOL Set for AIX to help you achieve this:
| Ÿ Use the DATEPROC compiler option and the DATE FORMAT clause to define date
| fields. This provides an automated windowing capability using the century window
| defined by the YEARWINDOW compiler option.
| For more information, see Chapter 29, “Using the Millennium Language
| Extensions” on page 446.
| Ÿ Use the intrinsic functions DATE-TO-YYYYMMDD, DAY-TO-YYYYDDD, and
| YEAR-TO-YYYY to interpret date fields based on a century window. The century
| window is specified as an argument to the intrinsic function. For example:
| If Function YEAR-TO-YYYY (Current-Year, 48) Greater Than
| Function YEAR-TO-YYYY (Due-Year, 48) Then
| Display "Due date has passed."
| End-If.
| In this example, the century window begins 48 years prior to the year at the time
| the program is being run. If the program is running in 1998, then the century
| window is 1950–2049. This would allow a Current-Year value of 00 to be “greater”
| than a Due-Year value of 99.
| Ÿ Insert IF statements around the references to date fields in your program, to deter-
| mine how to apply a century component. For example, the following code imple-
| ments a century window of 1940–2039:

440 COBOL Set for AIX Programming Guide


Year 2000

| If YY-1 less than "4ð" Then


| Move "2ð" to CC-1
| Else
| Move "19" to CC-1
| End-If.
| Ÿ Use the date and time callable services to manipulate date fields using a century
| window defined by the CEESCEN service.

You cannot use the century window forever because a 2-digit year can only be unique
in a given 100-year period. Over time you will need more than 100 years for your data
window—in fact, many companies need more than 100 years now. For example, the
century window cannot solve the problem of trying to figure out how old a customer is if
the customer is older than 100 years and you only have 2-digit year dates. Another
example is sorting. All of the records that you want to sort by date must have 4-digit
| year dates. For these issues and others you need to adopt The Full Field Expansion
| Solution.

Advantages:
Ÿ No database or file changes.

| Disadvantages: The following disadvantages apply to the Century Window solution


| regardless of which method you use to implement it:
| Ÿ Performance will be slower due to increased logic.
| Ÿ More testing is required to validate changes, and simulation of future dates on ded-
| icated machines is essential.
| Ÿ Very difficult to manage across applications.
| Ÿ The problem is not permanently solved and it will become necessary to change
| date programs and databases to use 4-digit years eventually.

| In addition, if you do not use the DATEPROC and DATE FORMAT method, the following
| disadvantages apply:
| Ÿ Risk of performing incorrect translations.
| Ÿ Code changes are more error-prone and require more expertise.
| Ÿ Increased maintenance costs.

| The Mixed Field Expansion and Century Window Solution


| You don't have to convert all of your files and databases at one time. Where a data
| base is shared by many applications, it might be more convenient to keep any dates
| that it contains in 2-digit year form. But where a file is used by a limited number of
| programs, it is best to eliminate the 2-digit year constraint as soon as possible.

| For those dates that are still in 2-digit year form, you can use internal bridging or
| century windowing, both of which are described in detail in “The Internal Bridging
| Solution” on page 439, and “The Century Window Solution” on page 440, respectively.

Chapter 28. The "Year 2000" Problem 441


Year 2000

| You change the data descriptions for dates that you have expanded to 4-digit year
| form, and then use any of the techniques described in “The Full Field Expansion
| Solution” for processing them.

| The DATEPROC compiler option is a particularly convenient way of implementing this


| solution, since it directly supports the use of both expanded and windowed date fields
| within a single statement.

| The mixed solution has the advantages and disadvantages of the individual techniques
| that are discussed in these sections. In addition, the mixed solution has the advantage
| that files and databases can be changed as convenient, and kept unmodified otherwise.

The Century Encoding/Compression Solution


The century encoding/compression solution involves encoding/compressing numbers
greater than 99 into existing 2-byte date fields. (For example, using hexadecimal rather
than decimal digits.) This means rewriting applications to correctly interpret
encoded/compressed values in the database.

This solution is the least desirable way to address the Year 2000 problem.

Advantages:
Ÿ Uses existing 2-byte date fields.

Disadvantages:
Ÿ Performance will be slower due to increased logic.
Ÿ More testing is required to validate changes and simulation of future dates on dedi-
cated machines is essential.
Ÿ Very difficult to manage across applications.
Ÿ Code changes are more error-prone and require more expertise.
Ÿ Increased maintenance costs.
Ÿ The problem is not permanently solved and it will become necessary to change
date programs and databases to use 4-digit years eventually.
Ÿ Cannot be read in dumps or listings.
Ÿ Must be translated whenever externalized.
Ÿ Risk of performing incorrect translations.

The Integer Format Date Solution


Integer dates specify a number of days from some point in the past.

Integer dates are provided by COBOL intrinsic functions and by the date and time call-
able services.

This solution is not the recommended way to address the Year 2000 problem. Instead,
use the The Full Field Expansion Solution described on page 437.

442 COBOL Set for AIX Programming Guide


Year 2000

Advantages:
Ÿ Uses only 4 bytes to store a date.

Disadvantages:
Ÿ Performance will be slower due to increased logic.
Ÿ More testing is required to validate changes and simulation of future dates on dedi-
cated machines is essential.
Ÿ Very difficult to manage across applications.
Ÿ Code changes are more error-prone and require more expertise.
Ÿ Increased maintenance costs.
Ÿ The problem is not permanently solved and it will become necessary to change
date programs and databases to use 4-digit years eventually.
Ÿ Cannot be read in dumps or listings.
Ÿ Must be translated whenever externalized.
Ÿ Risk of performing incorrect translations.
Ÿ There are too many different integer format starting dates:
– CICS, OS/390, and DB2 start with January 1, 1900
– PL/I does not support integer date values
– C starts with January 1, 1970
– COBOL starts with January 1, 1601
– Date and time callable services start with October 15, 1582 (Lilian integer
dates)
There will be no problems with integer dates if conversion to and from integer is
done using the same method in the same program. There will only be problems if
the integer values are stored or passed between programs. These problems could
still be avoided by:
– Not using the value returned by CEECBLDY as input to other date and time
callable services; CEECBLDY returns an ANSI COBOL integer date that can
be used with COBOL intrinsic functions.
– Only using date and time callable services, or only COBOL intrinsic functions,
for getting and manipulating 4-digit year dates.
Note: A program can be compiled on the host using the INTDATE(LILIAN) compiler
option to provide compatibility between the Lilian date returned by CEEDAYS and
COBOL intrinsic functions. However, COBOL Set for AIX does not support the
INTDATE compiler option and such a program will therefore not produce correct
results on the workstation or PC.

Chapter 28. The "Year 2000" Problem 443


How to Get 4-digit Year Dates

| Performance Considerations
| Any implementation of a solution to the year 2000 problem will have some impact on
| the performance of your application. This section discusses some of the performance
| aspects that you should consider.

| Performance Comparison
| The following implementation methods are listed in order of least performance impact to
| most performance impact.
| Full field expansion
| The best performance can be obtained by expanding all of the dates in your
| files as a one-time task, and thereafter using the 4-digit year date fields in all
| processing.
| Mixed field expansion and DATEPROC windowing
| If the dates in your files have not yet been expanded, the best performance can
| be obtained by expanding the date fields as they are read from the files, and
| using these expanded dates in the main processing body of the program. In
| this way, the expansion process is only performed once for each date field.
| Mixed field expansion and manual windowing
| You can expand your input date fields manually, using combinations of COBOL
| coding, intrinsic functions, and callable services to apply the century window.
| This has more performance impact than DATEPROC windowing, even though the
| expansion process is still only performed once for each date field.
| DATEPROC windowing
| The millennium language extensions provide a windowing method that is
| designed to be efficient. However, the action of viewing a windowed date field
| for a COBOL IF or MOVE statement still imposes some processor overhead.
| Manual windowing
| Date windowing using COBOL IF statements adds a level of complexity to the
| program, and adds some processor overhead because of the extra COBOL
| statements. Typically the overhead of an IF statement of this form is more than
| the overhead of the automatic DATEPROC windowing process.

| How to Get 4-digit Year Dates


| Many COBOL programs need to obtain the date at the time of execution, to use as
| “Date-Of-...” fields in output files or reports, or to compare against other dates read from
| input files. COBOL provides a number of methods of obtaining the current date with a
| 4-digit year. The simplest of these are:
| The intrinsic function CURRENT-DATE
| Retrieves the date in Gregorian form, and can also retrieve the current time and
| the offset from Greenwich Mean Time.
| ACCEPT identifier FROM DATE YYYYMMDD
| Retrieves the date in Gregorian form.

444 COBOL Set for AIX Programming Guide


How to Get 4-digit Year Dates

| ACCEPT identifier FROM DAY YYYYDDD


| Retrieves the date in Julian form.
| The CEELOCT callable service
| Retrieves the date in three different forms, including Gregorian with a 4-digit
| year.

Chapter 28. The "Year 2000" Problem 445


Description

| Chapter 29. Using the Millennium Language Extensions


| This chapter provides information on the millennium language extensions that have
| been incorporated into the IBM COBOL language to assist with Year 2000 processing.

| Description
| The term “Millennium Language Extensions” refers collectively to the features of
| COBOL Set for AIX that are activated by the DATEPROC compiler option to help with
| Year 2000 date logic problems.

| The DATEPROC compiler option enables special date-oriented processing of identified


| date fields, and the YEARWINDOW compiler option specifies the 100-year window (the
| century window) to be used for the interpretation of 2-digit windowed years. For a
| description of the DATEPROC compiler option, see “DATEPROC” on page 155. For a
| description of the YEARWINDOW compiler option, see “YEARWINDOW” on page 186.

| The extensions, when enabled, include:


| Ÿ The DATE FORMAT clause. This is added to items in the Data Division to identify
| date fields, and to specify the location of the year component within the date.
| Ÿ The reinterpretation of the function return value as a date field, for the following
| intrinsic functions:
| DATE-OF-INTEGER
| DATE-TO-YYYYMMDD
| DAY-OF-INTEGER
| DAY-TO-YYYYDDD
| YEAR-TO-YYYY
| Ÿ The reinterpretation as a date field of the conceptual data items DATE, DATE
| YYYYMMDD, DAY, and DAY YYYYDDD in the following forms of the ACCEPT
| statement:
| ACCEPT identifier FROM DATE
| ACCEPT identifier FROM DATE YYYYMMDD
| ACCEPT identifier FROM DAY
| ACCEPT identifier FROM DAY YYYYDDD
| Ÿ The intrinsic functions UNDATE and DATEVAL, used for selective reinterpretation
| of date fields and non-dates.
| Ÿ The intrinsic function YEARWINDOW, which retrieves the starting year of the
| century window set by the YEARWINDOW compiler option.

| This chapter describes how you can use these new facilities to help solve date logic
| problems in your COBOL programs.

446  Copyright IBM Corp. 1996, 1998


Implementing Date Processing

| Getting Started
| With the millennium language extensions, you can make simple changes to your
| COBOL programs to define date fields, and the compiler recognizes and acts on those
| dates using a century window to ensure consistency.

| A century window is a 100-year interval, such as 1950–2049, within which any 2-digit
| year is unique. For windowed date fields, the century window start date is specified by
| the YEARWINDOW compiler option. When the DATEPROC option is in effect, the
| compiler applies this window to 2-digit year, or windowed, date fields in the program.
| For example, with a century window of 1930–2029, COBOL interprets 2-digit years as:
| Year values from 00 through 29 are interpreted as years 2000–2029
| Year values from 30 through 99 are interpreted as years 1930–1999

| To implement date windowing using COBOL date processing, you define the century
| window with the YEARWINDOW compiler option, and identify the date fields in your
| program with DATE FORMAT clauses. The compiler then automatically applies the
| century window to operations on those dates. It is often possible to implement a sol-
| ution in which the windowing process is fully automatic; that is, you simply identify the
| fields that contain windowed dates, and you do not need any extra program logic to
| implement the windowing.

| Implementing Date Processing


| Following is a list of simple steps that you need to follow in order to implement auto-
| matic date recognition in a COBOL program:
| Ÿ Use the DATEPROC compiler option to enable the process. You specify this as
| either DATEPROC(FLAG) to get some helpful diagnostic messages, or
| DATEPROC(NOFLAG). For full information, see “DATEPROC” on page 155.

| Ÿ Use the YEARWINDOW compiler option to set the century window. There are two
| ways of doing this:
| – For a fixed window, specify a 4-digit year between 1900 and 1999 as the
| YEARWINDOW option value. For example, YEARWINDOW(1950) defines a fixed
| window of 1950–2049.
| – For a sliding window, specify a negative integer from -1 through -99 as the
| YEARWINDOW option value. For example, YEARWINDOW(-48) defines a sliding
| window that starts 48 years before the year that the program is running. So if
| the program is running in 1998, the century window is 1950–2049, and in 1999
| it automatically becomes 1951–2050, and so on. For a full description and
| syntax, see “YEARWINDOW” on page 186.
| Ÿ Add the DATE FORMAT clause to the data description entries of those data items
| in the program that contain dates that you want the compiler to recognize as win-
| dowed or expanded dates. For a full description of the DATE FORMAT clause,
| see IBM COBOL Language Reference.
| Ÿ To expand dates, use MOVE or COMPUTE statements to copy the contents of
| windowed date fields to expanded date fields.

Chapter 29. Using the Millennium Language Extensions 447


Basic Remediation

| Ÿ If necessary, use the DATEVAL and UNDATE intrinsic functions, to convert


| between date fields and non-dates. For a full description of these functions, see
| IBM COBOL Language Reference.
| Ÿ Compile the program with the DATEPROC(FLAG) option, and review the diagnostic
| messages to see if date processing has produced any unexpected side effects
| (see “Eliminating Warning-Level Messages” on page 460). When the compilation
| has only Information-level diagnostics, you can recompile with the
| DATEPROC(NOFLAG) option to produce a “clean” listing.

| This provides a simple implementation of date windowing and expansion capabilities in


| a COBOL program.

| Resolving Date-Related Logic Problems


| This section discusses three approaches that you can adopt to assist with date-related
| processing problems, and shows how you can use the millennium language extensions
| with each approach to achieve a solution.

| These and other approaches are discussed in conceptual terms in “Year 2000
| Solutions” on page 436. The description here concentrates on the application of
| COBOL date processing capabilities as a tool to implement the solutions.

| The approaches outlined here are:


| Ÿ Basic Remediation (the century window solution)
| Ÿ Internal Bridging
| Ÿ Full Field Expansion

| Basic Remediation
| The simplest method of ensuring that your programs will continue to function through
| the year 2000 is to implement a century window solution.

| With this method, you define a century window, and specify the fields that contain win-
| dowed dates. The compiler then interprets the 2-digit years in those date fields
| according to the century window.

| The following sample code shows how a program can be modified to use this automatic
| date windowing capability. The program checks whether a video tape was returned on
| time:

448 COBOL Set for AIX Programming Guide


Internal Bridging

| CBL LIB,QUOTE,NOOPT,DATEPROC(FLAG),YEARWINDOW(-6ð)
|| ..
| .
| ð1 Loan-Record.
| ð5 Member-Number Pic X(8).
| ð5 Tape-ID Pic X(8).
| ð5 Date-Due-Back Pic X(6) Date Format yyxxxx.
| ð5 Date-Returned Pic X(6) Date Format yyxxxx.
||| ...
| If Date-Returned Greater than Date-Due-Back Then
| Perform Fine-Member.
| In this example, there are no changes to the Procedure Division from the program's
| previous version. The addition of the DATE FORMAT clause on the two date fields
| means that the compiler recognizes them as windowed date fields, and therefore
| applies the century window when processing the IF statement. For example, if Date-
| Due-Back contains “000102” (January 2, 2000) and Date-Returned contains “991231”
| (December 31, 1999), Date-Returned is less than (earlier than) Date-Due-Back, so the
| program does not perform the Fine-Member paragraph.

| Advantages:
| Ÿ Fast and easy to implement.
| Ÿ No change to the program's logic, therefore less testing required.
| Ÿ This solution will allow your programs to function into and beyond the year 2000.

| Disadvantages:
| Ÿ This should be regarded as a short-term solution, not as a permanent fix.
| Ÿ There may be some performance degradation introduced by the date windowing
| functions.
| Ÿ Implementation of this solution is application-dependent. It will not suit all applica-
| tions.

| Internal Bridging
| If your files and databases have not yet been converted to 4-digit year dates, you can
| use an internal bridge technique to process the dates as 4-digit years. Your program
| will be structured as follows:
| 1. Read the input files with 2-digit year dates.
| 2. Declare these 2-digit dates as windowed date fields and move them to expanded
| date fields, so that the compiler automatically expands them to 4-digit year dates.
| 3. In the main body of the program, use the 4-digit year dates for all date processing.
| 4. Window the dates back to 2-digit years.
| 5. Write the 2-digit year dates to the output files.

Chapter 29. Using the Millennium Language Extensions 449


Internal Bridging

| This process provides a convenient migration path to a full expanded-date solution, and
| also may have performance advantages over using windowed dates. For more infor-
| mation, see “Performance Considerations” on page 444.

| Using this technique, you do not change any of the logic in the main body of the
| program. You simply use the 4-digit year date fields in Working-Storage instead of the
| 2-digit year fields in the records.

| Because you are converting the dates back to 2-digit years for output, you should allow
| for the possibility of the year being outside the century window. For example, if a date
| field contains the year 2005, but the century window is 1905–2004, then the date is
| outside the window, and simply storing it as a 2-digit year would be incorrect. To
| protect against this, you can use a COMPUTE statement to store the date, with the ON
| SIZE ERROR phrase to detect whether or not the date is within the century window.
| For more details, see “ON SIZE ERROR Phrase” on page 456.

| The following example shows how a program can be changed to implement an internal
| bridge method:
| CBL LIB,QUOTE,NOOPT,DATEPROC(FLAG),YEARWINDOW(-6ð)
|| ..
| .
| File Section.
| FD Customer-File.
| ð1 Cust-Record.
| ð5 Cust-Number Pic 9(9) Binary.
|| ..
| .
| ð5 Cust-Date Pic 9(6) Date Format yyxxxx.
| Working-Storage Section.
| 77 Exp-Cust-Date Pic 9(8) Date Format yyyyxxxx.
||| ...
| Procedure Division.
| Open I-O Customer-File.
| Read Customer-File.
| Move Cust-Date to Exp-Cust-Date.
|| ..
| .
| \=====================================================\
| \ Use expanded date in the rest of the program logic \
| \=====================================================\
|| ..
| .
| Compute Cust-Date = Exp-Cust-Date
| On Size Error Display "Exp-Cust-Date outside
| century window"
| End-Compute
| Rewrite Cust-Record.

| Advantages:
| Ÿ Little change to the program logic, therefore testing is easy.
| Ÿ This solution will allow your programs to function into and beyond the year 2000.
| Ÿ This is a good incremental step towards a full expanded-year solution.

450 COBOL Set for AIX Programming Guide


Full Field Expansion

| Ÿ Good performance.

| Disadvantages:
| Ÿ Some risk of data corruption.

| Full Field Expansion


| The full field expansion solution involves explicitly expanding 2-digit year date fields to
| contain full 4-digit years in your files and databases, and then using those fields in
| expanded form in your programs. This is the only method by which you can be
| assured of reliable date processing for all applications.

| The millennium language extensions allow you to progressively move towards a full
| date field expansion solution, using the following steps:
| 1. Apply the short-term (basic remediation) solution, and use this until you have the
| resources to implement a more permanent solution.
| 2. Apply the internal bridging scheme. This allows you to use expanded dates in your
| programs while your files continue to hold dates in 2-digit year form. This in turn
| will allow you to progress more easily to a full field expansion solution, because
| there will be no changes to the logic in the main body of the programs.
| 3. Change the file layouts and database definitions to use 4-digit year dates.
| 4. Change your COBOL copybooks to reflect these 4-digit year date fields.
| 5. Run a utility program (or special-purpose COBOL program) to copy from the old
| format files to the new format. For a sample program, see Figure 116 on
| page 452.
| 6. Recompile your programs and perform regression testing and date testing.

| After you have completed the first two steps, the remaining steps in the sequence can
| be repeated any number of times. You do not need to change every date field in every
| file at the same time. Using this method, you can select files for progressive conver-
| sion based on criteria such as business needs or interfaces with other applications.

| When you use this method, you will need to write special-purpose programs to convert
| your files to expanded-date form. Figure 116 on page 452 shows a simple program
| that copies from one file to another while expanding the date fields. Note that the
| record length of the output file is larger than that of the input file because the dates are
| expanded.

Chapter 29. Using the Millennium Language Extensions 451


Full Field Expansion

| CBL LIB,QUOTE,NOOPT,DATEPROC(FLAG),YEARWINDOW(-8ð)
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| \\ CONVERT - Read a file, convert the date \\
| \\ fields to expanded form, write \\
| \\ the expanded records to a new \\
| \\ file. \\
| \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
| IDENTIFICATION DIVISION.
| PROGRAM-ID. CONVERT.

| ENVIRONMENT DIVISION.

| INPUT-OUTPUT SECTION.
| FILE-CONTROL.
| SELECT INPUT-FILE
| ASSIGN TO INFILE
| FILE STATUS IS INPUT-FILE-STATUS.

| SELECT OUTPUT-FILE
| ASSIGN TO OUTFILE
| FILE STATUS IS OUTPUT-FILE-STATUS.

| DATA DIVISION.
| FILE SECTION.
| FD INPUT-FILE
| RECORDING MODE IS F.
| ð1 INPUT-RECORD.
| ð3 CUST-NAME.
| ð5 FIRST-NAME PIC X(1ð).
| ð5 LAST-NAME PIC X(15).
| ð3 ACCOUNT-NUM PIC 9(8).
| ð3 DUE-DATE PIC X(6) DATE FORMAT YYXXXX. .1/
| ð3 REMINDER-DATE PIC X(6) DATE FORMAT YYXXXX.
| ð3 DUE-AMOUNT PIC S9(5)V99 COMP-3.

| FD OUTPUT-FILE
| RECORDING MODE IS F.
| ð1 OUTPUT-RECORD.
| ð3 CUST-NAME.
| ð5 FIRST-NAME PIC X(1ð).
| ð5 LAST-NAME PIC X(15).
| ð3 ACCOUNT-NUM PIC 9(8).
| ð3 DUE-DATE PIC X(8) DATE FORMAT YYYYXXXX. .2/
| ð3 REMINDER-DATE PIC X(8) DATE FORMAT YYYYXXXX.
| ð3 DUE-AMOUNT PIC S9(5)V99 COMP-3.

| WORKING-STORAGE SECTION.

| ð1 INPUT-FILE-STATUS PIC 99.


| ð1 OUTPUT-FILE-STATUS PIC 99.

| PROCEDURE DIVISION.

| OPEN INPUT INPUT-FILE.


| OPEN OUTPUT OUTPUT-FILE.

| Figure 116 (Part 1 of 2). Expanding File Dates

452 COBOL Set for AIX Programming Guide


Programming Techniques

| READ-RECORD.
| READ INPUT-FILE
| AT END GO TO CLOSE-FILES.
| MOVE CORRESPONDING INPUT-RECORD TO OUTPUT-RECORD. .3/
| WRITE OUTPUT-RECORD.

| GO TO READ-RECORD.

| CLOSE-FILES.
| CLOSE INPUT-FILE.
| CLOSE OUTPUT-FILE.

| EXIT PROGRAM.

| END PROGRAM CONVERT.

| Figure 116 (Part 2 of 2). Expanding File Dates

| The following notes apply to Figure 116 on page 452.


| .1/ The fields DUE-DATE and REMINDER-DATE in the input record are both
| Gregorian dates with 2-digit year components. They have been defined with a
| DATE FORMAT clause in this program so that the compiler will recognize them as
| windowed date fields.
| .2/ The output record contains the same two fields in expanded date format. They
| have been defined with a DATE FORMAT clause so that the compiler will treat
| them as 4-digit year date fields.
| .3/ The MOVE CORRESPONDING statement moves each item in INPUT-RECORD
| individually to its matching item in OUTPUT-RECORD. When the two windowed
| date fields are moved to the corresponding expanded date fields, the compiler will
| expand the year values using the current century window.

| Advantages:
| Ÿ This is a permanent solution; no more changes are required. This solution will
| allow your programs to function into and beyond the year 2000.
| Ÿ Best performance.
| Ÿ Maintenance will be easier.

| Disadvantages:
| Ÿ Need to ensure that changes to databases, copybooks, and programs are all syn-
| chronized.

| Programming Techniques
| This section describes the techniques you can use in your programs to take advantage
| of date processing, and the effects of using date fields on COBOL language elements.

| For full details of COBOL syntax and restrictions, see IBM COBOL Language Refer-
| ence.

Chapter 29. Using the Millennium Language Extensions 453


Level 88 Condition-Name

| Date Comparisons
| When you compare two date fields, the two dates must be compatible; that is, they
| must have the same number of non-year characters (see “Compatible Dates” on
| page 462). The number of digits for the year component need not be the same. For
| example:
| 77 Todays-Date Pic X(8) Date Format yyyyxxxx.
| ð1 Loan-Record.
| ð5 Date-Due-Back Pic X(6) Date Format yyxxxx.
||| ...
| If Date-Due-Back Greater than Todays-Date Then...
| In this example, a windowed date field is compared to an expanded date field, so the
| century window is applied to Date-Due-Back.

| Note that Todays-Date must have a DATE FORMAT clause in this case to define it as
| an expanded date field. If it did not, it would be treated as a non-date field, and would
| therefore be considered to have the same number of year digits as Date-Due-Back.
| The compiler would apply the assumed century window to it, which would create an
| inconsistent comparison. For more information, see “The Assumed Window” on
| page 464.

| Level 88 Condition-Name
| If a windowed date field has an 88-level condition-name associated with it, the literal in
| the VALUE clause is windowed against the century window for the compilation unit
| rather than the assumed century window of 1900–1999. For example:
| ð5 Date-Due Pic 9(6) Date Format yyxxxx.
| 88 Date-Target Value ð5122ð.
| If the century window is 1950–2049 and the contents of Date-Due is 051220 (repres-
| enting December 20, 2005), then the condition
| If Date-Target
| would evaluate to TRUE, but the condition
| If Date-Due = ð5122ð
| would evaluate to FALSE. This is because the literal 051220 is treated as a non-date,
| and therefore windowed against the assumed century window of 1900–1999 to repre-
| sent December 20, 1905. But where the same literal is specified in the VALUE clause
| of an 88-level condition-name, it becomes part of the data item to which it is attached.
| Because this data item is a windowed date field, the century window is applied when-
| ever it is referenced.

| You can also use the DATEVAL intrinsic function in a comparison expression to convert
| a literal to a date field, and the output from the intrinsic function will then be treated as
| either a windowed or expanded date field to ensure a consistent comparison. For
| example, using the above definitions, both of these conditions
| If Date-Due = Function DATEVAL (ð5122ð "YYXXXX")
| If Date-Due = Function DATEVAL (2ðð5122ð "YYYYXXXX")

454 COBOL Set for AIX Programming Guide


Windowed Date Fields

| would evaluate to TRUE. For more information on the DATEVAL intrinsic function, see
| “DATEVAL” on page 458.

| Restriction: With a level-88 condition name, you can also specify the THRU option on
| the VALUE clause, for example:
| ð5 Year-Field Pic 99 Date Format yy.
| 88 In-Range Value 98 Thru ð6.

| With this form, the windowed value of the second item must be greater than the win-
| dowed value of the first item. However, the compiler can only verify this if the
| YEARWINDOW compiler option specifies a fixed century window (for example,
| YEARWINDOW(1940) rather than YEARWINDOW(-60)).

| For this reason, if the YEARWINDOW compiler option specifies a sliding century window,
| you cannot use the THRU option on the VALUE clause of a level-88 condition name.

| Arithmetic Expressions
| You can perform arithmetic operations on numeric date fields in the same manner as
| any numeric data item, and, where appropriate, the century window will be used in the
| calculation. However, there are some restrictions on where date fields can be used in
| arithmetic expressions.

| Arithmetic operations that include date fields are restricted to:


| Ÿ Adding a non-date to a date field
| Ÿ Subtracting a non-date from a date field
| Ÿ Subtracting a date field from a compatible date field to give a non-date result

| The following arithmetic operations are not allowed:


| Ÿ Any operation between incompatible date fields
| Ÿ Adding two date fields
| Ÿ Subtracting a date field from a non-date
| Ÿ Unary minus, applied to a date field
| Ÿ Multiplication, division, or exponentiation of or by a date field

| Windowed Date Fields


| Where a windowed date field participates in an arithmetic operation, it is processed as
| if the value of the year component of the field were first incremented by 1900 or 2000,
| depending on the century window. For example:
| ð1 Review-Record.
| ð3 Last-Review-Year Pic 99 Date Format yy.
| ð3 Next-Review-Year Pic 99 Date Format yy.
|| ..
| .
| Add 1ð to Last-Review-Year Giving Next-Review-Year.

Chapter 29. Using the Millennium Language Extensions 455


| If the century window is 1910–2009, and the value of Last-Review-Year is 98, then the
| computation proceeds as if Last-Review-Year is first incremented by 1900 to give 1998.
| Then the ADD operation is performed, giving a result of 2008. This is stored in Next-
| Review-Year as 08.

| Order of Evaluation
| Because of the restrictions on date fields in arithmetic expressions, you may find that
| programs that previously compiled successfully now produce diagnostic messages
| when some of the data items are changed to date fields.

| Consider the following example:


| ð1 Dates-Record.
| ð3 Start-Year-1 Pic 99 Date Format yy.
| ð3 End-Year-1 Pic 99 Date Format yy.
| ð3 Start-Year-2 Pic 99 Date Format yy.
| ð3 End-Year-2 Pic 99 Date Format yy.
|| ..
| .
| Compute End-Year-2 = Start-Year-2 + End-Year-1 - Start-Year-1.
| In this example, the first arithmetic expression evaluated is:
| Start-Year-2 + End-Year-1

| However, this is the addition of two date fields, which is not permitted. To resolve this,
| you should use parentheses to isolate those parts of the arithmetic expression that are
| allowed. For example:
| Compute End-Year-2 = Start-Year-2 + (End-Year-1 - Start-Year-1).
| In this case, the first arithmetic expression evaluated is:
| End-Year-1 - Start-Year-1
| This is the subtraction of one date field from another, which is permitted, and gives a
| non-date result. This non-date result is then added to the date field End-Year-1, giving
| a date field result which is stored in End-Year-2.

| ON SIZE ERROR Phrase


| In the example in “Windowed Date Fields” on page 455, the result of 2008 falls within
| the century window of 1910–2009, so a value of 08 in Next-Review-Year will be recog-
| nized as 2008 by subsequent statements in the program.

| However, the statement:


| Add 2ð to Last-Review-Year Giving Next-Review-Year.
| would give a result of 2018. As this falls outside the range of the century window, if the
| result is stored in Next-Review-Year it would be incorrect, because later references to
| Next-Review-Year would interpret it as 1918. In this case, the result of the operation
| depends on whether the ON SIZE ERROR phrase is specified on the ADD statement,
| as follows:
| Ÿ If SIZE ERROR is specified, the receiving field is not changed, and the SIZE
| ERROR imperative statement is executed.
456 COBOL Set for AIX Programming Guide
Other Date Formats

| Ÿ If SIZE ERROR is not specified, the result is stored in the receiving field with the
| left-hand digits truncated.

| This is an important consideration when developing an internal bridging solution to


| resolve a date processing problem (see “Internal Bridging” on page 449). When you
| contract a 4-digit year date field back to 2 digits to write it to the output file, you need to
| ensure that the date falls within the century window, and that therefore the 2-digit year
| date will be represented correctly in the field.

| You can achieve this using a COMPUTE statement to do the contraction, with a SIZE
| ERROR phrase to handle the out-of-window condition. For example:
| Compute Output-Date-YY = Work-Date-YYYY
| On Size Error Go To Out-of-Window-Error-Proc.

| Note: SIZE ERROR processing for windowed date receivers recognizes any year
| value that falls outside the century window. That is, a year value less than the starting
| year of the century window raises the SIZE ERROR condition, as does a year value
| greater than the ending year of the century window.

| Other Date Formats


| To be eligible for automatic windowing, a date field must contain a 2-digit year as the
| first or only part of the field. The remainder of the field, if present, must be between 2
| and 4 characters, but its content is not important. For example, it can contain a 3-digit
| Julian day, or a 2-character identifier of some event specific to the enterprise.

| If there are date fields in your application that do not fit these criteria, it is not possible
| to define them as date fields with the DATE FORMAT clause. Some examples of
| unsupported date formats are:
| Ÿ A 3-character field consisting of a 2-digit year and a single character to represent
| the month (A–L representing 1–12). This is not supported because date fields can
| have only zero, 2, 3, or 4 non-year characters.
| Ÿ A Gregorian date of the form DDMMYY. This is not supported because the year
| component is not the first part of the date.

| If you need to use date windowing in cases like these, you will need to add some code
| to isolate the year portion of the date.

| In the following example, the two date fields contain dates of the form DDMMYY:
| ð3 Last-Review-Date Pic 9(6).
| ð3 Next-Review-Date Pic 9(6).
|| ..
| .
| Add 1 to Last-Review-Date Giving Next-Review-Date.
| In this example, if Last-Review-Date contains 230197 (January 23, 1997), then Next-
| Review-Date will contain 230198 (January 23, 1998) after the ADD statement is exe-
| cuted. This is a simple method of setting the next date for an annual review. However,
| if Last-Review-Date contains 230199, then adding 1 gives 230200, which is not the
| desired result.

Chapter 29. Using the Millennium Language Extensions 457


DATEVAL

| Because the year is not the first part of these date fields, the DATE FORMAT clause
| cannot be applied without some code to isolate the year component. In the next
| example, the year component of both date fields has been isolated so that COBOL can
| apply the century window and maintain consistent results:
| ð3 Last-Review-Date.
| ð5 Last-R-DDMM Pic 9(4).
| ð5 Last-R-YY Pic 99 Date Format yy.
| ð3 Next-Review-Date Pic 9(6).
| ð5 Next-R-DDMM Pic 9(4).
| ð5 Next-R-YY Pic 99 Date Format yy.
|| ..
| .
| Move Last-R-DDMM to Next-R-DDMM.
| Add 1 to Last-R-YY Giving Next-R-YY.

| Controlling Date Processing Explicitly


| There may be times when you want COBOL data items to be treated as date fields only
| under certain conditions, or only in specific parts of the program. Or your application
| may contain 2-digit year date fields that cannot be declared as windowed date fields
| because of some interaction with another software product. For example, if a date field
| is used in a context where it is only recognized by its true binary contents without
| further interpretation, the date in this field cannot be windowed. This includes:
| Ÿ A key on a VSAM file
| Ÿ A search field in a database system such as DB2
| Ÿ A key field in a CICS command
| Conversely, there may be times when you want a date field to be treated as a non-date
| in specific parts of the program.

| COBOL provides two intrinsic functions to cater for these conditions:


| DATEVAL Converts a non-date into a date field.
| UNDATE Converts a date field into a non-date.

| DATEVAL
| You can use the DATEVAL intrinsic function to convert a non-date into a date field, so
| that COBOL will apply the relevant date processing to the field. The first argument to
| the function is the non-date to be converted, and the second argument specifies the
| date format. The second argument is a literal string with a specification similar to that
| of the date pattern in the DATE FORMAT clause.

| As an example, assume that a program contains a field Date-Copied, and that this field
| is referenced many times in the program, but most of these references simply move it
| between records or reformat it for printing. Only one reference relies on it containing a
| date, for comparison with another date.

| In this case, it is better to leave the field as a non-date, and use the DATEVAL intrinsic
| function in the comparison statement. For example:

458 COBOL Set for AIX Programming Guide


UNDATE

| ð3 Date-Distributed Pic 9(6) Date Format yyxxxx.


| ð3 Date-Copied Pic 9(6).
|| ..
| .
| If FUNCTION DATEVAL(Date-Copied "YYXXXX") Less than
| Date-Distributed ...
| In this example, the DATEVAL intrinsic function converts Date-Copied into a date field
| so that the comparison will be meaningful.

| In most cases, the compiler makes the correct assumption about the interpretation of a
| non-date, but accompanies this assumption with a warning-level diagnostic message.
| This typically happens when a windowed date is compared to a literal:
| ð3 When-Made Pic x(6) Date Format yyxxxx.
|| ..
| .
| If When-Made = "85ð7ð1" Perform Warranty-Check.
| The literal is assumed to be a compatible windowed date but with a century window of
| 1900–1999, thus representing July 15, 1985. You can use the DATEVAL intrinsic func-
| tion to make the year of the literal date explicit, and eliminate the warning message:
| If When-Made = Function Dateval("1985ð7ð1" "YYYYXXXX")
| Perform Warranty-Check.

| For a full description and syntax of the DATEVAL intrinsic function, see IBM COBOL
| Language Reference.

| UNDATE
| The UNDATE intrinsic function converts a date field to a non-date, so that it can be
| referenced without any date processing.

| In the following example, the field Invoice-Date in Invoice-Record is a windowed Julian


| date. In some records, it contains a value of "00999" to indicate that this is not a “true”
| invoice record, but a record containing file control information.

| Invoice-Date has been given a DATE FORMAT clause because most of its references
| in the program are date-specific. However, in the instance where it is checked for the
| existence of a control record, the value of "00" in the year component will lead to some
| confusion. A year of "00" in Invoice-Date will represent a “true” year of either 1900 or
| 2000, depending on the century window. This is compared to a non-date (the literal
| "00999" in the example), which will always be windowed against the assumed century
| window and will therefore always represent the year 1900.

| To ensure a consistent comparison, you should use the UNDATE intrinsic function to
| convert Invoice-Date to a non-date. This means that the IF statement is not comparing
| any date fields, so it does not need to apply any windowing. For example:
| ð1 Invoice-Record.
| ð3 Invoice-Date Pic x(5) Date Format yyxxx.
||| ...
| If FUNCTION UNDATE(Invoice-Date) Equal "ðð999" ...

Chapter 29. Using the Millennium Language Extensions 459


Eliminating Warning-Level Messages

| For a full description and syntax of the UNDATE intrinsic function, see IBM COBOL
| Language Reference.

| Eliminating Warning-Level Messages


| When the DATEPROC(FLAG) compiler option is in effect, the compiler produces diag-
| nostic messages for every statement that defines or references a date field. These
| should normally be information-level messages, but it is possible to get warning-level
| messages for COBOL code that appears to be correct, and even produces correct
| results.

| You should always eliminate error-level and severe-level messages from your program,
| and it is good programming practice to eliminate warning-level messages as much as
| possible. When the program is compiled and tested satisfactorily, you can then use the
| DATEPROC(NOFLAG) compiler option to produce a listing with as few diagnostic mes-
| sages as possible.

| To reduce or eliminate warning-level diagnostic messages when DATEPROC(FLAG) is


| in effect, you should follow these simple guidelines:
| Ÿ The diagnostic messages may indicate some date data items that should have had
| a DATE FORMAT clause but were missed. You should either add DATE FORMAT
| clauses to these items, or use the DATEVAL intrinsic function in references to
| them.
| Ÿ Don't specify a date field in a context where a date field doesn't make sense, such
| as a FILE STATUS, PASSWORD, ASSIGN USING, LABEL RECORD, or LINAGE
| item. If you do, you'll get a warning-level message and the date field will be
| treated as a non-date.
| Ÿ Ensure that implicit or explicit aliases for date fields are compatible, such as in a
| group item that consists solely of a date field, or when using the REDEFINES or
| RENAMES clauses.
| Ÿ Ensure that if a date field is defined with a VALUE clause, the value is compatible
| with the date field definition.
| Ÿ Use the DATEVAL intrinsic function if you want a non-date treated as a date field,
| such as when moving a non-date to a date field, or comparing a windowed date
| field with a non-date and you want a windowed date comparison. If you don't use
| DATEVAL, the compiler will make an assumption about the use of the non-date,
| and produce a warning-level diagnostic message. Even if the assumption is
| correct, you may want to use DATEVAL just to eliminate the message. For more
| information on the DATEVAL intrinsic function, see “DATEVAL” on page 458.
| Ÿ Use the UNDATE intrinsic function if you want a date field treated as a non-date,
| such as moving a date field to a non-date, or comparing a non-date and a win-
| dowed date field and you don't want a windowed comparison. For more informa-
| tion on the UNDATE intrinsic function, see “UNDATE” on page 459.
| Ÿ Don't subtract one date field from another unless the result field is a non-date. For
| more information, see “Arithmetic Expressions” on page 455.

460 COBOL Set for AIX Programming Guide


Objectives

| Principles
| To gain the most benefit from the millennium language extensions, it is important to
| understand the reasons for their introduction into the COBOL language, and the
| rationale behind their design. In particular, there are some apparent inconsistencies
| that only make sense with an understanding of what the extensions are, and what they
| are not.

| You should not consider using the extensions in new applications, or in enhancements
| to existing applications, unless the applications are using old data that cannot be
| expanded until later.

| The extensions do not provide fully-specified or complete date-oriented data types, with
| semantics that recognize, for example, the month and day parts of Gregorian dates.
| They do however provide special semantics for the year part of dates.

| The millennium language extensions focus on a few key principles:


| 1. Programs to be re-compiled with date semantics are fully-tested and valuable
| assets of the enterprise. Their only relevant limitation is that any 2-digit years in
| the programs are restricted to the range 1900–1999.
| 2. No special processing is done for the non-year part of dates. That is why the non-
| year part of the supported date formats is denoted by Xs. To do otherwise might
| change the meaning of existing programs. The only date-sensitive semantics that
| are provided involve automatically expanding (and contracting) the 2-digit year part
| of dates with respect to the century window for the program.
| 3. Dates with 4-digit year parts are generally only of interest when used in combina-
| tion with windowed dates. Otherwise there is little difference between 4-digit year
| dates and non-dates.

| Objectives
| Based on these principles, the millennium language extensions are designed to meet a
| number of objectives. You should evaluate the objectives that you need to meet in
| order to resolve your date processing problems, and compare them against the objec-
| tives of the millennium language extensions, to determine how your application can
| benefit from them.

| The objectives of the millennium language extensions are as follows:


| 1. The primary objective is to extend the useful life of your application programs, as
| they are currently specified, into the twenty-first century.
| 2. Source changes to accomplish this must be held to the bare minimum, preferably
| limited to augmenting the declarations of date fields in the Data Division. To imple-
| ment basic remediation of date problems, you should not be required to make any
| changes to the program logic in the Procedure Division.
| 3. The existing semantics of the programs will not be changed by the addition of date
| fields. For example, where a date is expressed as a literal, as in:

Chapter 29. Using the Millennium Language Extensions 461


Concepts

| If Expiry-Date Greater Than 98ð1ð1 ...


| the literal is considered to be compatible (windowed or expanded) with the date
| field to which it is compared. Further, because the existing program assumes that
| 2-digit year dates expressed as literals are in the range 1900–1999, the extensions
| do not change this assumption (see “The Assumed Window” on page 464).
| 4. The windowing feature is not intended for long-term use. Its intention is to extend
| the useful life of applications through the year 2000, as a start towards a long-term
| solution that can be implemented later.
| 5. The expanded date field feature is intended for long-term use, as an aid for
| expanding date fields in files and databases.

| Concepts
| With these principles and objectives in mind, you can better understand some of the
| concepts of the millennium language extensions, and how they interact with other parts
| of COBOL. This section describes some of these concepts.

| Date Semantics
| All arithmetic, whether performed on date fields or not, acts only on the numeric con-
| tents of the fields; date semantics for the non-year parts of date fields are not provided.
| For example, adding 1 to a windowed Gregorian date field that contains the value
| 980831 gives a result of 980832, not 980901.

| However, date semantics are provided for the year parts of date fields. For example, if
| the century window is 1950–2049, and the value of windowed date field TwoDigitYear
| is 49, then the following ADD statement will result in the SIZE ERROR imperative state-
| ment being executed:
| Add 1 to TwoDigitYear
| on Size Error Perform CenturyWindowOverflow
| End-Add

| Compatible Dates
| The meaning of the term compatible dates depends on the COBOL division in which
| the usage occurs, as follows:
| Ÿ The Data Division usage is concerned with the declaration of date fields, and the
| rules governing COBOL language elements such as subordinate data items and
| the REDEFINES clause. In the following example, Review-Date and Review-Year
| are compatible because Review-Year can be declared as a subordinate data item
| to Review-Date:
| ð1 Review-Record.
| ð3 Review-Date Date Format yyxxxx.
| ð5 Review-Year Pic XX Date Format yy.
| ð5 Review-M-D Pic XXXX.
| For full details, see IBM COBOL Language Reference.

462 COBOL Set for AIX Programming Guide


Concepts

| Ÿ The Procedure Division usage is concerned with how date fields can be used
| together in operations such as comparisons, moves, and arithmetic expressions.
| To be considered compatible, date fields must have the same number of non-year
| characters. For example, a field with DATE FORMAT YYXXXX is compatible with
| another field that has the same DATE FORMAT, and with a YYYYXXXX field, but
| not with a YYXXX field.

| The remainder of this discussion relates to the Procedure Division usage of compatible
| dates.

| You can perform operations on date fields, or on a combination of date fields and non-
| dates, provided that the date fields in the operation are compatible. For example, with
| the following definitions:
| ð1 Date-Gregorian-Win Pic 9(9) Packed Date Format yyxxxx.
| ð1 Date-Julian-Win Pic 9(9) Packed Date Format yyxxx.
| ð1 Date-Gregorian-Exp Pic 9(9) Packed Date Format yyyyxxxx.

| The statement:
| If Date-Gregorian-Win Less than Date-Julian-Win ...
| is inconsistent because the number of non-year digits is different between the two
| fields. The statement:
| If Date-Gregorian-Win Less than Date-Gregorian-Exp ...
| is accepted because the number of non-year digits is the same for both fields. In this
| case the century window is applied to the windowed date field (Date-Gregorian-Win) to
| ensure that the comparison is meaningful.

| Where a non-date is used in conjunction with a date field, the non-date is either
| assumed to be compatible with the date field, or treated as a simple numeric value, as
| described in the following section.

| Treatment of Non-Dates
| The simplest kind of non-date is just a literal value. The following items are also
| non-dates:
| Ÿ A data item whose data description does not include a DATE FORMAT clause.
| Ÿ The results (intermediate or final) of some arithmetic expressions. For example,
| the difference of two date fields is a non-date, wheras the sum of a date field and a
| non-date is a date field.
| Ÿ The output from the UNDATE intrinsic function.

| When you use a non-date in conjunction with a date field, the compiler interprets the
| non-date as either a date whose format is compatible with the date field, or a simple
| numeric value. This interpretation depends on the context in which the date field and
| non-date are used, as follows:

Chapter 29. Using the Millennium Language Extensions 463


Concepts

| Comparison
| Where a date field is compared to a non-date, the non-date is considered to be
| compatible with the date field in the number of year and non-year characters. In
| the following example:
| ð1 Date-1 Pic 9(6) Date Format yyxxxx.
||| ...
| If Date-1 Greater than 971231 ...
| Because the non-date literal 971231 is being compared to a windowed date
| field, it is treated as if it had the same DATE FORMAT as Date-1, but with a
| base year of 1900.
| Arithmetic operations
| In all supported arithmetic operations, non-date fields are treated as simple
| numeric values. In the following example:
| ð1 Date-2 Pic 9(6) Date Format yyxxxx.
||| ...
| Add 1ðððð to Date-2.
| the numeric value 10000 is added to the Gregorian date in Date-2, effectively
| adding one year to the date.
| MOVE statement
| Moving a date field to a non-date is not supported. However, you can use the
| UNDATE intrinsic function to achieve this. For more information, see “UNDATE”
| on page 459.
| When you move a non-date to a date field, the sending field is assumed to be
| compatible with the receiving field in the number of year and non-year charac-
| ters. For example, when you move a non-date to a windowed date field, the
| non-date field is assumed to contain a compatible date with a 2-digit year.

| The Assumed Window


| Where the program operates on windowed date fields, the compiler applies the century
| window for the compilation unit; that is, the one defined by the YEARWINDOW compiler
| option. Where a windowed date field is used in conjunction with a non-date, and the
| context demands that the non-date also be treated as a windowed date, the compiler
| uses an assumed century window to resolve the non-date field.

| The assumed century window is 1900–1999, which is typically not the same as the
| century window for the compilation unit.

| In many cases, particularly for literal non-dates, this assumed century window will be
| the correct choice. For example, in the construct:
| ð1 manufacturingRecord.
| ð3 makersDate Pic X(6) Date Format yyxxxx.
|| ..
| .
| If makersDate Greater than "72ð1ð1" ...
| the literal should retain its original meaning of January 1, 1972, and not change to 2072
| if the century window is, for example, 1975–2074. Even if the assumption is correct, it

464 COBOL Set for AIX Programming Guide


Concepts

| is better to make the year explicit, and also eliminate the warning-level diagnostic
| message that accompanies application of the assumed century window, by using the
| DATEVAL intrinsic function:
| If makersDate Greater than
| Function Dateval("1972ð1ð1" "YYYYXXXX") ...

| In other cases however, the asumption may not be correct. For example:
| ð1 Project-Controls.
| ð3 Date-Target Pic 9(6).
|| ..
| .
| ð1 Progress-Record.
| ð3 Date-Complete Pic 9(6) Date Format yyxxxx.
||| ...
| If Date-Complete Less than Date-Target ...

| For this example, assume that Project-Controls is in a COPY member that is used by
| other applications that have not yet been upgraded for Year 2000 processing, and
| therefore Date-Target cannot have a DATE FORMAT clause. In the example, if:
| Ÿ The century window is 1910–2009,
| Ÿ Date-Complete is 991202 (Gregorian date: December 2, 1999), and
| Ÿ Date-Target is 000115 (Gregorian date: January 15, 2000),
| then:
| Ÿ Date-Complete is earlier than (less than) Date-Target.

| However, because Date-Target does not have a DATE FORMAT clause, it is a non-
| date, so the century window applied to it is the assumed century window of 1900–1999,
| which means that it is processed as January 15, 1900. So Date-Complete will be
| greater than Date-Target, which is not the desired result.

| In this case, you should use the DATEVAL intrinsic function to convert Date-Target to a
| date field for this comparison. For example:
| If Date-Complete Less than
| Function Dateval (Date-Target "YYXXXX") ...

| For more information on the DATEVAL intrinsic function, see “DATEVAL” on page 458.

Chapter 29. Using the Millennium Language Extensions 465


Differences with Host COBOL

Appendix A. Summary of Differences with Host COBOL


This appendix gives an overview of the product function differences between IBM
COBOL for OS/390 & VM and IBM COBOL Set for AIX.

Figure 117 lists the differences between IBM COBOL for OS/390 & VM and IBM
COBOL Set for AIX. For information on COBOL language differences between the dif-
| ferent platforms, see the IBM COBOL Language Reference. For information on devel-
| oping applications that are portable between the different platforms, see Chapter 17,
| “Porting Applications between Platforms” on page 316.

Figure 117 (Page 1 of 3). Product Differences Between Mainframe and Workstation IBM COBOL
Product Function Workstation Implementation
Compiler Options The following compiler options are treated as comments: ADV, AWO,
BUFSIZE, DATA, DECK, DBCS, FASTSRT, FLAGMIG, INTDATE, LAN-
GUAGE, NAME, OUTDD, RENT, and suboptions of TEST. These options
are flagged with I-level messages.
The following compiler options are treated as comments; however, if speci-
fied, the application might yield unpredictable results: NOADV and CMPR2.
These options are flagged with W-level messages.
LIB is the IBM-supplied default on the workstation; NOLIB is the IBM-supplied
default on the host.
Data Representation Binary data types are handled based on the specification of the BINARY
compiler option.
Sign representation for external decimal data are ASCII-based. Specifying
NUMPROC(NOPFD) allows the full range of valid sign values for the
numeric class test.
EBCDIC vs ASCII:
Ÿ You can specify the EBCDIC collating sequence using the following lan-
guage elements: ALPHABET clause, PROGRAM COLLATING
SEQUENCE clause, and the COLLATING SEQUENCE phrase of the
SORT and MERGE verbs.
Ÿ You can specify the CHAR(EBCDIC) compiler option to indicate that
DISPLAY data items are in the System/390 data representation
(EBCDIC).
You can use the FLOAT(S390) compiler option to indicate that floating point
data items are in the System/390 data representation (hexadecimal) as
opposed to the native (IEEE) format.
DBCS—Under AIX, OS/2, and Windows, you do not use shift-in or shift-out
delimiters for DBCS literals unless the CHAR(EBCDIC) compiler option is in
effect.
Within an alphanumeric literal, using control characters X'00' through
X'1F' can yield unpredictable results.

466  Copyright IBM Corp. 1996, 1998


Differences with Host COBOL

Figure 117 (Page 2 of 3). Product Differences Between Mainframe and Workstation IBM COBOL
Product Function Workstation Implementation
Environment Variables IBM COBOL Set for AIX recognizes the following as environment variables:
Ÿ ASSIGNment name
Ÿ COBMSGS
Ÿ COBOPT
Ÿ COBPATH
Ÿ COBRTOPT
Ÿ DB2DBDFT
Ÿ EBCDIC_CODEPAGE
Ÿ LANG
Ÿ LC_COLLATE
Ÿ LC_MESSAGES
Ÿ LC_TIME
Ÿ LIBPATH
Ÿ library-name specified as a user-defined word
Ÿ LOCPATH
Ÿ NLSPATH
Ÿ SYSIN, SYSIPT, SYSOUT, SYSLIST, SYSLST, CONSOLE,
SYSPUNCH, and SYSPCH
Ÿ SYSLIB
Ÿ TEMP
Ÿ text-name specified as a user-defined word
Ÿ TZ
File Specification All files are treated as single volume files. All other file specifications are
treated as comments. This affects the following: REEL, UNIT, MULTIPLE
FILE TAPE clause, and CLOSE...UNIT/REEL.
Inter-Language Communication (ILC) ILC is available with C, C++, and PL/I programs.

Appendix A. Summary of Differences with Host COBOL 467


Differences with Host COBOL

Figure 117 (Page 3 of 3). Product Differences Between Mainframe and Workstation IBM COBOL
Product Function Workstation Implementation
I-O I-O support for sequential, relative, and indexed files is provided using STL
file system and VSAM. Sizes and values are different for the data-name
returned from the file system.
IBM COBOL Set for AIX does not provide direct support for tape drives or
diskette drives.
Line Sequential I-O is supported using the native byte stream file support of
the platform. The following language elements are treated as comments for
Line Sequential files, as well as for Sequential, Relative, and Indexed files:
Ÿ ADVANCING phrase of WRITE statement
Ÿ APPLY WRITE ONLY clause
Ÿ AT END-OF-PAGE phrase of WRITE statement
Ÿ BLOCK CONTAINS clause
Ÿ CODE-SET clause
Ÿ DATA RECORDS clause
Ÿ FILE STATUS value 39 (fixed file attribute conflict)
Ÿ LABEL RECORDS clause
Ÿ LINAGE clause
Ÿ OPEN I-O option
Ÿ PADDING CHARACTER clause
Ÿ RECORD CONTAINS 0 clause
Ÿ RECORD CONTAINS clause (format 3)
Ÿ RECORD DELIMITER clause
Ÿ RECORDING MODE clause
Ÿ RERUN clause
Ÿ RESERVE clause
Ÿ REVERSED phrase of OPEN statement
Ÿ VALUE OF clause of file description entry
Run-Time Options The following run-time options are not recognized by IBM COBOL Set for
AIX and will be treated as invalid options: AIXBLD, ALL31, CBLPSHPOP,
CBLQDA, COUNTRY, HEAP, MSGFILE, NATLANG, SIMVRD, and STACK.
| On the host, the STORAGE run-time option can be used to initialize COBOL
| working storage. With IBM COBOL Set for AIX, this is achieved with the
| WSCLEAR compiler option.
Source Code Line A COBOL source line can be less than 72 characters. A line ends on
column 72 or where a carriage control character is found.

468 COBOL Set for AIX Programming Guide


Appendix B. System/390 Host Data Type Considerations
The following are considerations, restrictions, and limitations which apply to the use of
System/390 host data types. The CHAR and FLOAT compiler options determine if
System/390 host data types or native data types are used. See Chapter 10, “Compiler
Options” on page 147 for details on how to specify these options and for specific infor-
mation about how each option is used.

CICS Access
CICS allows you to specify various data conversion choices at various places and at
various granularities. For example, client CICS translator option specifications on the
server for different resources (file, EIBLK, COMMAREA, transient data queue, etc.).
Your use of host versus native data depends on such selections. Refer to the appro-
priate CICS documentation for specific information about how such choices can best be
made.
| Note: System/390 host data type support is only allowed on the following CICS
| systems using the EBCDIC enablement support:
| Ÿ CICS for OS/2
| Ÿ VisualAge CICS Enterprise Application Development
It will not work for COBOL programs that are translated by the CICS translator and run
on CICS for Windows NT or CICS for AIX.

Date and Time Callable Services


| The date and time callable services can be used with the System/390 host data types.
| All of the parameters passed to the callable services must be in System/390 host data
| type format. You cannot mix native and host data types in the same call to a date and
| time service.

Floating Point Overflow Exceptions


Due to differences in the limits of floating point data representations on the workstation
and the System/390 host platform, it is possible that a floating point overflow exception
can occur during conversion between the two formats. For example, you might get the
following message on the workstation:
IWZð53S An overflow occurred on conversion to floating point
when running a program which executes successfully on the System/390 host platform.

To avoid this problem, you must be aware of the maximum floating point values sup-
ported on either platform for the respective data types. The limits are shown in
Figure 118

 Copyright IBM Corp. 1996, 1998 469


Figure 118. Floating Point Value Limits
Data Type Maximum Workstation Value Maximum System/390 Host Value
COMP-1 ±(2\\128-2\\4) ±(16\\63-16\\57)
(Approx. ±3.4028E+38) (Approx. ±7.2370E+75)
COMP-2 ±(2\\1024-2\\971) ±(16\\63-16\\49)
(Approx. ±1.7977E+308) (Approx. ±7.2370E+75)
Note: \\ indicates “in the power of.”

As shown above, the System/390 host can carry a larger COMP-1 value than the work-
station and the workstation can carry a larger COMP-2 value than the System/390 host.

DB2
| The System/390 host data type compiler options can be used with DB2 programs.

MQSeries
The System/390 host data type compiler options should not be used with MQSeries
programs.

Remote File Access


Ÿ If you are accessing remote host files using SMARTdata Utilities, (via COBOL file
I/O statements), you do not need to specify A Data Language (ADL) for data con-
version. You can access the data in the VSAM host files directly when you
compile with the host data options.
Ÿ If you are already using ADL for conversion of remote file data, do not use the host
data support.
Ÿ Note that file records (01 record under FD) implicitly take on the characteristics of
the CHAR compiler option.

SORT
| All of the System/390 host data types can be used as sort keys.

470 COBOL Set for AIX Programming Guide


Calculating Precision

Appendix C. Intermediate Results and Arithmetic Precision


The compiler handles arithmetic statements as a succession of operations, performed
according to operator precedence, and sets up an intermediate field to contain the
results of these operations.

Intermediate results are possible in the following cases:


Ÿ In an ADD or SUBTRACT statement containing more than one operand immediately
following the verb.
Ÿ In a COMPUTE statement specifying a series of arithmetic operations or multiple
result fields.
Ÿ In arithmetic expressions contained in conditional statements and reference modifi-
cation specifications.
Ÿ In the GIVING option with multiple result fields for the ADD, SUBTRACT, MULTIPLY,
or DIVIDE statements.
Ÿ In a statement with an intrinsic function used as an operand.

For a discussion on when the compiler uses fixed-point or floating-point arithmetic, refer
to “Fixed-Point versus Floating-Point Arithmetic” on page 43.

Calculating Precision of Intermediate Results


The compiler uses algorithms to determine the number of integer and decimal places
reserved for intermediate results.

In the following discussion of how the compiler determines the number of integer and
decimal places reserved for intermediate results, these abbreviations are used:
i The number of integer places carried for an intermediate result.
d The number of decimal places carried for an intermediate result.
ROUNDED
If the ROUNDED option is used, one more integer or decimal might be added
for accuracy, if necessary. Only the final results are rounded; the interme-
diate results are not rounded.
dmax In a particular statement, the largest of:
Ÿ The number of decimal places needed for the final result field(s).
Ÿ The maximum number of decimal places defined for any operand,
except divisors or exponents.
Ÿ The outer-dmax for any function operand.

 Copyright IBM Corp. 1996, 1998 471


Calculating Precision

inner-dmax
The inner-dmax for a function is the largest of:
Ÿ The number of decimal places defined for any of its elementary argu-
ments.
Ÿ The dmax for any of its arithmetic expression arguments.
Ÿ The outer-dmax for any of its embedded functions.
outer-dmax
The number that determines how a function result contributes to operations
outside of its own evaluation (for example, if the function is an operand in an
arithmetic expression or an argument to another function).
op1 The first operand in a generated arithmetic statement. For division, op1 is
the divisor.
op2 The second operand in a generated arithmetic statement. For division, op2
is the dividend.
i1,i2 The number of integer places in op1 and op2, respectively.
d1,d2 The number of decimal places defined for op1 and op2, respectively.
ir The intermediate result field obtained when a generated arithmetic statement
or operation is performed. ir1, ir2,. . ., represent successive intermediate
results. These intermediate results are generated either in registers or in
storage locations. Successive intermediate results might have the same
location.

The compiler handles each statement as a succession of operations. For example, the
following statement:
COMPUTE Y = A + B \ C - D / E + F \\ G

is calculated as:

** F BY G yielding ir1
MULTIPLY B BY C yielding ir2
DIVIDE E INTO D yielding ir3
ADD A TO ir2 yielding ir4
SUBTRACT ir3 FROM ir4 yielding ir5
ADD ir5 TO ir1 yielding Y

472 COBOL Set for AIX Programming Guide


Fixed-Point Data

Fixed-Point Data and Intermediate Results


The number of integer and decimal places in an intermediate result can be determined
by using the following guidelines:

Figure 119. Determining the Precision of an Intermediate Result


Operation Integer Places Decimal Places
+ or - (i1 or i2) + 1, whichever is greater d1 or d2, whichever is greater
* i1 + i2 d1 + d2
/ i2 + d1 (d2 - d1) or dmax, whichever is greater

You must define the operands of any arithmetic statements with enough decimal places
to give the desired accuracy in the final result.

Figure 120 indicates the action of the compiler when handling intermediate results for
fixed-point numbers.

Figure 120. Determining When the Compiler Might Truncate Intermediate Results
Value of Value of Value of Action Taken
i + d d i + dmax
<30 Any value Any value i integer and d decimal places are carried for ir.
=30
>30 <dmax Any value 30-d integer and d decimal places are carried for ir.
=dmax
>dmax <30 i integer and 30-i decimal places are carried for ir.
=30
>30 30-dmax integer and dmax decimal places are carried
for ir.

Exponentiations Evaluated in Fixed-Point Arithmetic


Exponentiation is represented by the expression op1 ** op2. Based on the character-
istics of op2, the compiler handles exponentiation of fixed-point numbers in one of three
ways:
Ÿ When op2 is expressed with decimals, floating-point rules (see “Floating-Point Data
and Intermediate Results” on page 477) are used to calculate the exponentiation.
Ÿ When op2 is an integral literal or constant, the value d is computed as:
d = d1 \ |op2|
When op1 is a data-name or variable, the value i is computed as:
i = i1 \ |op2|
When op1 is a literal or constant, the actual value of op1 ** |op2| is computed and
i is set equal to the number of integers in that value.

Appendix C. Intermediate Results and Arithmetic Precision 473


Fixed-Point Data

Having calculated i and d, the compiler takes the action indicated in the following
figure to handle intermediate results:

Figure 121. Determining When the Compiler Might Truncate Intermediate Results for
Exponentiation
Value of Other Conditions Action Taken
i + d
<30 Any i integer and d decimal places are carried for ir.
=30 op1 has an odd i integer and d decimal places are carried for ir.
number of digits
op1 has an even The exponentiation is handled the same as it is when
number of digits op2 is an integral data-name or a variable, except in
the case of a 30-digit integer raised to the power of
literal 1, where the computation is done following the
rules for op1 with an odd number of digits.
>30 Any The exponentiation is handled the same as it is when
op2 is an integral data-name or a variable.

If op2 is negative, the value of 1 is divided by the result produced by the prelimi-
nary computation described above. The values of i and d that are used are calcu-
lated using the rules for division found in Figure 119 on page 473.
Ÿ When op2 is an integral data-name or a variable, dmax decimals and 3ð-dmax inte-
gers are used. Here, op1 is multiplied by itself (|op2| - 1) times. For example,
the following statement:
COMPUTE Y = A \\ B, where B has a value of 4
is calculated as:

MULTIPLY A BY A yielding ir1


MULTIPLY ir1 BY A yielding ir2
MULTIPLY ir2 BY A yielding ir3
MOVE ir3 TO ir4 which has dmax decimals

The values of i and d that are used for the above multiplications are calculated
using the rules for multiplication found in Figure 119 on page 473.
If B is positive, Y = ir4.
If B is negative, however,
DIVIDE ir4 INTO 1 yielding ir5, which has dmax decimals
Y = ir5
If op2 is equal to zero, the answer is 1. Division-by-0 and exponentiation SIZE
ERROR conditions apply. For specific information on the SIZE ERROR option, see
the IBM COBOL Language Reference.

Fixed-point exponents with more than 9 significant digits are always truncated to 9
digits. If the exponent is a literal or constant, an E-level compiler diagnostic message is
issued; otherwise, an informational message is issued at run time.

474 COBOL Set for AIX Programming Guide


Fixed-Point Data

Truncated Intermediate Results


Whenever the number of digits in a decimal is greater than 30, the field is truncated to
30 digits. You will get a warning message when you compile the program. If truncation
happens at run time, a message is issued and the program continues running.

If you think an intermediate result field might exceed 30 digits, you can use floating-
point operands (COMP-1 and COMP-2) to avoid truncation.

Binary Data and Intermediate Results


If an operation involving binary operands requires intermediate results greater than 18
digits, the compiler converts the operands to internal decimal before performing the
operation. If the result field is binary, the result will be converted from internal decimal
to binary.

Binary items are used most efficiently when the intermediate result is not greater than 9
digits.

Intrinsic Functions Evaluated in Fixed-Point Arithmetic


Integer functions and mixed functions can both return an integer result. The inner-
dmax and outer-dmax values are determined by the characteristics of the function.

Integer Functions
These functions always return an integer, and the outer-dmax will always be zero. For
those functions whose arguments must be integer, the inner-dmax will also always be
zero.

The following table summarizes the precision of the function results:

Figure 122 (Page 1 of 2). Precision of Integer Intrinsic Functions


Inner- Outer-
Function Dmax Dmax Function Result
DATE-OF-INTEGER 0 0 8-digit integer
DATE-TO-YYYYMMDD 0 0 8-digit integer
DAY-OF-INTEGER 0 0 7-digit integer
DAY-TO-YYYYDDD 0 0 7-digit integer
FACTORIAL 0 0 fixed-point, 30-digit integer
INTEGER-OF-DATE 0 0 7-digit integer
INTEGER-OF-DAY 0 0 7- digit integer
LENGTH n/a 0 9- digit integer
MOD 0 0 integer with as many digits as min(i1 i2)
ORD n/a 0 3-digit integer
ORD-MAX 0 9-digit integer
ORD-MIN 0 9-digit integer

Appendix C. Intermediate Results and Arithmetic Precision 475


Fixed-Point Data

Figure 122 (Page 2 of 2). Precision of Integer Intrinsic Functions


Inner- Outer-
Function Dmax Dmax Function Result
YEAR-TO-YYYY 0 0 4-digit integer
INTEGER 0 With a fixed-point argument, result will be fixed-
point integer with one more integer digit than the
argument. With a floating-point argument, result
will be fixed-point, 30-digit integer.
INTEGER-PART 0 With a fixed-point argument, result will be fixed-
point integer with the same number of integer
digits as the argument. With a floating-point
argument, result will be fixed-point, 30-digit
integer.

Mixed Functions
When the compiler handles a mixed function as fixed-point arithmetic, the result will be
either integer or fixed-point with decimals (when any argument is floating-point, the
function becomes a floating-point function and will follow floating-point rules). For MAX,
MIN, RANGE, REM, and SUM, the outer-dmax is always equal to the inner-dmax. To
determine the precision of the result returned for these functions, apply the rules for
fixed-point arithmetic to each step in the algorithm used to calculate the function result.

MAX

1. Assign the first argument to your function result.


2. For each remaining argument:
a. Compare the algebraic value of your function result with the argument.
b. Assign the greater of the two to your function result.

MIN

1. Assign the first argument to your function result.


2. For each remaining argument:
a. Compare the algebraic value of your function result with the argument.
b. Assign the lesser of the two to your function result.

RANGE

1. Use the steps for MAX to select your maximum argument.


2. Use the steps for MIN to select your minimum argument.
3. Subtract the minimum argument from the maximum.
4. Assign the difference to your function result.

REM

1. Divide argument-1 by argument-2.


2. Remove all non-integer digits from the result of step 1.
3. Multiply the result of step 2 by argument-2.
4. Subtract the result of step 3 from argument-1.

476 COBOL Set for AIX Programming Guide


Floating-Point Data

5. Assign the difference to your function result.

SUM

1. Assign the value 0 to your function result.


2. For each argument:
a. Add the argument to your function result.
b. Assign the sum to your function result.

Floating-Point Data and Intermediate Results


Floating-point instructions are used to compute an arithmetic expression if any of the
following conditions are true:
Ÿ A receiver or operand in the expression is COMP-1, COMP-2, external floating-point
data, or a floating-point literal.
Ÿ An exponent contains decimal places.
Ÿ An exponent is an expression that contains an exponentiation or divide operator
and dmax is greater than zero.
Ÿ An intrinsic numeric function is a floating-point function.

If any operation in an arithmetic expression is computed in floating-point, the entire


expression is computed as if all operands were converted to floating-point and the oper-
ations are evaluated using floating-point instructions.

If an expression is computed in floating-point, double-precision floating-point is used if


any receiver or operand in the expression is not COMP-1, or if a multiplication or
exponentiation operation appears in the expression. Whenever double-precision
floating-point is used for one operation in an arithmetic expression, all operations in the
expression are computed as if double-precision floating-point instructions were used.
Alert: If a floating-point operation has an intermediate result field in which exponent
overflow occurs, the job will be abnormally terminated.

Exponentiations Evaluated in Floating-Point Arithmetic


Floating-point exponentiations are always evaluated using double-precision floating-
point arithmetic.

The value of a negative number raised to a fractional power is undefined. For example,
(-2) ** 3 is equal to -8, but (-2) ** (3.000001) is not defined. When an exponentiation is
evaluated in floating-point and there is a possibility that the value of the exponentiation
will be undefined (as in the example above), then the value of the exponent is evalu-
ated at run time to determine if it is actually an integer.

Intrinsic Functions Evaluated in Floating-Point Arithmetic


The floating-point numeric functions will always return a double precision floating-point
value. For a list of the floating-point, fixed-point and mixed functions, see “Numeric
Intrinsic Functions” on page 39.

Appendix C. Intermediate Results and Arithmetic Precision 477


Arithmetic Expressions

Mixed functions with floating-point arguments will be evaluated using floating-point arith-
metic.

Arithmetic Expressions in Non-arithmetic Statements


Arithmetic expressions can appear in contexts other than arithmetic statements. For
example, an arithmetic expression can be used with the IF statement. In such state-
ments, the rules for intermediate results, floating point, and double-precision floating-
point apply, with the following changes:
Ÿ Abbreviated IF statements are handled as though the statements were not abbrevi-
ated.
Ÿ An explicit relation condition exists when a required relational operator is used to
define the comparison between two operands (here referred to as comparands). In
an explicit relation condition where one or both of the comparands is an arithmetic
expression, the rules for intermediate results are determined taking into consider-
ation the attributes of both comparands. That is to say, dmax is defined to be the
maximum number of decimal places defined for any operand of either comparand,
except divisors and exponents. The rules for floating-point and double-precision
floating-point apply if any of the following conditions are true:
– Any operand in either comparand is COMP-1, COMP-2, external floating- point
data, or a floating-point literal.
– An exponent contains decimal places.
– An exponent is an expression that contains an exponentiation or divide oper-
ator and dmax is greater than zero.
For example, in the statement:
IF operand-1 = expression-1 THEN . . .
where operand-1 is a data-name defined to be COMP-2, and expression-1 contains
only fixed-point operands, the rules for floating-point arithmetic apply to
expression-1 because it is being compared to a floating-point operand.
Ÿ When the comparison between an arithmetic expression and either a data item or
another arithmetic expression is defined without using a relational operator, then no
explicit relation condition is said to exist. Here, the arithmetic expression is evalu-
ated without regard to the attributes of the operand with which the comparison is
being made. For example, in the statement:
EVALUATE expression-1
WHEN expression-2 THRU expression-3
WHEN expression-4
.
.
END-EVALUATE
each arithmetic expression is evaluated in fixed-point or floating-point arithmetic
based on its own characteristics.

478 COBOL Set for AIX Programming Guide


Complex OCCURS DEPENDING ON

Appendix D. Complex OCCURS DEPENDING ON


Complex OCCURS DEPENDING ON (ODO) is supported as an extension to the COBOL
85 Standard.

The basic forms of complex ODO permitted by the compiler are:


Ÿ A data item described by an OCCURS clause with the DEPENDING ON option is fol-
lowed by a non-subordinate element or group (a variably-located item).
Ÿ A data item described by an OCCURS clause with the DEPENDING ON option is fol-
lowed by a non-subordinate data item described by an OCCURS clause with the
DEPENDING ON option (variably-located table).

Ÿ A data item described by an OCCURS clause with the DEPENDING ON option is


nested within another data item described by an OCCURS clause with the
DEPENDING ON option (table with variable-length elements).

Ÿ Index-name for a table with variable-length elements.

Be Sure to Set Values of ODO Objects


Every ODO object in an 01-level must be set before any reference is made to a
complex ODO item in the 01-level. (Note: An ODO object cannot be variably located.)
For instance, in the following example, before EMPLOYEE-NUMBER can be referred to,
COUNTER-1 and COUNTER-2 must be set, even though EMPLOYEE-NUMBER does not directly
depend on either of the ODO objects for its value.

The length of the variable portions of each record is the product of the ODO object and
the length of the subject of the OCCURS clause. The length is calculated at the time of
a reference to one of the following:
Ÿ A data item following, and not subordinate to, a variable-length table in the same
level-01 record (variably-located item).
.1/ in the following example.
Ÿ A group item following, and not subordinate to, a variable-length table in the same
level-01 record (variably-located group).
.2/ in the following example.
Ÿ An index name for a table that has variable-length elements.
.3/ in the following example.
Ÿ An element of a table that has variable-length elements.
.4/ in the following example.

 Copyright IBM Corp. 1996, 1998 479


Complex OCCURS DEPENDING ON

Complex ODO Example


Any item that meets one of these four criteria is considered to be a “complex ODO
item.” The following example illustrates each of the possible occurrences of a complex
ODO item.
ð1 FIELD-A.
ð2 COUNTER-1 PIC S99.
ð2 COUNTER-2 PIC S99.
ð2 TABLE-1.
ð3 RECORD-1 OCCURS 1 TO 5 TIMES
DEPENDING ON COUNTER-1 PIC X(3).
ð2 EMPLOYEE-NUMBER PIC X(5). .1/
ð2 TABLE-2 OCCURS 5 TIMES .2/
INDEXED BY INDX. .3/
ð3 TABLE-ITEM PIC 99. .4/
ð3 RECORD-2 OCCURS 1 TO 3 TIMES
DEPENDING ON COUNTER-2.
ð4 DATA-NUM PIC S99.

How Length Will be Calculated


Whenever a reference is made to one of these four data items, the actual length, if
used, is computed as follows:
Ÿ The contents of COUNTER-1 are multiplied by 3 to calculate the length of TABLE-1.
Ÿ The contents of COUNTER-2 are multiplied by 2 and added to the length of
TABLE-ITEM to calculate the length of TABLE-2.
Ÿ The length of FIELD-A is calculated by adding the length of COUNTER-1, COUNTER-2,
TABLE-1, EMPLOYEE-NUMBER, and TABLE-2 times 5.

Changes in ODO Object Value


If a data item described by an OCCURS clause with the DEPENDING ON option is fol-
lowed in the same level-01 record by non-subordinate data items, a change in the value
of the ODO object, and a subsequent reference to a complex ODO item during the
course of program execution, will have the following effects:
Ÿ The size of any group containing the related OCCURS clause will reflect the new
value of the ODO object.
Ÿ Whenever a MOVE to a group containing an ODO object is executed, the MOVE is
made based on the current contents of the object of the DEPENDING ON option.
Caution: The value of the ODO object may change because a MOVE is made to it
or to the group in which it is contained. The value of the ODO object may also
change because the group in which it is contained is a record area that has been
changed by execution of a READ statement.
Ÿ The location of any non-subordinate items following the item described with the
OCCURS clause will be affected by the new value of the ODO object. If you wish
to preserve the contents of these items, the following procedure can be used:
Prior to the change in the ODO object, move all non-subordinate items following

480 COBOL Set for AIX Programming Guide


Complex OCCURS DEPENDING ON

the variable item to a work area; after the change in the ODO object, move all the
items back.

Changing ODO Object with Complex-ODO Index Names


You must be careful when using complex-ODO index names. If you set an index name
(like 'INDX' in the previous example) for a table with variable-length entries
('TABLE-2'), and then change the value of the ODO object ('COUNTER-2'), be aware
that the offset in your index is no longer valid for the table, since the table has
changed. If, at this point, you were to code statements that used your index name,
thinking the index name had a valid value for the table, the statements would yield
unexpected results. This would apply to coding:
Ÿ A reference (using your index name) to an element of the table
Ÿ A format-1 SET statement of the type SET INTEGER-DATA-ITEM TO INDEX-NAME
Ÿ A format-2 SET statement of the type SET INDEX-NAME UP/DOWN BY INTEGER.

To avoid making this type of error, you can do the following:


1. Save the value of your index name (in the form of its integer occurrence number)
in an integer data-item before changing the ODO object.
2. Immediately after changing the ODO object, restore the value of your index name
from the integer data-item.

For example:
77 INTEGER-DATA-ITEM-1 PIC 99.

SET INDX TO 5
\ INDX is valid at this point.
SET INTEGER-DATA-ITEM-1 TO INDX
MOVE NEW-VALUE TO COUNTER-2.
\ INDX is not valid at this point.
SET INDX TO INTEGER-DATA-ITEM-1.
\ INDX Is now valid and can be
\ used with expected results.

Changing ODO Object with Variable Occurrence Table


The following example applies to changing an ODO object by adding an element to a
variable occurrence table with variably-located items following it. The example updates
a record containing an OCCURS clause with the DEPENDING ON option and at least one
other subsequent entry. In this case, the subsequent entry is another OCCURS clause
with the DEPENDING ON option.

Appendix D. Complex OCCURS DEPENDING ON 481


Complex OCCURS DEPENDING ON

WORKING-STORAGE SECTION.
ð1 VARIABLE-REC.
ð5 FIELD-1 PIC X(1ð).
ð5 CONTROL-1 PIC S99.
ð5 CONTROL-2 PIC S99.
ð5 VARY-FIELD-1 OCCURS 1 TO 1ð TIMES
DEPENDING ON CONTROL-1 PIC X(5).
ð5 GROUP-ITEM-1.
1ð VARY-FIELD-2
OCCURS 1 TO 1ð TIMES
DEPENDING ON CONTROL-2 PIC X(9).
ð1 STORE-VARY-FIELD-2.
ð5 GROUP-ITEM-2.
1ð VARY-FLD-2
OCCURS 1 TO 1ð TIMES
DEPENDING ON CONTROL-2 PIC X(9).

Assume that both CONTROL-1 and CONTROL-2 contain the value 3. In this situation,
storage for VARY-FIELD-1 and VARY-FIELD-2 would look like this:

┌──┬──┬──┬──┬──┐
VARY─FIELD─1(1) │ │ │ │ │ │
├──┼──┼──┼──┼──┤
VARY─FIELD─1(2) │ │ │ │ │ │
├──┼──┼──┼──┼──┤
VARY─FIELD─1(3) │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┬──┬──┬──┐
VARY─FIELD─2(1) │ │ │ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┼──┼──┤
VARY─FIELD─2(2) │ │ │ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┼──┼──┤
VARY─FIELD─2(3) │ │ │ │ │ │ │ │ │ │
└──┴──┴──┴──┴──┴──┴──┴──┴──┘

In order to add a fourth field to VARY-FIELD-1, the following steps are required to
prevent VARY-FIELD-1 from overlaying the first 5 bytes of VARY-FIELD-2:
MOVE GROUP-ITEM-1 TO GROUP-ITEM-2
ADD 1 TO CONTROL-1
MOVE "additional field" TO
VARY-FIELD-1 (CONTROL-1)
MOVE GROUP-ITEM-2 TO GROUP-ITEM-1

482 COBOL Set for AIX Programming Guide


Complex OCCURS DEPENDING ON

The updated storage for VARY-FIELD-1 and VARY-FIELD-2 would now look like this:

┌──┬──┬──┬──┬──┐
VARY─FIELD─1(1) │ │ │ │ │ │
├──┼──┼──┼──┼──┤
VARY─FIELD─1(2) │ │ │ │ │ │
├──┼──┼──┼──┼──┤
VARY─FIELD─1(3) │ │ │ │ │ │
├──┼──┼──┼──┼──┤
VARY─FIELD─1(4) │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┬──┬──┬──┐
VARY─FIELD─2(1) │ │ │ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┼──┼──┤
VARY─FIELD─2(2) │ │ │ │ │ │ │ │ │ │
├──┼──┼──┼──┼──┼──┼──┼──┼──┤
VARY─FIELD─2(3) │ │ │ │ │ │ │ │ │ │
└──┴──┴──┴──┴──┴──┴──┴──┴──┘

The intent of this last example is to emphasize that if you want to preserve the values
contained in data items that follow a variable-length item within the same record, you
must move them to another field prior to changing the length of the variable-length item,
and then move them back after the length indicator has been changed.

Appendix D. Complex OCCURS DEPENDING ON 483


CEECBLDY

Appendix E. Date and Time Callable Services Reference

CEECBLDY—Convert Date to COBOL Integer Format


CEECBLDY converts a string representing a date into a COBOL Integer format, which
is the number of days since 31 December 1600. This service is similar to CEEDAYS,
except that it provides a string in COBOL Integer format, which is compatible with ANSI
intrinsic functions. Use CEECBLDY to access the century window of the date and time
callable services and to perform date calculations with ANSI intrinsic functions.

Syntax
55──CALL──"CEECBLDY"──USING──input_char_date──,──picture_string──,─────5
5──output_Integer_date──,──fc──.──────────────────────────────────────5%

input_char_date (input)
A halfword length-prefixed character string, representing a date or timestamp, in a
format conforming to that specified by picture_string.
The character string must contain between 5 and 255 characters, inclusive.
input_char_date can contain leading or trailing blanks. Parsing for a date begins
with the first nonblank character (unless the picture string itself contains leading
blanks, in which case CEECBLDY skips exactly that many positions before parsing
begins).
After parsing a valid date, as determined by the format of the date specified in
picture_string, CEECBLDY ignores all remaining characters. Valid dates range
between and include 01 January 1601 to 31 December 9999.
See Figure 110 on page 426 for a list of valid picture character terms that can be
specified in input_char_date.

picture_string (input)
A halfword length-prefixed character string, indicating the format of the date speci-
fied in input_char_date.
Each character in the picture_string corresponds to a character in input_char_date.
For example, if you specify MMDDYY as the picture_string, CEECBLDY reads an
input_char_date of 060288 as 02 June 1988.
If delimiters such as the slash (/) appear in the picture string, leading zeros can be
omitted. For example, the following calls to CEECBLDY:
MOVE '6/2/88' TO DATEVAL-STRING.
MOVE 6 TO DATEVAL-LENGTH.
MOVE 'MM/DD/YY' TO PICSTR-STRING.
MOVE 8 TO PICSTR-LENGTH.
CALL CEECBLDY USING DATEVAL, PICSTR, COBINTDTE, FC.

484  Copyright IBM Corp. 1996, 1998


CEECBLDY

MOVE 'ð6/ð2/88' TO DATEVAL-STRING.


MOVE 8 TO DATEVAL-LENGTH.
MOVE 'MM/DD/YY' TO PICSTR-STRING.
MOVE 8 TO PICSTR-LENGTH.
CALL CEECBLDY USING DATEVAL, PICSTR, COBINTDTE, FC.
MOVE 'ð6ð288' TO DATEVAL-STRING.
MOVE 6 TO DATEVAL-LENGTH.
MOVE 'MMDDYY' TO PICSTR-STRING.
MOVE 6 TO PICSTR-LENGTH.
CALL CEECBLDY USING DATEVAL, PICSTR, COBINTDTE, FC.
MOVE '88154' TO DATEVAL-STRING.
MOVE 5 TO DATEVAL-LENGTH.
MOVE 'YYDDD' TO PICSTR-STRING.
MOVE 5 TO PICSTR-LENGTH.
CALL CEECBLDY USING DATEVAL, PICSTR, COBINTDTE, FC.
would each assign the same value, 141502 (02 June 1988), to COBINTDTE.
Whenever characters such as colons or slashes are included in the picture_string
(such as HH:MI:SS YY/MM/DD), they count as placeholders but are otherwise
ignored.
See Figure 110 on page 426 for a list of valid picture character terms and
Figure 111 on page 427 for examples of valid picture strings.
If picture_string includes a Japanese Era symbol <JJJJ>, the YY position in
input_char_date is replaced by the year number within the Japanese Era. For
example, the year 1988 equals the Japanese year 63 in the Showa era. See
Figure 111 on page 427 for an additional example. See Figure 112 on page 428
for a list of Japanese Eras supported.
If picture_string includes an ROC (Republic of China) Era symbol <CCCC> or
<CCCCCCCC>, the YY position in input_char_date is replaced by the year number
within the ROC Era. For example, the year 1988 equals the ROC year 77 in the
MinKow Era. See Figure 111 on page 427 for an additional example. See
Figure 113 on page 428 for a list of ROC Eras supported.

output_Integer_date (output)
A 32-bit binary integer representing the COBOL Integer date, the number of days
since 31 December 1600. For example, 16 May 1988 is day number 141485.
If input_char_date does not contain a valid date, output_Integer_date is set to 0
and CEECBLDY terminates with a non-CEE000 symbolic feedback code.
Date calculations are performed easily on the output_Integer_date, because
output_Integer_date is an integer. Leap year and end-of-year anomalies do not
affect the calculations.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Appendix E. Date and Time Callable Services Reference 485


CEECBLDY

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2EB 3 2507 Insufficient data was passed to CEEDAYS
or CEESECS. The Lilian value was not cal-
culated.
CEE2EC 3 2508 The date value passed to CEEDAYS or
CEESECS was invalid.
CEE2ED 3 2509 The Japanese or Republic of China Era
passed to CEEDAYS or CEESECS was not
recognized.
CEE2EH 3 2513 The input date passed in a CEEISEC,
CEEDAYS, or CEESECS call was not within
the supported range.
CEE2EL 3 2517 The month value in a CEEISEC call was not
recognized.
CEE2EM 3 2518 An invalid picture string was specified in a
call to a date/time service.
CEE2EO 3 2520 CEEDAYS detected non-numeric data in a
numeric field, or the date string did not
match the picture string.
CEE2EP 3 2521 The Japanese (<JJJJ>) or Chinese
(<CCCC>) year-within-Era value passed to
CEEDAYS or CEESECS was zero.

Usage Notes
Ÿ Call CEECBLDY only from COBOL programs that use the returned value as input
to COBOL intrinsic functions. You should not use the returned value with other
date and time callable services, nor should you call CEECBLDY from any
non-COBOL programs. Unlike CEEDAYS, there is no inverse function of
CEECBLDY, because it is only for COBOL users who want to use the date and
time century window service together with COBOL intrinsic functions for date calcu-
lations. The inverse function of CEECBLDY is provided by the
DATE-OF-INTEGER and DAY-OF-INTEGER intrinsic functions.
Ÿ To perform calculations on dates earlier than 1 January 1601, add 4000 to the year
in each date, convert the dates to COBOL Integer format, then do the calculation.
If the result of the calculation is a date, as opposed to a number of days, convert
the result to a date string and subtract 4000 from the year.
Ÿ By default, 2-digit years lie within the 100-year range starting 80 years prior to the
system date. Thus, in 1997, all 2-digit years represent dates between 1917 and
2016, inclusive. You can change this default range by using the CEESCEN call-
able service.

486 COBOL Set for AIX Programming Guide


CEECBLDY

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Invoke CEECBLDY callable service \\
\\ to convert date to COBOL Integer format. \\
\\ This service is used when using the \\
\\ Century Window feature of the date and time \\
\\ callable services mixed with COBOL \\
\\ Intrinsic Functions. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLDY.

DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 CHRDATE.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of CHRDATE.
ð1 PICSTR.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of PICSTR.
ð1 INTEGER PIC S9(9) BINARY.
ð1 NEWDATE PIC 9(8).
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.

Appendix E. Date and Time Callable Services Reference 487


CEEDATE

PROCEDURE DIVISION.
PARA-CBLDAYS.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify input date and length \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 25 TO Vstring-length of CHRDATE.
MOVE '1 January ðð'
to Vstring-text of CHRDATE.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify a picture string that describes \\
\\ input date, and set the string's length. \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 23 TO Vstring-length of PICSTR.
MOVE 'ZD Mmmmmmmmmmmmmmz YY'
TO Vstring-text of PICSTR.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEECBLDY to convert input date to a \\
\\ COBOL Integer date \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEECBLDY' USING CHRDATE, PICSTR,
INTEGER, FC.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEECBLDY runs successfully, then compute \\
\\ the date of the 9ðth day after the \\
\\ input date using Intrinsic Functions \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
COMPUTE INTEGER = INTEGER + 9ð
COMPUTE NEWDATE = FUNCTION
DATE-OF-INTEGER (INTEGER)
DISPLAY NEWDATE
' is Lilian day: ' INTEGER
ELSE
DISPLAY 'CEEBLDY failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEEDATE—Convert Lilian Date to Character Format


CEEDATE converts a number representing a Lilian date to a date written in character
format. The output is a character string, such as 1996/ð4/23.

488 COBOL Set for AIX Programming Guide


CEEDATE

Syntax
55──CALL──"CEEDATE"──USING──input_Lilian_date──,──picture_string──,────5
5──output_char_date──,──fc──.─────────────────────────────────────────5%

input_Lilian_date (input)
A 32-bit integer representing the Lilian date. The Lilian date is the number of days
since 14 October 1582. For example, 16 May 1988 is Lilian day number 148138.
The valid range of Lilian dates is 1 to 3,074,324 (15 October 1582 to 31 December
9999).

picture_string (input)
A halfword length-prefixed character string, representing the desired format of
output_char_date, for example MM/DD/YY. Each character in picture_string repres-
ents a character in output_char_date. If delimiters such as the slash (/) appear in
the picture string, they are copied as is to output_char_date.
See Figure 110 on page 426 for a list of valid picture characters, and Figure 111
on page 427 for examples of valid picture strings.
If picture_string includes a Japanese Era symbol <JJJJ>, the YY position in
output_char_date is replaced by the year number within the Japanese Era. For
example, the year 1988 equals the Japanese year 63 in the Showa era. See
Figure 111 on page 427 for an additional example. See Figure 112 on page 428
for a list of Japanese Eras supported.
If picture_string includes an ROC (Republic of China) Era symbol <CCCC> or
<CCCCCCCC>, the YY position in output_char_date is replaced by the year number
within the ROC Era. For example, the year 1988 equals the ROC year 77 in the
MinKow Era. See Figure 111 on page 427 for an additional example. See
Figure 113 on page 428 for a list of ROC Eras supported.

output_char_date (output)
A fixed-length 80-character string that is the result of converting input_Lilian_date
to the format specified by picture_string. See Figure 123 on page 492 for sample
output dates. If input_Lilian_date is invalid, output_char_date is set to all blanks
and CEEDATE terminates with a non-CEE000 symbolic feedback code.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2EG 3 2512 The Lilian date value passed in a call to
CEEDATE or CEEDYWK was not within the
supported range.

Appendix E. Date and Time Callable Services Reference 489


CEEDATE

Symbolic
Feedback Message
Code Severity Number Message Text
CEE2EM 3 2518 An invalid picture string was specified in a
call to a date/time service.
CEE2EQ 3 2522 Japanese (<JJJJ>) or Republic of China
(<CCCC> or <CCCCCCCC>) Era was used
in a picture string passed to CEEDATE, but
the Lilian date value was not within the sup-
ported range. The era could not be deter-
mined.
CEE2EU 2 2526 The date string returned by CEEDATE was
truncated.
CEE2F6 1 2534 Insufficient field width was specified for a
month or weekday name in a call to
CEEDATE or CEEDATM. Output set to
blanks.

Usage Notes
Ÿ The inverse of CEEDATE is CEEDAYS, which converts character dates to the
Lilian format.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: CEEDATE - convert Lilian date to \\
\\ character format \\
\\ \\
\\ In this example, a call is made to CEEDATE \\
\\ to convert a Lilian date (the number of \\
\\ days since 14 October 1582) to a character \\
\\ format (such as 6/22/88). The result is \\
\\ displayed. The Lilian date is obtained \\
\\ via a call to CEEDAYS. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLDATE.
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 LILIAN PIC S9(9) BINARY.

490 COBOL Set for AIX Programming Guide


CEEDATE

ð1 CHRDATE PIC X(8ð).


ð1 IN-DATE.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of IN-DATE.
ð1 PICSTR.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of PICSTR.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.

PROCEDURE DIVISION.
PARA-CBLDAYS.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEEDAYS to convert date of 6/2/88 to \\
\\ Lilian representation \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 6 TO Vstring-length of IN-DATE.
MOVE '6/2/88' TO Vstring-text of IN-DATE(1:6).
MOVE 8 TO Vstring-length of PICSTR.
MOVE 'MM/DD/YY' TO Vstring-text of PICSTR(1:8).
CALL 'CEEDAYS' USING IN-DATE, PICSTR,
LILIAN, FC.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEEDAYS runs successfully, display result\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY Vstring-text of IN-DATE
' is Lilian day: ' LILIAN
ELSE
DISPLAY 'CEEDAYS failed with msg '

Appendix E. Date and Time Callable Services Reference 491


CEEDATE

Msg-No of FC UPON CONSOLE


STOP RUN
END-IF.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify picture string that describes the \\
\\ desired format of the output from CEEDATE, \\
\\ and the picture string's length. \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 23 TO Vstring-length OF PICSTR.
MOVE 'ZD Mmmmmmmmmmmmmmz YYYY' TO
Vstring-text OF PICSTR(1:23).

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEEDATE to convert the Lilian date \\
\\ to a picture string. \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEEDATE' USING LILIAN, PICSTR,
CHRDATE, FC.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEEDATE runs successfully, display result\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY 'Input Lilian date of ' LILIAN
' corresponds to: ' CHRDATE
ELSE
DISPLAY 'CEEDATE failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

Figure 123 shows the sample output from CEEDATE.

Figure 123 (Page 1 of 2). Sample Output of CEEDATE

input_Lilian_date picture_string output_char_date


148138 YY 88
YYMM 8805
YY-MM 88-05
YYMMDD 880516
YYYYMMDD 19880516
YYYY-MM-DD 1988-05-16
YYYY-ZM-ZD 1988-5-16
<JJJJ> YY.MM.DD Showa 63.05.16 (in a DBCS
string)
<CCCC> YY.MM.DD MinKow 77.05.16 (in a DBCS
string)

492 COBOL Set for AIX Programming Guide


CEEDATM

Figure 123 (Page 2 of 2). Sample Output of CEEDATE

input_Lilian_date picture_string output_char_date


148139 MM 05
MMDD 0517
MM/DD 05/17
MMDDYY 051788
MM/DD/YYYY 05/17/1988
ZM/DD/YYYY 5/17/1988
148140 DD 18
DDMM 1805
DDMMYY 180588
DD.MM.YY 18.05.88
DD.MM.YYYY 18.05.1988
DD Mmm YYYY 18 May 1988
148141 DDD 140
YYDDD 88140
YY.DDD 88.140
YYYY.DDD 1988.140
148142 YY/MM/DD HH:MI:SS.99 88/05/20 00:00:00.00
YYYY/ZM/ZD ZH:MI AP 1988/5/20 0:00 AM
148143 WWW., MMM DD, YYYY SAT., MAY 21, 1988
Www., Mmm DD, YYYY Sat., May 21, 1988

Wwwwwwwwww, Saturday ,
Mmmmmmmmmm DD, YYYY May 21, 1988

Wwwwwwwwwz, Saturday, May 21, 1988


Mmmmmmmmmz DD, YYYY

CEEDATM—Convert Seconds to Character Timestamp


CEEDATM converts a number representing the number of seconds since 00:00:00 14
October 1582 to a character string format. The format of the output is a character
string timestamp, for example, 1988/ð7/26 2ð:37:ðð.

Syntax
55──CALL──"CEEDATM"──USING──input_seconds──,──picture_string──,────────5
5──output_timestamp──,──fc──.─────────────────────────────────────────5%

input_seconds (input)
A 64-bit double floating-point number representing the number of seconds since
00:00:00 on 14 October 1582, not counting leap seconds.
For example, 00:00:01 on 15 October 1582 is second number 86,401 (24*60*60 +
01). The valid range of input_seconds is 86,400 to 265,621,679,999.999
(23:59:59.999 31 December 9999).

Appendix E. Date and Time Callable Services Reference 493


CEEDATM

picture_string (input)
A halfword length-prefixed character string, representing the desired format of
output_timestamp, for example, MM/DD/YY HH:MI AP.
Each character in the picture_string represents a character in output_timestamp. If
delimiters such as a slash (/) appear in the picture string, they are copied as is to
output_timestamp.
See Figure 110 on page 426 for a list of valid picture character terms and
Figure 111 on page 427 for examples of valid picture strings.
If picture_string includes the Japanese Era symbol <JJJJ>, the YY position in
output_timestamp represents the year within Japanese Era. See Figure 111 on
page 427 for an example. See Figure 112 on page 428 for a list of Japanese
Eras supported.
If picture_string includes the ROC (Republic of China) Era symbol <CCCC> or
<CCCCCCCC>, the YY position in output_timestamp represents the year within ROC
Era. See Figure 111 on page 427 for an example. See Figure 113 on page 428
for a list of ROC Eras supported.

output_timestamp (output)
A fixed-length 80-character string that is the result of converting input_seconds to
the format specified by picture_string.
If necessary, the output is truncated to the length of output_timestamp. See
Figure 124 on page 497 for sample output.
If input_seconds is invalid, output_timestamp is set to all blanks and CEEDATM
terminates with a non-CEE000 symbolic feedback code.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2E9 3 2505 The input_seconds value in a call to
CEEDATM or CEESECI was not within the
supported range.
CEE2EA 3 2506 Japanese (<JJJJ>) or Republic of China
(<CCCC> or <CCCCCCCC>) Era was used
in a picture string passed to CEEDATM, but
the input number-of-seconds value was not
within the supported range. The era could
not be determined.
CEE2EM 3 2518 An invalid picture string was specified in a
call to a date/time service.
CEE2EV 2 2527 The timestamp string returned by
CEEDATM was truncated.

494 COBOL Set for AIX Programming Guide


CEEDATM

Symbolic
Feedback Message
Code Severity Number Message Text
CEE2F6 1 2534 Insufficient field width was specified for a
month or weekday name in a call to
CEEDATE or CEEDATM. Output set to
blanks.

Usage Notes
Ÿ The inverse of CEEDATM is CEESECS, which converts a timestamp to number of
seconds.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: CEEDATM - convert seconds to \\
\\ character timestamp \\
\\ \\
\\ In this example, a call is made to CEEDATM \\
\\ to convert a date represented in Lilian \\
\\ seconds (the number of seconds since \\
\\ ðð:ðð:ðð 14 October 1582) to a character \\
\\ format (such as ð6/ð2/88 1ð:23:45). The \\
\\ result is displayed. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLDATM.
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 DEST PIC S9(9) BINARY VALUE 2.
ð1 SECONDS COMP-2.
ð1 IN-DATE.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of IN-DATE.
ð1 PICSTR.
ð2 Vstring-length PIC S9(4) BINARY.

Appendix E. Date and Time Callable Services Reference 495


CEEDATM

ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of PICSTR.
ð1 TIMESTP PIC X(8ð).
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.

PROCEDURE DIVISION.
PARA-CBLDATM.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEESECS to convert timestamp of 6/2/88 \\
\\ at 1ð:23:45 AM to Lilian representation \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 2ð TO Vstring-length of IN-DATE.
MOVE 'ð6/ð2/88 1ð:23:45 AM'
TO Vstring-text of IN-DATE.
MOVE 2ð TO Vstring-length of PICSTR.
MOVE 'MM/DD/YY HH:MI:SS AP'
TO Vstring-text of PICSTR.
CALL 'CEESECS' USING IN-DATE, PICSTR,
SECONDS, FC.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEESECS runs successfully, display result\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY Vstring-text of IN-DATE
' is Lilian second: ' SECONDS
ELSE
DISPLAY 'CEESECS failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify desired format of the output. \\

496 COBOL Set for AIX Programming Guide


CEEDATM

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 35 TO Vstring-length OF PICSTR.
MOVE 'ZD Mmmmmmmmmmmmmmz YYYY at HH:MI:SS'
TO Vstring-text OF PICSTR.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEEDATM to convert Lilian seconds to \\
\\ a character timestamp \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEEDATM' USING SECONDS, PICSTR,
TIMESTP, FC.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEEDATM runs successfully, display result\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY 'Input seconds of ' SECONDS
' corresponds to: ' TIMESTP
ELSE
DISPLAY 'CEEDATM failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

Figure 124 shows the sample output of CEEDATM.

Figure 124 (Page 1 of 2). Sample Output of CEEDATM

input_seconds picture_string output_timestamp


12,799,191,601.000 YYMMDD 880516
HH:MI:SS 19:00:01
YY-MM-DD 88-05-16
YYMMDDHHMISS 880516190001
YY-MM-DD HH:MI:SS 88-05-16 19:00:01

YYYY-MM-DD HH:MI:SS 1988-05-16 07:00:01


AP PM
12,799,191,661.986 DD Mmm YY 16 May 88
DD MMM YY HH:MM 16 MAY 88 19:01

WWW, MMM DD, YYYY MON, MAY 16, 1988


ZH:MI AP 7:01 PM

Wwwwwwwwwz, ZM/ZD/YY Monday, 5/16/88


HH:MI:SS.99 19:01:01.98

Appendix E. Date and Time Callable Services Reference 497


CEEDAYS

Figure 124 (Page 2 of 2). Sample Output of CEEDATM

input_seconds picture_string output_timestamp


12,799,191,662.009 YYYY 1988
YY 88
Y 8
MM ð5
ZM 5
RRRR V␣␣␣
MMM MAY
Mmm May
Mmmmmmmmmm May␣␣␣␣␣␣
Mmmmmmmmmz May
DD 16
ZD 16
DDD 137
HH 19
ZH 19
MI ð1
SS ð2
99 ðð
999 ðð9
AP PM
WWW MON
Www Mon
Wwwwwwwwww Monday␣␣␣␣
Wwwwwwwwwz Monday

CEEDAYS—Convert Date to Lilian Format


CEEDAYS converts a string representing a date into a Lilian format, which represents a
date as the number of days from the beginning of the Gregorian calendar. CEEDAYS
converts the specified input_char_date to a number representing the number of days
since day zero in the Lilian format: Friday, 14 October, 1582.

Do not use CEEDAYS in combination with COBOL intrinsic functions. Use CEECBLDY
for programs that use intrinsic functions.

Syntax
55──CALL──"CEEDAYS"──USING──input_char_date──,──picture_string──,──────5
5──output_Lilian_date──,──fc──.───────────────────────────────────────5%

input_char_date (input)
A halfword length-prefixed character string, representing a date or timestamp, in a
format conforming to that specified by picture_string.
The character string must contain between 5 and 255 characters, inclusive.
input_char_date can contain leading or trailing blanks. Parsing for a date begins
with the first nonblank character (unless the picture string itself contains leading

498 COBOL Set for AIX Programming Guide


CEEDAYS

blanks, in which case CEEDAYS skips exactly that many positions before parsing
begins).
After parsing a valid date, as determined by the format of the date specified in
picture_string, CEEDAYS ignores all remaining characters. Valid dates range
between and include 15 October 1582 to 31 December 9999.
See Figure 110 on page 426 for a list of valid picture character terms that can be
specified in input_char_date.

picture_string (input)
A halfword length-prefixed character string, indicating the format of the date speci-
fied in input_char_date.
Each character in the picture_string corresponds to a character in input_char_date.
For example, if you specify MMDDYY as the picture_string, CEEDAYS reads an
input_char_date of 060288 as 02 June 1988.
If delimiters such as a slash (/) appear in the picture string, leading zeros can be
omitted. For example, the following calls to CEEDAYS:
CALL CEEDAYS USING '6/2/88' , 'MM/DD/YY', lildate, fc.
CALL CEEDAYS USING 'ð6/ð2/88', 'MM/DD/YY', lildate, fc.
CALL CEEDAYS USING 'ð6ð288' , 'MMDDYY' , lildate, fc.
CALL CEEDAYS USING '88154' , 'YYDDD' , lildate, fc.
would each assign the same value, 148155 (02 June 1988), to lildate.
Whenever characters such as colons or slashes are included in the picture_string
(such as HH:MI:SS YY/MM/DD), they count as placeholders but are otherwise
ignored.
See Figure 110 on page 426 for a list of valid picture character terms, and
Figure 111 on page 427 for examples of valid picture strings.
If picture_string includes a Japanese Era symbol <JJJJ>, the YY position in
input_char_date is replaced by the year number within the Japanese Era. For
example, the year 1988 equals the Japanese year 63 in the Showa era. See
Figure 111 on page 427 for an additional example. See Figure 112 on page 428
for a list of Japanese Eras supported.
If picture_string includes an ROC (Republic of China) Era symbol <CCCC> or
<CCCCCCCC>, the YY position in input_char_date is replaced by the year number
within the ROC Era. For example, the year 1988 equals the ROC year 77 in the
MinKow Era. See Figure 111 on page 427 for an additional example. See
Figure 113 on page 428 for a list of ROC Eras supported.

output_Lilian_date (output)
A 32-bit binary integer representing the Lilian date, the number of days since 14
October 1582. For example, 16 May 1988 is day number 148138.
If input_char_date does not contain a valid date, output_Lilian_date is set to 0 and
CEEDAYS terminates with a non-CEE000 symbolic feedback code.
Date calculations are performed easily on the output_Lilian_date, because it is an
integer. Leap year and end-of-year anomalies do not affect the calculations.

Appendix E. Date and Time Callable Services Reference 499


CEEDAYS

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2EB 3 2507 Insufficient data was passed to CEEDAYS
or CEESECS. The Lilian value was not cal-
culated.
CEE2EC 3 2508 The date value passed to CEEDAYS or
CEESECS was invalid.
CEE2ED 3 2509 The Japanese or Republic of China Era
passed to CEEDAYS or CEESECS was not
recognized.
CEE2EH 3 2513 The input date passed in a CEEISEC,
CEEDAYS, or CEESECS call was not within
the supported range.
CEE2EL 3 2517 The month value in a CEEISEC call was not
recognized.
CEE2EM 3 2518 An invalid picture string was specified in a
call to a date/time service.
CEE2EO 3 2520 CEEDAYS detected non-numeric data in a
numeric field, or the date string did not
match the picture string.
CEE2EP 3 2521 The Japanese (<JJJJ>) or Chinese
(<CCCC>) year-within-Era value passed to
CEEDAYS or CEESECS was zero.

Usage Notes
Ÿ The inverse of CEEDAYS is CEEDATE, which converts output_Lilian_date from
Lilian format to character format.
Ÿ To perform calculations on dates earlier than 15 October 1582, add 4000 to the
year in each date, convert the dates to Lilian, then do the calculation. If the result
of the calculation is a date, as opposed to a number of days, convert the result to a
date string and subtract 4000 from the year.
Ÿ By default, 2-digit years lie within the 100-year range starting 80 years prior to the
system date. Thus, in 1997, all 2-digit years represent dates between 1917 and
2016, inclusive. This default range is changed by using the callable service
CEESCEN.
Ÿ Date calculations can be performed easily on the output_Lilian_date, because it is
an integer. Leap year and end-of-year anomalies are avoided.

500 COBOL Set for AIX Programming Guide


CEEDAYS

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: CEEDAYS - convert date to \\
\\ Lilian format \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLDAYS.
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 CHRDATE.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of CHRDATE.
ð1 PICSTR.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of PICSTR.
ð1 LILIAN PIC S9(9) BINARY.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.

PROCEDURE DIVISION.
PARA-CBLDAYS.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify input date and length \\

Appendix E. Date and Time Callable Services Reference 501


CEEDYWK

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 16 TO Vstring-length of CHRDATE.
MOVE '1 January 2ððð'
TO Vstring-text of CHRDATE.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify a picture string that describes \\
\\ input date, and the picture string's length.\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 25 TO Vstring-length of PICSTR.
MOVE 'ZD Mmmmmmmmmmmmmmz YYYY'
TO Vstring-text of PICSTR.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEEDAYS to convert input date to a \\
\\ Lilian date \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEEDAYS' USING CHRDATE, PICSTR,
LILIAN, FC.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEEDAYS runs successfully, display result\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY Vstring-text of CHRDATE
' is Lilian day: ' LILIAN
ELSE
DISPLAY 'CEEDAYS failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEEDYWK—Calculate Day of Week from Lilian Date


CEEDYWK calculates the day of the week on which a Lilian date falls. The day of the
week is returned to the calling routine as a number between 1 and 7.

The number returned by CEEDYWK is useful for end-of-week calculations.

Syntax
55──CALL──"CEEDYWK"──USING──input_Lilian_date──,──output_day_no──,─────5
5──fc──.──────────────────────────────────────────────────────────────5%

input_Lilian_date (input)
A 32-bit binary integer representing the Lilian date, the number of days since 14
October 1582.
For example, 16 May 1988 is day number 148138. The valid range of
input_Lilian_date is between 1 and 3,074,324 (15 October 1582 and 31 December
9999).

502 COBOL Set for AIX Programming Guide


CEEDYWK

output_day_no (output)
A 32-bit binary integer representing input_Lilian_date's day-of-week: 1 equals
Sunday, 2 equals Monday, ..., 7 equals Saturday.
If input_Lilian_date is invalid, output_day_no is set to 0 and CEEDYWK terminates
with a non-CEE000 symbolic feedback code.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2EG 3 2512 The Lilian date value passed in a call to
CEEDATE or CEEDYWK was not within the
supported range.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEEDYWK to calculate the \\
\\ day of the week from Lilian date \\
\\ \\
\\ In this example, a call is made to CEEDYWK \\
\\ to return the day of the week on which a \\
\\ Lilian date falls. (A Lilian date is the \\
\\ number of days since 14 October 1582) \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLDYWK.
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 LILIAN PIC S9(9) BINARY.
ð1 DAYNUM PIC S9(9) BINARY.
ð1 IN-DATE.

Appendix E. Date and Time Callable Services Reference 503


CEEDYWK

ð2 Vstring-length PIC S9(4) BINARY.


ð2 Vstring-text.
ð3 Vstring-char PIC X,
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of IN-DATE.
ð1 PICSTR.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X,
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of PICSTR.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.

PROCEDURE DIVISION.
PARA-CBLDAYS.
\\ Call CEEDAYS to convert date of 6/2/88 to
\\ Lilian representation
MOVE 6 TO Vstring-length of IN-DATE.
MOVE '6/2/88' TO Vstring-text of IN-DATE(1:6).
MOVE 8 TO Vstring-length of PICSTR.
MOVE 'MM/DD/YY' TO Vstring-text of PICSTR(1:8).
CALL 'CEEDAYS' USING IN-DATE, PICSTR,
LILIAN, FC.

\\ If CEEDAYS runs successfully, display result.


IF CEEððð of FC THEN
DISPLAY Vstring-text of IN-DATE
' is Lilian day: ' LILIAN
ELSE
DISPLAY 'CEEDAYS failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

PARA-CBLDYWK.

504 COBOL Set for AIX Programming Guide


CEEGMT

\\ Call CEEDYWK to return the day of the week on


\\ which the Lilian date falls
CALL 'CEEDYWK' USING LILIAN , DAYNUM , FC.

\\ If CEEDYWK runs successfully, print results


IF CEEððð of FC THEN
DISPLAY 'Lilian day ' LILIAN
' falls on day ' DAYNUM
' of the week, which is a:'
\\ Select DAYNUM to display the name of the day
\\ of the week.
EVALUATE DAYNUM
WHEN 1
DISPLAY 'Sunday.'
WHEN 2
DISPLAY 'Monday.'
WHEN 3
DISPLAY 'Tuesday'
WHEN 4
DISPLAY 'Wednesday.'
WHEN 5
DISPLAY 'Thursday.'
WHEN 6
DISPLAY 'Friday.'
WHEN 7
DISPLAY 'Saturday.'
END-EVALUATE
ELSE
DISPLAY 'CEEDYWK failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEEGMT—Get Current Greenwich Mean Time


CEEGMT returns the current Greenwich Mean Time (GMT) as both a Lilian date and as
the number of seconds since 00:00:00 14 October 1582. GMT is also known as Coor-
dinated Universal Time (UTC). The returned values are compatible with those gener-
ated and used by the other date and time callable services.

Appendix E. Date and Time Callable Services Reference 505


CEEGMT

Syntax
55──CALL──"CEEGMT"──USING──output_GMT_Lilian──,──output_GMT_seconds────5
5──,──fc──.───────────────────────────────────────────────────────────5%

output_GMT_Lilian (output)
A 32-bit binary integer representing the current date in Greenwich, England, in the
Lilian format (the number of days since 14 October 1582).
For example, 16 May 1988 is day number 148138. If GMT is not available from
the system, output_GMT_Lilian is set to 0 and CEEGMT terminates with a
non-CEE000 symbolic feedback code.

output_GMT_seconds (output)
A 64-bit double floating-point number representing the current date and time in
Greenwich, England, as the number of seconds since 00:00:00 on 14 October
1582, not counting leap seconds.
For example, 00:00:01 on 15 October 1582 is second number 86,401 (24*60*60 +
01). 19:00:01.078 on 16 May 1988 is second number 12,799,191,601.078. If GMT
is not available from the system, output_GMT_seconds is set to 0 and CEEGMT
terminates with a non-CEE000 symbolic feedback code.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2E6 3 2502 The UTC/GMT was not available from the
system.

Usage Notes
Ÿ CEEDATE converts output_GMT_Lilian to a character date, and CEEDATM con-
verts output_GMT_seconds to a character timestamp.
Ÿ In order for the results of this service to be meaningful, your system's clock must
be set to the local time and the environment variable TZ must be set correctly.
See “Setting Environment Variables” on page 128 for details on how to set envi-
ronment variables and “Run-Time Environment Variables” on page 130 for specific
information about the TZ environment variable.
Ÿ The values returned by CEEGMT are handy for elapsed time calculations. For
example, you can calculate the time elapsed between two calls to CEEGMT by
calculating the differences between the returned values.
Ÿ CEEUTC is identical to this service.

506 COBOL Set for AIX Programming Guide


CEEGMT

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEEGMT to get current \\
\\ Greenwich Mean Time \\
\\ \\
\\ In this example, a call is made to CEEGMT \\
\\ to return the current GMT as a Lilian date \\
\\ and as Lilian seconds. The results are \\
\\ displayed. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. IGZTGMT.
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 LILIAN PIC S9(9) BINARY.
ð1 SECS COMP-2.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.
PARA-CBLGMT.
CALL 'CEEGMT' USING LILIAN , SECS , FC.

IF CEEððð of FC THEN
DISPLAY 'The current GMT is also '
'known as Lilian day: ' LILIAN
DISPLAY 'The current GMT in Lilian '

Appendix E. Date and Time Callable Services Reference 507


CEEGMTO

'seconds is: ' SECS


ELSE
DISPLAY 'CEEGMT failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEEGMTO—Get Offset from Greenwich Mean Time to Local Time


CEEGMTO returns values to the calling routine representing the difference between the
local system time and Greenwich Mean Time (GMT).

Syntax
55──CALL──"CEEGMTO"──USING──offset_hours──,──offset_minutes──,─────────5
5──offset_seconds──,──fc──.───────────────────────────────────────────5%

offset_hours (output)
A 32-bit binary integer representing the offset from GMT to local time, in hours.
For example, for Pacific Standard Time, offset_hours equals -8.
The range of offset_hours is -12 to +13 (+13 = Daylight Savings Time in the +12
time zone).
If local time offset is not available, offset_hours equals 0 and CEEGMTO termi-
nates with a non-CEE000 symbolic feedback code.

offset_minutes (output)
A 32-bit binary integer representing the number of additional minutes that local time
is ahead of or behind GMT.
The range of offset_minutes is 0 to 59.
If the local time offset is not available, offset_minutes equals 0 and CEEGMTO
terminates with a non-CEE000 symbolic feedback code.

offset_seconds (output)
A 64-bit double floating-point number representing the offset from GMT to local
time, in seconds.
For example, Pacific Standard Time is eight hours behind GMT. If local time is in
the Pacific time zone during standard time, CEEGMTO would return -28,800 (-8 *
60 * 60). The range of offset_seconds is -43,200 to +46,800. offset_seconds can
be used with CEEGMT to calculate local date and time. See “CEEGMT—Get
Current Greenwich Mean Time” on page 505 for more information.
If the local time offset is not available from the system, offset_seconds is set to 0
and CEEGMTO terminates with a non-CEE000 symbolic feedback code.

508 COBOL Set for AIX Programming Guide


CEEGMTO

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2E7 3 2503 The offset from UTC/GMT to local time was
not available from the system.

Usage Notes
Ÿ CEEDATM is used to convert offset_seconds to a character timestamp.
Ÿ In order for the results of this service to be meaningful, your system's clock must
be set to the local time and the environment variable TZ must be set correctly.
See “Setting Environment Variables” on page 128 for details on how to set envi-
ronment variables and “Run-Time Environment Variables” on page 130 for specific
information about the TZ environment variable.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEEGMTO to get offset from \\
\\ Greenwich Mean Time to local \\
\\ time \\
\\ \\
\\ In this example, a call is made to CEEGMTO \\
\\ to return the offset from GMT to local time \\
\\ as separate binary integers representing \\
\\ offset hours, minutes, and seconds. The \\
\\ results are displayed. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. IGZTGMTO.

DATA DIVISION.
WORKING-STORAGE SECTION.

Appendix E. Date and Time Callable Services Reference 509


CEEISEC

ð1 HOURS PIC S9(9) BINARY.


ð1 MINUTES PIC S9(9) BINARY.
ð1 SECONDS COMP-2.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.
PARA-CBLGMTO.
CALL 'CEEGMTO' USING HOURS , MINUTES ,
SECONDS , FC.

IF CEEððð of FC THEN
DISPLAY 'Local time differs from GMT '
'by: ' HOURS ' hours, '
MINUTES ' minutes, OR '
SECONDS ' seconds. '
ELSE
DISPLAY 'CEEGMTO failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEEISEC—Convert Integers to Seconds


CEEISEC converts separate binary integers representing year, month, day, hour,
minute, second, and millisecond to a number representing the number of seconds since
00:00:00 14 October 1582. Use CEEISEC instead of CEESECS when the input is in
numeric format rather than character format.

Syntax
55──CALL──"CEEISEC"──USING──input_year──,──input_months──,─────────────5
5──input_day──,──input_hours──,──input_minutes──,──input_seconds──,────5
5──input_milliseconds──,──output_seconds──,──fc──.────────────────────5%

input_year (input)
A 32-bit binary integer representing the year.
The range of valid values for input_year is 1582 to 9999, inclusive.

510 COBOL Set for AIX Programming Guide


CEEISEC

input_month (input)
A 32-bit binary integer representing the month.
The range of valid values for input_month is 1 to 12.

input_day (input)
A 32-bit binary integer representing the day.
The range of valid values for input_day is 1 to 31.

input_hours (input)
A 32-bit binary integer representing the hours.
The range of valid values for input_hours is 0 to 23.

input_minutes (input)
A 32-bit binary integer representing the minutes.
The range of valid values for input_minutes is 0 to 59.

input_seconds (input)
A 32-bit binary integer representing the seconds.
The range of valid values for input_seconds is 0 to 59.

input_milliseconds (input)
A 32-bit binary integer representing milliseconds.
The range of valid values for input_milliseconds is 0 to 999.

output_seconds (output)
A 64-bit double floating-point number representing the number of seconds since
00:00:00 on 14 October 1582, not counting leap seconds.
For example, 00:00:01 on 15 October 1582 is second number 86,401 (24*60*60 +
01). The valid range of output_seconds is 86,400 to 265,621,679,999.999
(23:59:59.999 31 December 9999).
If any input values are invalid, output_seconds is set to zero.
To convert output_seconds to a Lilian day number, divide output_seconds by
86,400 (the number of seconds in a day).

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2EE 3 2510 The hours value in a call to CEEISEC or
CEESECS was not recognized.

Appendix E. Date and Time Callable Services Reference 511


CEEISEC

Symbolic
Feedback Message
Code Severity Number Message Text
CEE2EF 3 2511 The day parameter passed in a CEEISEC
call was invalid for year and month speci-
fied.
CEE2EH 3 2513 The input date passed in a CEEISEC,
CEEDAYS, or CEESECS call was not within
the supported range.
CEE2EI 3 2514 The year value passed in a CEEISEC call
was not within the supported range.
CEE2EJ 3 2515 The milliseconds value in a CEEISEC call
was not recognized.
CEE2EK 3 2516 The minutes value in a CEEISEC call was
not recognized.
CEE2EL 3 2517 The month value in a CEEISEC call was not
recognized.
CEE2EN 3 2519 The seconds value in a CEEISEC call was
not recognized.

Usage Notes
Ÿ The inverse of CEEISEC is CEESECI, which converts number of seconds to
integer year, month, day, hour, minute, second, and millisecond.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEEISEC to convert integers \\
\\ to seconds \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLISEC.
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 YEAR PIC S9(9) BINARY.
ð1 MONTH PIC S9(9) BINARY.
ð1 DAYS PIC S9(9) BINARY.

512 COBOL Set for AIX Programming Guide


CEEISEC

ð1 HOURS PIC S9(9) BINARY.


ð1 MINUTES PIC S9(9) BINARY.
ð1 SECONDS PIC S9(9) BINARY.
ð1 MILLSEC PIC S9(9) BINARY.
ð1 OUTSECS COMP-2.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.
PARA-CBLISEC.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify seven binary integers representing \\
\\ the date and time as input to be converted \\
\\ to Lilian seconds \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 2ððð TO YEAR.
MOVE 1 TO MONTH.
MOVE 1 TO DAYS.
MOVE ð TO HOURS.
MOVE ð TO MINUTES.
MOVE ð TO SECONDS.
MOVE ð TO MILLSEC.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEEISEC to convert the integers \\
\\ to seconds \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEEISEC' USING YEAR, MONTH, DAYS,
HOURS, MINUTES, SECONDS,
MILLSEC, OUTSECS , FC.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEEISEC runs successfully, display result\\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY MONTH '/' DAYS '/' YEAR
' AT ' HOURS ':' MINUTES ':' SECONDS

Appendix E. Date and Time Callable Services Reference 513


CEELOCT

' is equivalent to ' OUTSECS ' seconds'


ELSE
DISPLAY 'CEEISEC failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEELOCT—Get Current Local Date or Time


CEELOCT returns the current local date or time in three formats:
Ÿ Lilian date (the number of days since 14 October 1582)
Ÿ Lilian seconds (the number of seconds since 00:00:00 14 October 1582)
Ÿ Gregorian character string (in the form YYYYMMDDHHMISS999).
These values are compatible with other date and time callable services, and with
existing language intrinsic functions.

CEELOCT performs the same function as calling the CEEGMT, CEEGMTO, and
CEEDATM date and time services separately. CEELOCT, however, performs the same
services with much greater speed.

Syntax
55──CALL──"CEELOCT"──USING──output_Lilian──,──output_seconds──,────────5
5──output_Gregorian──,──fc──.─────────────────────────────────────────5%

output_Lilian (output)
A 32-bit binary integer representing the current local date in the Lilian format, that
is, day 1 equals 15 October 1582, day 148,887 equals 4 June 1990.
If the local time is not available from the system, output_Lilian is set to 0 and
CEELOCT terminates with a non-CEE000 symbolic feedback code.

output_seconds (output)
A 64-bit double-floating point number representing the current local date and time
as the number of seconds since 00:00:00 on 14 October 1582, not counting leap
seconds. For example, 00:00:01 on 15 October 1582 is second number 86,401
(24*60*60 + 01). 19:00:01.078 on 4 June 1990 is second number
12,863,905,201.078.
If the local time is not available from the system, output_seconds is set to 0 and
CEELOCT terminates with a non-CEE000 symbolic feedback code.

output_Gregorian (output)
A 17-byte fixed-length character string in the form YYYYMMDDHHMISS999 repres-
enting local year, month, day, hour, minute, second, and millisecond.

514 COBOL Set for AIX Programming Guide


CEELOCT

If the format of output_Gregorian does not meet your needs, you can use the
CEEDATM callable service to convert output_seconds to another format.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2F3 3 2531 The local time was not available from the
system.

Usage Notes
Ÿ You can use the CEEGMT callable service to determine Greenwich Mean Time
(GMT).
Ÿ You can use the CEEGMTO callable service to obtain the offset from GMT to local
time.
Ÿ The character value returned by CEELOCT is designed to match that produced by
existing intrinsic functions. The numeric values returned can be used to simplify
date calculations.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEELOCT to get current \\
\\ local time \\
\\ \\
\\ In this example, a call is made to CEELOCT \\
\\ to return the current local time in Lilian \\
\\ days (the number of days since 14 October \\
\\ 1582), Lilian seconds (the number of \\
\\ seconds since ðð:ðð:ðð 14 October 1582), \\
\\ and a Gregorian string (in the form \\
\\ YYYMMDDMISS999). The Gregorian character \\
\\ string is then displayed. \\

Appendix E. Date and Time Callable Services Reference 515


CEEQCEN

\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLLOCT.
DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 LILIAN PIC S9(9) BINARY.
ð1 SECONDS COMP-2.
ð1 GREGORN PIC X(17).
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.
PARA-CBLLOCT.
CALL 'CEELOCT' USING LILIAN, SECONDS,
GREGORN, FC.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEELOCT runs successfully, display \\
\\ Gregorian character string \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY 'Local Time is ' GREGORN
ELSE
DISPLAY 'CEELOCT failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEEQCEN—Query the Century Window


CEEQCEN queries the century which is a 2-digit year value. When you want to change
the setting, use CEEQCEN to get the setting and then use CEESCEN to save and
restore the current setting.

516 COBOL Set for AIX Programming Guide


CEEQCEN

Syntax
55──CALL──"CEEQCEN"──USING──century_start──,──fc──.───────────────────5%

century_start (output)
An integer between 0 and 100 indicating the year on which the century window is
based.
For example, if the date and time callable services default is in effect, all 2-digit
years lie within the 100-year window starting 80 years prior to the system date.
CEEQCEN then returns the value 80. An 80 value indicates to the date and time
callable services that, in 1997, all 2-digit years lie within the 100-year window
starting 80 years before the system date (between 1917 and 2016, inclusive).

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEEQCEN to query the \\
\\ date and time callable services \\
\\ century window \\
\\ \\
\\ In this example, CEEQCEN is called to query \\
\\ the date at which the century window starts \\
\\ The century window is the 1ðð-year window \\
\\ within which the date and time callable \\
\\ services assume all two-digit years lie. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.

Appendix E. Date and Time Callable Services Reference 517


CEESCEN

PROGRAM-ID. CBLQCEN.

DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 STARTCW PIC S9(9) BINARY.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.

PARA-CBLQCEN.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEEQCEN to return the start of the \\
\\ century window \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

CALL 'CEEQCEN' USING STARTCW, FC.


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ CEEQCEN has no non-zero feedback codes to \\
\\ check, so just display result. \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY 'The start of the century '
'window is: ' STARTCW
ELSE
DISPLAY 'CEEQCEN failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

CEESCEN—Set the Century Window


CEESCEN sets the century to a 2-digit year value for use by other date and time call-
able services. Use it in conjunction with CEEDAYS or CEESECS when:
Ÿ You process date values containing 2-digit years (for example, in the YYMMDD
format).
Ÿ The default century interval does not meet the requirements of a particular applica-
tion.

To query the century window, use CEEQCEN.

518 COBOL Set for AIX Programming Guide


CEESCEN

Syntax
55──CALL──"CEESCEN"──USING──century_start──,──fc──.───────────────────5%

century_start
An integer between 0 and 100, setting the century window.
A value of 80, for example, places all two-digit years within the 100-year window
starting 80 years before the system date. In 1997, therefore, all two-digit years are
assumed to represent dates between 1917 and 2016, inclusive.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2E6 3 2502 The UTC/GMT was not available from the
system.
CEE2F5 3 2533 The value passed to CEESCEN was not
between 0 and 100.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEESCEN to set the \\
\\ date and time callable services \\
\\ century window \\
\\ \\
\\ In this example, CEESCEN is called to change \\
\\ the start of the century window to 3ð years \\
\\ before the system date. CEEQCEN is then \\
\\ called to query that the change made. A \\
\\ message that this has been done is then \\
\\ displayed. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Appendix E. Date and Time Callable Services Reference 519


CEESCEN

IDENTIFICATION DIVISION.
PROGRAM-ID. CBLSCEN.

DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 STARTCW PIC S9(9) BINARY.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.
PARA-CBLSCEN.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify 3ð as century start, and two-digit
\\ years will be assumed to lie in the
\\ 1ðð-year window starting 3ð years before
\\ the system date.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 3ð TO STARTCW.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEESCEN to change the start of the century
\\ window.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEESCEN' USING STARTCW, FC.
IF NOT CEEððð of FC THEN
DISPLAY 'CEESCEN failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

PARA-CBLQCEN.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEEQCEN to return the start of the century
\\ window
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEEQCEN' USING STARTCW, FC.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ CEEQCEN has no non-zero feedback codes to
\\ check, so just display result.

520 COBOL Set for AIX Programming Guide


CEESECI

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
DISPLAY 'The start of the century '
'window is: ' STARTCW
GOBACK.

CEESECI—Convert Seconds to Integers


CEESECI converts a number representing the number of seconds since 00:00:00 14
October 1582 to seven separate binary integers representing year, month, day, hour,
minute, second, and millisecond. Use CEESECI instead of CEEDATM when the output
is needed in numeric format rather than in character format.

Syntax
55──CALL──"CEESECI"──USING──input_seconds──,──output_year──,───────────5
5──output_month──,──output_day──,──output_hours──,──output_minutes─────5
5──,──output_seconds──,──output_milliseconds──,──fc──.────────────────5%

input_seconds
A 64-bit double floating-point number representing the number of seconds since
00:00:00 on 14 October 1582, not counting leap seconds.
For example, 00:00:01 on 15 October 1582 is second number 86,401 (24*60*60 +
01). The range of valid values for input_seconds is 86,400 to 265,621,679,999.999
(23:59:59.999 31 December 9999).
If input_seconds is invalid, all output parameters except the feedback code are set
to 0.

output_year (output)
A 32-bit binary integer representing the year.
The range of valid values for output_year is 1582 to 9999, inclusive.

output_month (output)
A 32-bit binary integer representing the month.
The range of valid values for output_month is 1 to 12.

output_day (output)
A 32-bit binary integer representing the day.
The range of valid values for output_day is 1 to 31.

output_hours (output)
A 32-bit binary integer representing the hour.
The range of valid values for output_hours is 0 to 23.

output_minutes (output)
A 32-bit binary integer representing the minutes.
The range of valid values for output_minutes is 0 to 59.

Appendix E. Date and Time Callable Services Reference 521


CEESECI

output_seconds (output)
A 32-bit binary integer representing the seconds.
The range of valid values for output_seconds is 0 to 59.

output_milliseconds (output)
A 32-bit binary integer representing milliseconds.
The range of valid values for output_milliseconds is 0 to 999.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2E9 3 2505 The input_seconds value in a call to
CEEDATM or CEESECI was not within the
supported range.

Usage Notes
Ÿ The inverse of CEESECI is CEEISEC, which converts separate binary integers
representing year, month, day, hour, second, and millisecond to a number of
seconds.
Ÿ If the input value is a Lilian date instead of seconds, multiply the Lilian date by
86,400 (number of seconds in a day), and pass the new value to CEESECI.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEESECI to convert seconds \\
\\ to integers \\
\\ \\
\\ In this example a call is made to CEESECI \\
\\ to convert a number representing the number \\
\\ of seconds since ðð:ðð:ðð 14 October 1582 \\

522 COBOL Set for AIX Programming Guide


CEESECI

\\ to seven binary integers representing year, \\


\\ month, day, hour, minute, second, and \\
\\ millisecond. The results are displayed in \\
\\ this example. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLSECI.

DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 INSECS COMP-2.
ð1 YEAR PIC S9(9) BINARY.
ð1 MONTH PIC S9(9) BINARY.
ð1 DAYS PIC S9(9) BINARY.
ð1 HOURS PIC S9(9) BINARY.
ð1 MINUTES PIC S9(9) BINARY.
ð1 SECONDS PIC S9(9) BINARY.
ð1 MILLSEC PIC S9(9) BINARY.
ð1 IN-DATE.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X,
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of IN-DATE.
ð1 PICSTR.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X,
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of PICSTR.
ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.
PARA-CBLSECS.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEESECS to convert timestamp of 6/2/88

Appendix E. Date and Time Callable Services Reference 523


CEESECI

\\ at 1ð:23:45 AM to Lilian representation


\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 2ð TO Vstring-length of IN-DATE.
MOVE 'ð6/ð2/88 1ð:23:45 AM'
TO Vstring-text of IN-DATE.
MOVE 2ð TO Vstring-length of PICSTR.
MOVE 'MM/DD/YY HH:MI:SS AP'
TO Vstring-text of PICSTR.
CALL 'CEESECS' USING IN-DATE, PICSTR,
INSECS, FC.
IF NOT CEEððð of FC THEN
DISPLAY 'CEESECS failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

PARA-CBLSECI.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEESECI to convert seconds to integers
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEESECI' USING INSECS, YEAR, MONTH,
DAYS, HOURS, MINUTES,
SECONDS, MILLSEC, FC.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ If CEESECI runs successfully, display results
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IF CEEððð of FC THEN
DISPLAY 'Input seconds of ' INSECS
' represents:'
DISPLAY ' Year......... ' YEAR
DISPLAY ' Month........ ' MONTH
DISPLAY ' Day.......... ' DAYS
DISPLAY ' Hour......... ' HOURS
DISPLAY ' Minute....... ' MINUTES
DISPLAY ' Second....... ' SECONDS
DISPLAY ' Millisecond.. ' MILLSEC
ELSE
DISPLAY 'CEESECI failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

GOBACK.

524 COBOL Set for AIX Programming Guide


CEESECS

CEESECS—Convert Timestamp to Seconds


CEESECS converts a string representing a timestamp into the number of Lilian
seconds (number of seconds since 00:00:00 14 October 1582). This service makes it
easier to perform time arithmetic, such as calculating the elapsed time between two
timestamps.

Syntax
55──CALL──"CEESECS"──USING──input_timestamp──,──picture_string──,──────5
5──output_seconds──,──fc──.───────────────────────────────────────────5%

input_timestamp (input)
A halfword length-prefixed character string, representing a date or timestamp in a
format matching that specified by picture_string.
The character string must contain between 5 and 80 picture characters, inclusive.
input_timestamp can contain leading or trailing blanks. Parsing begins with the first
nonblank character (unless the picture string itself contains leading blanks; in this
case, CEESECS skips exactly that many positions before parsing begins).
After a valid date is parsed, as determined by the format of the date you specify in
picture_string, all remaining characters are ignored by CEESECS. Valid dates
range between and including the dates 15 October 1582 to 31 December 9999. A
full date must be specified. Valid times range from 00:00:00.000 to 23:59:59.999.
If any part or all of the time value is omitted, zeros are substituted for the
remaining values. For example:
1992-ð5-17-19:ð2 is equivalent to 1992-ð5-17-19:ð2:ðð
1992-ð5-17 is equivalent to 1992-ð5-17-ðð:ðð:ðð

picture_string (input)
A halfword length-prefixed character string, indicating the format of the date or
timestamp value specified in input_timestamp.
Each character in the picture_string represents a character in input_timestamp.
For example, if you specify MMDDYY HH.MI.SS as the picture_string, CEESECS
reads an input_char_date of 060288 15.35.02 as 3:35:02 PM on 02 June 1988. If
delimiters such as the slash (/) appear in the picture string, leading zeros can be
omitted. For example, the following calls to CEESECS all assign the same value
to variable secs:
CALL CEESECS USING '92/ð6/ð3 15.35.ð3',
'YY/MM/DD HH.MI.SS', secs, fc.
CALL CEESECS USING '92/6/3 15.35.ð3',
'YY/MM/DD HH.MI.SS', secs, fc.
CALL CEESECS USING '92/6/3 3.35.ð3 PM',
'YY/MM/DD HH.MI.SS AP', secs, fc.
CALL CEESECS USING '92.155 3.35.ð3 pm',
'YY.DDD HH.MI.SS AP', secs, fc.

Appendix E. Date and Time Callable Services Reference 525


CEESECS

If picture_string includes a Japanese era symbol <JJJJ>, the YY position in


input_timestamp represents the year number within the Japanese era. For
example, the year 1988 equals the Japanese year 63 in the Showa era. See
Figure 112 on page 428 for a list of Japanese Eras supported.
If picture_string includes a Republic of China (ROC) Era symbol <CCCC> or
<CCCCCCCC>, the YY position in input_timestamp represents the year number within
the ROC Era. For example, the year 1988 equals the ROC year 77 in the MinKow
Era.
See Figure 113 on page 428 for a list of ROC Eras supported.
See Figure 110 on page 426 for a list of valid picture characters, and Figure 111
on page 427 for examples of valid picture strings.

output_seconds (output)
A 64-bit double floating-point number representing the number of seconds since
00:00:00 on 14 October 1582, not counting leap seconds. For example, 00:00:01
on 15 October 1582 is second 86,401 (24*60*60 + 01) in the Lilian format.
19:00:01.12 on 16 May 1988 is second 12,799,191,601.12.
The largest value represented is 23:59:59.999 on 31 December 9999, which is
second 265,621,679,999.999 in the Lilian format.
A 64-bit double floating-point value can accurately represent approximately 16 sig-
nificant decimal digits without loss of precision. Therefore, accuracy is available to
the nearest millisecond (15 decimal digits).
If input_timestamp does not contain a valid date or timestamp, output_seconds is
set to 0 and CEESECS terminates with a non-CEE000 symbolic feedback code.
Elapsed time calculations are performed easily on the output_seconds, because it
represents elapsed time. Leap year and end-of-year anomalies do not affect the
calculations.

fc (output)
A 12-byte feedback code (optional), that indicates the result of this service.
The following symbolic conditions can result from this service:

Symbolic
Feedback Message
Code Severity Number Message Text
CEE000 0 — The service completed successfully.
CEE2EB 3 2507 Insufficient data was passed to CEEDAYS
or CEESECS. The Lilian value was not cal-
culated.
CEE2EC 3 2508 The date value passed to CEEDAYS or
CEESECS was invalid.
CEE2ED 3 2509 The Japanese or Republic of China Era
passed to CEEDAYS or CEESECS was not
recognized.

526 COBOL Set for AIX Programming Guide


CEESECS

Symbolic
Feedback Message
Code Severity Number Message Text
CEE2EE 3 2510 The hours value in a call to CEEISEC or
CEESECS was not recognized.
CEE2EH 3 2513 The input date passed in a CEEISEC,
CEEDAYS, or CEESECS call was not within
the supported range.
CEE2EK 3 2516 The minutes value in a CEEISEC call was
not recognized.
CEE2EL 3 2517 The month value in a CEEISEC call was not
recognized.
CEE2EM 3 2518 An invalid picture string was specified in a
call to a date/time service.
CEE2EN 3 2519 The seconds value in a CEEISEC call was
not recognized.
CEE2EP 3 2521 The Japanese (<JJJJ>) or Chinese
(<CCCC>) year-within-Era value passed to
CEEDAYS or CEESECS was zero.
CEE2ET 3 2525 CEESECS detected non-numeric data in a
numeric field, or the timestamp string did not
match the picture string.

Usage Notes
Ÿ The inverse of CEESECS is CEEDATM, which converts output_seconds to char-
acter format.
Ÿ By default, 2-digit years lie within the 100 year range starting 80 years prior to the
system date. Thus, in 1997, all 2-digit years represent dates between 1917 and
2016, inclusive. You can change this range by using the callable service
CEESCEN.

Example

Appendix E. Date and Time Callable Services Reference 527


CEESECS

CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ \\
\\ Function: Call CEESECS to convert \\
\\ timestamp to number of seconds \\
\\ \\
\\ In this example, calls are made to CEESECS \\
\\ to convert two timestamps to the number of \\
\\ seconds since ðð:ðð:ðð 14 October 1582. \\
\\ The Lilian seconds for the earlier \\
\\ timestamp are then subtracted from the \\
\\ Lilian seconds for the later timestamp \\
\\ to determine the number of between the \\
\\ two. This result is displayed. \\
\\ \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLSECS.

DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 SECOND1 COMP-2.
ð1 SECOND2 COMP-2.
ð1 TIMESTP.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X,
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of TIMESTP.
ð1 TIMESTP2.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X,
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of TIMESTP2.
ð1 PICSTR.
ð2 Vstring-length PIC S9(4) BINARY.
ð2 Vstring-text.
ð3 Vstring-char PIC X,
OCCURS ð TO 256 TIMES
DEPENDING ON Vstring-length
of PICSTR.

528 COBOL Set for AIX Programming Guide


CEESECS

ð1 FC.
ð2 Condition-Token-Value.
COPY CEEIGZCT.
ð3 Case-1-Condition-ID.
ð4 Severity PIC S9(4) COMP.
ð4 Msg-No PIC S9(4) COMP.
ð3 Case-2-Condition-ID
REDEFINES Case-1-Condition-ID.
ð4 Class-Code PIC S9(4) COMP.
ð4 Cause-Code PIC S9(4) COMP.
ð3 Case-Sev-Ctl PIC X.
ð3 Facility-ID PIC XXX.
ð2 I-S-Info PIC S9(9) COMP.
PROCEDURE DIVISION.

PARA-SECS1.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify first timestamp and a picture string
\\ describing the format of the timestamp
\\ as input to CEESECS
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 25 TO Vstring-length of TIMESTP.
MOVE '1969-ð5-ð7 12:ð1:ðð.ððð'
TO Vstring-text of TIMESTP.
MOVE 25 TO Vstring-length of PICSTR.
MOVE 'YYYY-MM-DD HH:MI:SS.999'
TO Vstring-text of PICSTR.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEESECS to convert the first timestamp
\\ to Lilian seconds
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEESECS' USING TIMESTP, PICSTR,
SECOND1, FC.
IF NOT CEEððð of FC THEN
DISPLAY 'CEESECS failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

PARA-SECS2.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Specify second timestamp and a picture string
\\ describing the format of the timestamp as
\\ input to CEESECS.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
MOVE 25 TO Vstring-length of TIMESTP2.
MOVE '2ððð-ð1-ð1 ðð:ðð:ð1.ððð'
TO Vstring-text of TIMESTP2.
MOVE 25 TO Vstring-length of PICSTR.

Appendix E. Date and Time Callable Services Reference 529


IGZEDT4

MOVE 'YYYY-MM-DD HH:MI:SS.999'


TO Vstring-text of PICSTR.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call CEESECS to convert the second timestamp
\\ to Lilian seconds
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'CEESECS' USING TIMESTP2, PICSTR,
SECOND2, FC.
IF NOT CEEððð of FC THEN
DISPLAY 'CEESECS failed with msg '
Msg-No of FC UPON CONSOLE
STOP RUN
END-IF.

PARA-SECS2.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Subtract SECOND2 from SECOND1 to determine the
\\ number of seconds between the two timestamps
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
SUBTRACT SECOND1 FROM SECOND2.
DISPLAY 'The number of seconds between '
Vstring-text OF TIMESTP ' and '
Vstring-text OF TIMESTP2 ' is: ' SECOND2.

GOBACK.

CEEUTC—Get Coordinated Universal Time


CEEUTC is identical to CEEGMT. See “CEEGMT—Get Current Greenwich Mean
Time” on page 505.

IGZEDT4—Get Current Date


Note: In addition to the previous date and time callable services, COBOL Set for AIX
supports the VS COBOL II callable service IGZEDT4.

IGZEDT4 returns the current date with a 4-digit year in the form YYYYMMDD.

Syntax
55──CALL──"IGZEDT4"──USING──output_char_date──.───────────────────────5%

output_char_date (output)
An 8-byte fixed-length character string in the form YYYYMMDD representing
current year, month, and day.

530 COBOL Set for AIX Programming Guide


IGZEDT4

Usage Notes
Ÿ IGZEDT4 is not supported under CICS.

Example
CBL LIB,APOST
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Function: IGZEDT4 - get current date in the \\
\\ format YYYYMMDD. \\
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
IDENTIFICATION DIVISION.
PROGRAM-ID. CBLEDT4.

DATA DIVISION.
WORKING-STORAGE SECTION.
ð1 CHRDATE PIC S9(8) USAGE DISPLAY.

PROCEDURE DIVISION.
PARA-CBLEDT4.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ Call IGZEDT4.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
CALL 'IGZEDT4' USING BY REFERENCE CHRDATE.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
\\ IGZEDT4 has no non-zero return code to
\\ check, so just display result.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
DISPLAY 'The current date is: '
CHRDATE

GOBACK.

Appendix E. Date and Time Callable Services Reference 531


IWZ006S ŸIWZ006S

Appendix F. Run-Time Messages


Messages for COBOL Set for AIX contain a message prefix, message number, severity
code, and descriptive text. The message prefix is always IWZ, followed by the
| message number. The severity code will be either I (Information), W (Warning), S
| (Severe), or C (Critical). The message text provides a brief explanation of the condi-
tion.

In the following example message:


IWZ2519S The seconds value in a CEEISEC call was not recognized.
Ÿ The message prefix is IWZ.
Ÿ The message number is 2519.
Ÿ The severity code is S.
Ÿ The message text is “The seconds value in a CEEISEC call was not recognized.”

The date and time callable services messages also contain a symbolic feedback code,
which represents the first 8 bytes of a 12-byte condition token. You can think of the
symbolic feedback code as the nickname for a condition. Note that the callable ser-
vices messages contain a 4-digit message number.

IWZ006S The reference to table table-name by verb number verb-number on line line-
number addressed an area outside the region of the table.

Explanation: When the SSRANGE option is in effect, this message is issued to indicate that a
fixed-length table has been subscripted in a way that exceeds the defined size of the table, or, for
variable-length tables, the maximum size of the table.
The range check was performed on the composite of the subscripts and resulted in an address
outside the region of the table. For variable-length tables, the address is outside the region of the
table defined when all OCCURS DEPENDING ON objects are at their maximum values; the ODO
object's current value is not considered. The check was not performed on individual subscripts.
Programmer Response: Ensure that the value of literal subscripts and/or the value of variable
subscripts as evaluated at run-time do not exceed the subscripted dimensions for subscripted data
in the failing statement.
System Action: The application was terminated.

532  Copyright IBM Corp. 1996, 1998


IWZ007S ŸIWZ026W

IWZ007S The reference to variable length group group-name by verb number verb-
number on line line-number addressed an area outside the maximum defined
length of the group.

Explanation: When the SSRANGE option is in effect, this message is issued to indicate that a
variable-length group generated by OCCURS DEPENDING ON has a length that is less than zero,
or is greater than the limits defined in the OCCURS DEPENDING ON clauses.
The range check was performed on the composite length of the group, and not on the individual
OCCURS DEPENDING ON objects.
Programmer Response: Ensure that OCCURS DEPENDING ON objects as evaluated at run-
time do not exceed the maximum number of occurrences of the dimension for tables within the
referenced group item.
System Action: The application was terminated.

IWZ012I Invalid run unit termination occurred while sort or merge is running.

Explanation: A sort or merge initiated by a COBOL program was in progress and one of the
following was attempted:
1. A STOP RUN was issued.
2. A GOBACK or an EXIT PROGRAM was issued within the input procedure or the output proce-
dure of the COBOL program that initiated the sort or merge. Note that the GOBACK and
EXIT PROGRAM statements are allowed in a program called by an input procedure or an
output procedure.
Programmer Response: Change the application so that it does not use one of the above
methods to end the sort or merge.
System Action: The application was terminated.

IWZ013S Sort or merge requested while sort or merge is running in a different thread.

Explanation: Running sort or merge in two or more threads at the same time is not supported.
Programmer Response: Always run sort or merge in the same thread. Alternatively, include
code before each call to the sort or merge that determines if sort or merge is running in another
thread. If sort or merge is running in another thread, then wait for that thread to finish. If it isn't,
then set a flag to indicate sort or merge is running and call sort or merge.
System Action: The thread is terminated.

IWZ026W The SORT-RETURN special register was never referenced, but the current
content indicated the sort or merge operation in program program-name on
line number line-number was unsuccessful. The sort or merge return code
was return code

Explanation: The COBOL source does not contain any references to the sort-return register.
The compiler generates a test after each sort or merge verb. A nonzero return code has been
passed back to the program by Sort/Merge.
Programmer Response: Determine why the Sort/Merge was unsuccessful and fix the problem.

Appendix F. Run-Time Messages 533


IWZ029S ŸIWZ037I

System Action: No system action was taken.

IWZ029S Argument-1 for function function-name in program program-name at line line-


number was less than zero.

Explanation: An illegal value for argument-1 was used.


Programmer Response: Ensure that argument-1 is greater than or equal to zero.
System Action: The application was terminated.

IWZ030S Argument-2 for function function-name in program program at line line-number


was not a positive integer.

Explanation: An illegal value for argument-1 was used.


Programmer Response: Ensure that argument-2 is a positive integer.
System Action: The application was terminated.

IWZ036W Truncation of high order digit positions occurred in program program-name


on line number line-number .

Explanation: The generated code has truncated an intermediate result (that is, temporary
storage used during an arithmetic calculation) to 30 digits; some of the truncated digits were not 0.
Programmer Response: See Appendix C, “Intermediate Results and Arithmetic Precision” on
page 471 for a description of intermediate results.
System Action: No system action was taken.

IWZ037I The flow of control in program program-name proceeded beyond the last line
of the program. Control returned to the caller of the program program-name

Explanation: The program did not have a terminator (STOP, GOBACK, or EXIT), and control fell
through the last instruction.
Programmer Response: Check the logic of the program. Sometimes this error occurs because
of one of the following logic errors:
Ÿ The last paragraph in the program was only supposed to receive control as the result of a
PERFORM statement, but due to a logic error it was branched to by a GO TO statement.
Ÿ The last paragraph in the program was executed as the result of a “fall-through” path, and
there was no statement at the end of the paragraph to end the program.
System Action: The application was terminated.

534 COBOL Set for AIX Programming Guide


IWZ038S ŸIWZ040S

IWZ038S A reference modification length value of reference-modification-value on line


line-number which was not equal to 1 was found in a reference to data item
data-item

Explanation: The length value in a reference modification specification was not equal to 1. The
length value must be equal to 1.
Programmer Response: Check the indicated line number in the program to ensure that any ref-
erence modified length values are (or will resolve to) 1.
System Action: The application was terminated.

IWZ039S An invalid overpunched sign was detected.

Explanation: The value in the sign position was not valid.


Given X'sd', where s is the sign representation and d represents the digit, the valid sign repres-
entations for external decimal (USAGE DISPLAY without the SIGN IS SEPARATE clause) are:
Positive: 0, 1, 2, 3, 8, 9, A, and B.
Negative: 4, 5, 6, 7, C, D, E, and F.
Signs generated internally are 3 for positive and unsigned, and 7 for negative.
Given X'ds', where d represents the digit and s is the sign representation, the valid sign repres-
entations for internal decimal (USAGE PACKED-DECIMAL) COBOL data are:
Positive: A, C, E, and F.
Negative: B and D.
Signs generated internally are C for positive and unsigned, and D for negative.
Programmer Response: This error might have occurred because of a REDEFINES clause
involving the sign position or a group move involving the sign position, or the position was never
initialized. Check for the above cases.
System Action: The application was terminated.

IWZ040S An invalid separate sign was detected.

Explanation: An operation was attempted on data defined with a separate sign. The value in the
sign position was not a plus (+) or a minus (-).
Programmer Response: This error might have occurred because of a REDEFINES clause
involving the sign position or a group move involving the sign position, or the position was never
initialized. Check for the above cases.
System Action: The application was terminated.

Appendix F. Run-Time Messages 535


IWZ045S ŸIWZ049W

IWZ045S Unable to invoke method method-name on line number line number in


program program-name.

Explanation: The specific method is not supported for the class of the current object reference.
Programmer Response: Check the indicated line number in the program to ensure that the
class of the current object reference supports the method being invoked.
System Action: The application was terminated.

IWZ047S Unable to invoke method method-name on line number line number in class
class-name.

Explanation: The specific method is not supported for the class of the current object reference.
Programmer Response: Check the indicated line number in the class to ensure that the class
of the current object reference supports the method being invoked.
System Action: The application was terminated.

IWZ048W A negative base was raised to a fractional power in an exponentiation


expression. The absolute value of the base was used.

Explanation: A negative number raised to a fractional power occurred in a library routine.


The value of a negative number raised to a fractional power is undefined in COBOL. If a SIZE
ERROR clause had appeared on the statement in question, the SIZE ERROR imperative would
have been used. However, no SIZE ERROR clause was present, so the absolute value of the
base was used in the exponentiation.
Programmer Response: Ensure that the program variables in the failing statement have been
set correctly.
System Action: No system action was taken.

IWZ049W A zero base was raised to a zero power in an exponentiation expression.


The result was set to one.

Explanation: The value of zero raised to the power zero occurred in a library routine.
The value of zero raised to the power zero is undefined in COBOL. If a SIZE ERROR clause had
appeared on the statement in question, the SIZE ERROR imperative would have been used.
However, no SIZE ERROR clause was present, so the value returned was one.
Programmer Response: Ensure that the program variables in the failing statement have been
set correctly.
System Action: No system action was taken.

536 COBOL Set for AIX Programming Guide


IWZ050S ŸIWZ058S

IWZ050S A zero base was raised to a negative power in an exponentiation


expression.

Explanation: The value of zero raised to a negative power occurred in a library routine.
The value of zero raised to a negative number is not defined. If a SIZE ERROR clause had
appeared on the statement in question, the SIZE ERROR imperative would have been used.
However, no SIZE ERROR clause was present.
Programmer Response: Ensure that the program variables in the failing statement have been
set correctly.
System Action: The application was terminated.

IWZ053S An overflow occurred on conversion to floating point.

Explanation: A number was generated in the program that is too large to be represented in
floating point.
Programmer Response: You need to modify the program appropriately to avoid an overflow.
System Action: The application was terminated.

IWZ054S A floating point exception occurred.

Explanation: A floating point calculation has produced an illegal result. Floating point calcu-
lations are done using IEEE floating point arithmetic, which can produce results called NaN (Not a
Number). For example, the result of 0 divided by 0 is NaN.
Programmer Response: Modify the program to test the arguments to this operation so that NaN
is not produced.
System Action: The application was terminated.

IWZ055W An underflow occurred on conversion to floating point. The result was set
to zero.

Explanation: On conversion to floating point, the negative exponent exceeded the limit of the
hardware. The floating point value was set to zero.
Programmer Response: No action is necessary, although you may want to modify the program
to avoid an underflow.
System Action: No system action was taken.

IWZ058S Exponent overflow occurred.

Explanation: Floating point exponent overflow occurred in a library routine.


Programmer Response: Ensure that the program variables in the failing statement have been
set correctly.
System Action: The application was terminated.

Appendix F. Run-Time Messages 537


IWZ059W ŸIWZ063S

IWZ059W An exponent with more than nine digits was truncated.

Explanation: Exponents in fixed point exponentiations may not contain more than nine digits.
The exponent was truncated back to nine digits; some of the truncated digits were not 0.
Programmer Response: No action is necessary, although you may want to adjust the exponent
in the failing statement.
System Action: No system action was taken.

IWZ060W Truncation of high order digit positions occurred.

Explanation: Code in a library routine has truncated an intermediate result (that is, temporary
storage used during an arithmetic calculation) back to 30 digits; some of the truncated digits were
not 0.
Programmer Response: See Appendix C, “Intermediate Results and Arithmetic Precision” on
page 471 for a description of intermediate results.
System Action: No system action was taken.

IWZ061S Division by zero occurred.

Explanation: Division by zero occurred in a library routine. Division by zero is not defined. If a
SIZE ERROR clause had appeared on the statement in question, the SIZE ERROR imperative
would have been used. However, no SIZE ERROR clause was present.
Programmer Response: Ensure that the program variables in the failing statement have been
set correctly.
System Action: The application was terminated.

IWZ063S An invalid sign was detected in a numeric edited sending field in program-
name on line number line-number.

Explanation: An attempt has been made to move a signed numeric edited field to a signed
numeric or numeric edited receiving field in a MOVE statement. However, the sign position in the
sending field contained a character that was not a valid sign character for the corresponding
PICTURE.
Programmer Response: Ensure that the program variables in the failing statement have been
set correctly.
System Action: The application was terminated.

538 COBOL Set for AIX Programming Guide


IWZ064S ŸIWZ071S

IWZ064S A recursive call to active program program-name in compilation unit


compilation-unit was attempted.

Explanation: COBOL does not allow reinvocation of an internal program which has begun exe-
cution, but has not yet terminated. For example, if internal programs A and B are siblings of a
containing program, and A calls B and B calls A, this message will be issued.
Programmer Response: Examine your program to eliminate calls to active internal programs.
System Action: The application was terminated.

IWZ065I A CANCEL of active program program-name in compilation unit compilation-


unit was attempted.

Explanation: An attempt was made to cancel an active internal program. For example, if internal
programs A and B are siblings in a containing program and A calls B and B cancels A, this
message will be issued.
Programmer Response: Examine your program to eliminate cancellation of active internal pro-
grams.
System Action: The application was terminated.

IWZ066S The length of external data record data-record in program program-name did
not match the existing length of the record.

Explanation: While processing External data records during program initialization, it was deter-
mined that an External data record was previously defined in another program in the run-unit, and
the length of the record as specified in the current program was not the same as the previously
defined length.
Programmer Response: Examine the current file and ensure the External data records are
specified correctly.
System Action: The application was terminated.

IWZ071S ALL subscripted table reference to table table-name by verb number verb-
number on line line-number had an ALL subscript specified for an OCCURS
DEPENDING ON dimension, and the object was less than or equal to 0.

Explanation: When the SSRANGE option is in effect, this message is issued to indicate that
there are 0 occurrences of dimension subscripted by ALL.
The check is performed against the current value of the OCCURS DEPENDING ON OBJECT.
Programmer Response: Ensure that ODO object(s) of ALL-subscripted dimensions of any sub-
scripted items in the indicated statement are positive.
System Action: The application was terminated.

Appendix F. Run-Time Messages 539


IWZ072S ŸIWZ075S

IWZ072S A reference modification start position value of reference-modification-value


on line line-number referenced an area outside the region of data item data-
item.

Explanation: The value of the starting position in a reference modification specification was less
than 1, or was greater than the current length of the data item that was being reference modified.
The starting position value must be a positive integer less than or equal to the number of charac-
ters in the reference modified data item.
Programmer Response: Check the value of the starting position in the reference modification
specification.
System Action: The application was terminated.

IWZ073S A non-positive reference modification length value of reference-modification-


value on line line-number was found in a reference to data item data-item.

Explanation: The length value in a reference modification specification was less than or equal to
0. The length value must be a positive integer.
Programmer Response: Check the indicated line number in the program to ensure that any ref-
erence modified length values are (or will resolve to) positive integers.
System Action: The application was terminated.

IWZ074S A reference modification start position value of reference-modification-value


and length value of length on line line-number caused reference to be made
beyond the rightmost character of data item data-item.

Explanation: The starting position and length value in a reference modification specification
combine to address an area beyond the end of the reference modified data item. The sum of the
starting position and length value minus one must be less than or equal to the number of charac-
ters in the reference modified data item.
Programmer Response: Check the indicated line number in the program to ensure that any ref-
erence modified start and length values are set such that a reference is not made beyond the
rightmost character of the data item.
System Action: The application was terminated.

IWZ075S Inconsistencies were found in EXTERNAL file file-name in program program-


name. The following file attributes did not match those of the established
external file: attribute-1 attribute-2 attribute-3 attribute-4 attribute-5 attribute-6
attribute-7

Explanation: One or more attributes of an external file did not match between two programs that
defined it.
Programmer Response: Correct the external file. For a summary of file attributes which must
match between definitions of the same external file, see the COBOL Language Reference.
System Action: The application was terminated.

540 COBOL Set for AIX Programming Guide


IWZ076W ŸIWZ078S

IWZ076W The number of characters in the INSPECT REPLACING CHARACTERS BY


data-name was not equal to one. The first character was used.

Explanation: A data item which appears in a CHARACTERS phrase within a REPLACING


phrase in an INSPECT statement must be defined as being one character in length. Because of a
reference modification specification for this data item, the resultant length value was not equal to
one. The length value is assumed to be one.
Programmer Response: You may correct the reference modification specifications in the failing
INSPECT statement to ensure that the reference modification length is (or will resolve to) 1; pro-
grammer action is not required.
System Action: No system action was taken.

IWZ077W The lengths of the INSPECT data items were not equal. The shorter length
was used.

Explanation: The two data items which appear in a REPLACING or CONVERTING phrase in an
INSPECT statement must have equal lengths, except when the second such item is a figurative
constant. Because of the reference modification for one or both of these data items, the resultant
length values were not equal. The shorter length value is applied to both items, and execution
proceeds.
Programmer Response: You may adjust the operands of unequal length in the failing INSPECT
statement; programmer action is not required.
System Action: No system action was taken.

IWZ078S ALL subscripted table reference to table table-name by verb number verb-
number on line line-number will exceed the upper bound of the table.

Explanation: When the SSRANGE option is in effect, this message is issued to indicate that a
multidimensional table with ALL specified as one or more of the subscripts will result in a reference
beyond the upper limit of the table.
The range check was performed on the composite of the subscripts and the maximum occur-
rences for the ALL subscripted dimensions. For variable-length tables the address is outside the
region of the table defined when all OCCURS DEPENDING ON objects are at their maximum
values; the ODO object's current value is not considered. The check was not performed on indi-
vidual subscripts.
Programmer Response: Ensure that OCCURS DEPENDING ON objects as evaluated at run-
time do not exceed the maximum number of occurrences of the dimension for table items refer-
enced in the failing statement.
System Action: The application was terminated.

Appendix F. Run-Time Messages 541


IWZ096C ŸIWZ100S

IWZ096C Dynamic call of program program-name failed. Message variants include:


Ÿ A load of module module-name failed with an error code of error-code.
Ÿ A load of module module-name failed with a return code of return-code.
Ÿ Dynamic call of program program-name failed. Insufficient resources.
Ÿ Dynamic call of program program-name failed. COBPATH not found in
environment.
Ÿ Dynamic call of program program-name failed. Entry entry-name not
found.
Ÿ Dynamic call failed. The name of the target program does not contain
any valid characters.
Ÿ Dynamic call of program program-name failed. The load module load-
module could not be found in the directories identified in the COBPATH
environment variable.

Explanation: A dynamic call failed due to one of the reasons listed in the message variants
above. In the above, the value of error-code depends on the execution platform as follows:
AIX: The errno set by load.
OS/2: The return code from the DosLoadModule service.
Windows: The last-error code value set by LoadLibrary.
Programmer Response: Check that you have COBPATH defined. Check that the module
exists: AIX, OS/2, and Windows have graphical interfaces for showing directories and files. You
can also use the ls command on AIX or the dir command on OS/2 and Windows. Check that the
name of the module to be loaded matches the name of the entry called. Check that the module to
be loaded is built correctly using the appropriate cob2 options, for example, to build a DLL on
Windows, the -dll option must be used.
System Action: The application was terminated.

IWZ097S Argument-1 for function function-name contained no digits.

Explanation: Argument-1 for the indicated function must contain at least 1 digit.
Programmer Response: Adjust the number of digits in Argument-1 in the failing statement.
System Action: The application was terminated.

IWZ100S Argument-1 for function function was less than or equal to -1.

Explanation: An illegal value was used for Argument-1.


Programmer Response: Ensure that argument-1 is greater than -1.
System Action: The application was terminated.

542 COBOL Set for AIX Programming Guide


IWZ151S ŸIWZ157S

IWZ151S Argument-1 for function function-name contained more than 18 digits.

Explanation: The total number of digits in argument-1 of the indicated function exceeded 18
digits.
Programmer Response: Adjust the number of digits in argument-1 in the failing statement.
System Action: The application was terminated.

IWZ152S Invalid character character was found in column column-number in


argument-1 for function function-name .

Explanation: A non-digit character other than a decimal point, comma, space or sign (+,-,CR,DB)
was found in argument-1 for NUMVAL/NUMVAL-C function.
Programmer Response: Correct argument-1 for NUMVAL or NUMVAL-C in the indicated state-
ment.
System Action: The application was terminated.

IWZ155S Invalid character character was found in column column-number in


argument-2 for function function-name .

Explanation: Illegal character was found in argument-2 for NUMVAL-C function.


Programmer Response: Check that the function argument does follow the syntax rules.
System Action: The application was terminated.

IWZ156S Argument-1 for function function-name was less than zero or greater than 28.

Explanation: Input argument to function FACTORIAL is greater than 28 or less than 0.


Programmer Response: Check that the function argument is only one byte long.
System Action: The application was terminated.

IWZ157S The length of Argument-1 for function function-name was not equal to 1.

Explanation: The length of input argument to ORD function is not 1.


Programmer Response: Check that the function argument is only one byte long.
System Action: The application was terminated.

Appendix F. Run-Time Messages 543


IWZ159S ŸIWZ163S

IWZ159S Argument-1 for function function-name was less than 1 or greater than
3067671.

Explanation: The input argument to DATE-OF-INTEGER or DAY-OF-INTEGER function is less


than 1 or greater than 3067671.
Programmer Response: Check that the function argument is in the valid range.
System Action: The application was terminated.

IWZ160S Argument-1 for function function-name was less than 16010101 or greater
than 99991231.

Explanation: The input argument to function INTEGER-OF-DATE is less than 16010101 or


greater than 99991231.
Programmer Response: Check that the function argument is in the valid range.
System Action: The application was terminated.

IWZ161S Argument-1 for function function-name was less than 1601001 or greater
than 9999365.

Explanation: The input argument to function INTEGER-OF-DAY is less than 1601001 or greater
than 9999365.
Programmer Response: Check that the function argument is in the valid range.
System Action: The application was terminated.

IWZ162S Argument-1 for function function-name was less than 1 or greater than the
number of positions in the program collating sequence.

Explanation: The input argument to function CHAR is less than 1 or greater than the highest
ordinal position in the program collating sequence.
Programmer Response: Check that the function argument is in the valid range.
System Action: The application was terminated.

IWZ163S Argument-1 for function function-name was less than zero.

Explanation: The input argument to function RANDOM is less than 0.


Programmer Response: Correct the argument for function RANDOM in the failing statement.
System Action: The application was terminated.

544 COBOL Set for AIX Programming Guide


IWZ165S ŸIWZ168W

IWZ165S A reference modification start position value of start-position-value on line


line number referenced an area outside the region of the function result of
function-result.

Explanation: The value of the starting position in a reference modification specification was less
than 1, or was greater than the current length of the function result that was being reference modi-
fied. The starting position value must be a positive integer less than or equal to the number of
characters in the reference modified function result.
Programmer Response: Check the value of the starting position in the reference modification
specification and the length of the actual function result.
System Action: The application was terminated.

IWZ166S A non-positive reference modification length value of length on line line-


number was found in a reference to the function result of function-result.

Explanation: The length value in a reference modification specification for a function result was
less than or equal to 0. The length value must be a positive integer.
Programmer Response: Check the length value and make appropriate correction.
System Action: The application was terminated.

IWZ167S A reference modification start position value of start-position and length


value of length on line line-number caused reference to be made beyond the
rightmost character of the function result of function-result.

Explanation: The starting position and length value in a reference modification specification
combine to address an area beyond the end of the reference modified function result. The sum of
the starting position and length value minus one must be less than or equal to the number of
characters in the reference modified function result.
Programmer Response: Check the length of the reference modification specification against the
actual length of the function result and make appropriate corrections.
System Action: The application was terminated.

IWZ168W SYSPUNCH/SYSPCH will default to the system logical output device. The
corresponding environment variable has not been set.

Explanation: COBOL environment names (such as SYSPUNCH/SYSPCH) are used as the envi-
ronment variable names corresponding to the mnemonic names used on ACCEPT and DISPLAY
statements. Set them equal to files, not existing directory names. To set environment variables:
Ÿ On OS/2 or Windows, use the SET command.
Ÿ On AIX, use the EXPORT command.
You can set environment variables either temporarily or persistently. For more information, see
“Setting Environment Variables” on page 128.
Programmer Response: If you do not want SYSPUNCH/SYSPCH to default to the screen, set
the corresponding environment variable.
System Action: No system action was taken.

Appendix F. Run-Time Messages 545


IWZ170S ŸIWZ174I

IWZ170S Illegal data type for DISPLAY operand.

Explanation: An invalid data type was specified as the target of the DISPLAY statement.
Programmer Response: Specify a valid data type. The following data types are not valid:
Ÿ Data items defined with USAGE IS PROCEDURE-POINTER
Ÿ Data items defined with USAGE IS OBJECT REFERENCE
Ÿ Data items or index names defined with USAGE IS INDEX
System Action: The application was terminated.

IWZ171I string-name is not a valid run-time option.

Explanation: string-name is not a valid option.


Programmer Response: See Chapter 11, “Run-Time Options” on page 193 for valid run-time
options.
System Action: string-name is ignored.

IWZ172I The string string-name is not a valid suboption of the run-time option option-
name.

Explanation: string-name was not in the set of recognized values.


Programmer Response: Remove the invalid suboption string from the run-time option option-
name. See Chapter 11, “Run-Time Options” on page 193 for valid suboptions for run-time option
option-name.
System Action: The invalid suboption is ignored.

IWZ173I The suboption string string-name of the run-time option option-name must be
number of characters long. The default will be used.

Explanation: The number of characters for the suboption string string-name of run-time option
option-name is invalid.
Programmer Response: If you do not want to accept the default, specify a valid character
length. See Chapter 11, “Run-Time Options” on page 193
System Action: The default value will be used.

IWZ174I The suboption string string-name of the run-time option option-name contains
one or more invalid characters. The default will be used.

Explanation: At least one invalid character was detected in the specified suboption.
Programmer Response: If you do not want to accept the default, specify valid characters.
System Action: The default value will be used.

546 COBOL Set for AIX Programming Guide


IWZ175S ŸIWZ180S

IWZ175S There is no support for routine routine-name on this system.

Explanation: routine-name is not supported.


Programmer Response:
System Action: The application was terminated.

IWZ176S Argument-1 for function function-name was greater than decimal-value.

Explanation: An illegal value for argument-1 was used.


Programmer Response: Ensure argument-1 is less than or equal to decimal-value.
System Action: The application was terminated.

IWZ177S Argument-2 for function function-name was equal to decimal-value.

Explanation: An illegal value for argument-2 was used.


Programmer Response: Ensure argument-1 is not equal to decimal-value.
System Action: The application was terminated.

IWZ178S Argument-1 for function function-name was less than or equal to decimal-
value.

Explanation: An illegal value for argument-1 was used.


Programmer Response: Ensure argument-1 is greater than decimal-value.
System Action: The application was terminated.

IWZ179S Argument-1 for function function-name was less than decimal-value.

Explanation: An illegal value for argument-1 was used.


Programmer Response: Ensure argument-1 is equal to or greater than decimal-value.
System Action: The application was terminated.

IWZ180S Argument-1 for function function-name was not an integer.

Explanation: An illegal value for argument-1 was used.


Programmer Response: Ensure argument-1 is an integer.
System Action: The application was terminated.

Appendix F. Run-Time Messages 547


IWZ181I ŸIWZ200S

IWZ181I An invalid character was found in the numeric string string of the run-time
option option-name. The default will be used.

Explanation: string did not contain all decimal numeric characters.


Programmer Response: If you do not want the default value, correct the run-time option's string
to contain all numeric characters.
System Action: The default will be used.

IWZ182I The number number of the run-time option option-name exceeded the range
of min-range to max-range. The default will be used.

Explanation: number exceeded the range of min-range to max-range.


Programmer Response: Correct the run-time option's string to be within the valid range. See
Chapter 11, “Run-Time Options” on page 193 for valid ranges.
System Action: The default will be used.

IWZ183S The function name in _iwzCOBOLInit did a return.

Explanation: The run unit termination exit routine returned to the invoker of the routine (the func-
tion specified in function_code).
Programmer Response: Rewrite the function so that the run unit termination exit routine does a
longjump or exit() instead of return to the function.
System Action: The application was terminated.

IWZ200S Message variants include:


Ÿ Error detected during I/O operation for file file-name. File status is: file-
status.
Ÿ STOP or ACCEPT failed with an I/O error, error-code. The run unit is
terminated.

Explanation: See messages below.

IWZ200S Error detected during I/O operation for file file-name. File status is: file-status.

Explanation: An error was detected during a file I/O operation. No file status was specified for
the file and no applicable error declarative is in effect for the file.
Programmer Response: Correct the condition described in this message. You can specify the
FILE STATUS clause for the file if you want to detect the error and take appropriate actions within
your source program.
System Action: The application was terminated.

548 COBOL Set for AIX Programming Guide


IWZ200S ŸIWZ203W

IWZ200S STOP or ACCEPT failed with an I/O error, error-code. The run unit is termi-
nated.

Explanation: A STOP or ACCEPT statement failed.


Programmer Response: Check that the STOP or ACCEPT refers to a legitimate file or terminal
device.
System Action: The application was terminated.

IWZ201C Message variants include:

Access Intent List Error. Address Error.


Concurrent Opens Exceeds Maximum. Command Check.
Cursor Not Selecting a Record Position. Duplicate File Name.
Data Stream Syntax Error. End of File Condition.
Duplicate Key Different Index. Existing Condition.
Duplicate Key Same Index. File Handle Not Found.
Duplicate Record Number. Field Length Error.
File Temporarily Not Available. File Not Found.
File system cannot be found. File Damaged.
File Space Not Available. File is Full.
File Closed with Damage. File In Use.
Invalid Key Definition. Function Not Supported.
Invalid Base File Name. Invalid Access Method.
Key Update Not Allowed by Different Index. Invalid Data Record.
Key Update Not Allowed by Same Index. Invalid Key Length.
No Update Intent on Record. Invalid File Name.
Not Authorized to Use Access Method. Invalid Request.
Not Authorized to Directory. Invalid Flag.
Not Authorized to Function. Object Not Supported.
Not authorized to File. Record Not Available.
Parameter Value Not Supported. Record Not Found.
Parameter Not Supported. Record Inactive.
Record Number Out of Bounds. Record Damaged.
Record Length Mismatch. Record In Use.
Resource Limits Reached in Target System. Update Cursor Error.
Resource Limits Reached in Source System.

Explanation: An error was detected during a file I/O operation for a VSAM file. No file status
was specified for the file and no applicable error declarative is in effect for the file.
Programmer Response: Correct the condition described in this message. For details, see the
SMARTdata Utilities VSAM manual for your platform:
Ÿ For OS/2: VSAM in a Distributed Environment
Ÿ For Windows: VSAM API Reference
Ÿ For AIX: VSAM in a Distributed Environment
System Action: The application was terminated.

IWZ203W The code page in effect is not a DBCS code page.

Explanation: References to DBCS data was made with a non-DBCS code page in effect.
Programmer Response: For DBCS data, specify a valid DBCS code page. Valid DBCS code
pages are:

Appendix F. Run-Time Messages 549


IWZ204W ŸIWZ230x

OS/2 Windows (NT and 95) AIX


Japan IBM-932, IBM-942, IBM-943 IBM-932
IBM-943
Korea IBM-942 IBM-1363
China (Simplified - IBM-1381, IBM-1861 IBM-1386
Mainland)
China (Traditional - IBM-950 IBM-950
Taiwan)

Note: The code pages listed above might not be supported for a specific version or release of
that platform. For additional information, see “Locales and Code Sets Supported on AIX” on
page 408.
System Action: No system action was taken.

IWZ204W An error occurred during conversion from ASCII DBCS to EBCDIC DBCS.

Explanation: A Kanji or DBCS class test failed due to an error detected during the ASCII char-
acter string EBCDIC string conversion.
Programmer Response: Verify that the locale in effect is consistent with the ASCII character
string being tested. No action is likely to be required if the locale setting is correct. The class test
is likely to indicate the string to be non-Kanji or non-DBCS correctly.
System Action: No system action was taken.

IWZ230x Message variants include:


Ÿ The conversion table for the current codeset, ASCII codeset-id, to the
EBCDIC codeset, EBCDIC codeset-id, is not available. The default ASCII
to EBCDIC conversion table will be used.
Ÿ The EBCDIC codepage specified, EBCDIC codepage, is not consistent
with the locale locale, but will be used as requested.
Ÿ The EBCDIC codepage specified, EBCDIC codepage, is not supported.
The default EBCDIC codepage, EBCDIC codepage, will be used.
Ÿ The EBCDIC conversion table cannot be opened.
Ÿ The EBCDIC conversion table cannot be built.

Explanation: See separate messages listed below.

550 COBOL Set for AIX Programming Guide


IWZ230W ŸIWZ230S

IWZ230W The conversion table for the current codeset, ASCII codeset-id, to the
EBCDIC codeset, EBCDIC codeset-id, is not available. The default ASCII to
EBCDIC conversion table will be used.

Explanation: The application has a module which was compiled with the CHAR(EBCDIC) com-
piler option. At run-time a translation table will be built to handle the conversion from the current
ASCII code page to an EBCDIC code page specified by the EBCDIC_CODEPAGE environment
variable. This error occurred because either a conversion table is not available for the specified
code pages, or the specification of the EBCDIC_CODE page is invalid. Execution will continue
with a default conversion table based on ASCII code page IBM-850 and EBCDIC code page
IBM-037.
Programmer Response: Verify that the EBCDIC_CODEPAGE environment variable has a valid
value (see “Locales and Code Sets Supported on AIX” on page 408).
If EBCDIC_CODEPAGE is not set, the default value, IBM-037, will be used. This is the default
code page used by IBM COBOL for OS/390 & VM.
System Action: No system action was taken.

IWZ230W The EBCDIC codepage specified, EBCDIC codepage, is not consistent with
the locale locale, but will be used as requested.

Explanation: The application has a module which was compiled with the CHAR(EBCDIC) com-
piler option. This error occurred because the code page specified is not the same language as the
current locale.
Programmer Response: Verify that the EBCDIC_CODEPAGE environment variable is valid for
this locale (see “Locales and Code Sets Supported on AIX” on page 408).
System Action: No system action was taken.

IWZ230W The EBCDIC codepage specified, EBCDIC codepage, is not supported. The
default EBCDIC codepage, EBCDIC codepage, will be used.

Explanation: The application has a module which was compiled with the CHAR(EBCDIC) com-
piler option. This error occurred because the specification of the EBCDIC_CODE page is invalid.
Execution will continue with the default host code page that corresponds to the current locale.
Programmer Response: Verify that the EBCDIC_CODEPAGE environment variable has a valid
value (see “Locales and Code Sets Supported on AIX” on page 408).
System Action: No system action was taken.

IWZ230S The EBCDIC conversion table cannot be opened.

Explanation: The current system installation does not include the translation table for the default
ASCII and EBCDIC code pages.
Programmer Response: Reinstall the compiler and run time. If the problem still persists, call
your IBM representative.
System Action: The application was terminated.

Appendix F. Run-Time Messages 551


IWZ230S ŸIWZ240S

IWZ230S The EBCDIC conversion table cannot be built.

Explanation: The ASCII to EBCDIC conversion table has been opened, but the conversion has
failed.
Programmer Response: Retry the execution from a new window.
System Action: The application was terminated.

IWZ231S Query of current locale setting failed.

Explanation: A query of the execution environment failed to identify a valid locale setting. The
current locale needs to be established to access appropriate message files and set the collating
order. It is also used by the date/time services and for EBCDIC character support.
Programmer Response: Check the settings for the following environment variables:
Ÿ LOCPATH
– Not used on AIX.
– On OS/2 and Windows, this environment variable should include the IBMCOBOL\LOCALE
directory
Ÿ LANG
– On OS/2, this environment variable should be set to the filename (without extension) of
one of the DLLs located in the IBM\LOCALE directory. The default value is en_US.
– On Windows this should be set to the name of one of the directories located in the
IBMCOBW\LOCALE directory. The default value is en_US.
– On AIX this should be set to a locale which has been installed on your machine. Type
"locale -a" to get a list of the valid values. The default value is en_US.
System Action: The application was terminated.

| IWZ240S The base year for program program-name was outside the valid range of
| 1900 through 1999. The sliding window value window-value resulted in a
| base year of base-year.

| Explanation: When the 100-year window was computed using the current year and the sliding
| window value specified with the YEARWINDOW compiler option, the base year of the 100-year
| window was outside the valid range of 1900 through 1999.
| For example, if a COBOL program had been compiled with YEARWINDOW(-99) and the COBOL
| program was run in the year 1998 this message would occur because the base year of the
| 100-year window would be 1899 (1998 - 99).
| Programmer Response: Examine the application design to determine if it will support a change
| to the YEARWINDOW option value. If the application can run with a change to the
| YEARWINDOW option value, then compile the program with an appropriate YEARWINDOW option
| value. If the application cannot run with a change to the YEARWINDOW option value, then
| convert all date fields to expanded dates and compile the program with NODATEPROC.
| System Action: The application was terminated.

552 COBOL Set for AIX Programming Guide


IWZ241S ŸIWZ902W

| IWZ241S The current year was outside the 100-year window, year-start through
| year-end, for program program-name.

| Explanation: The current year was outside the 100-year fixed window specified by the
| YEARWINDOW compiler option value.
| For example, if a COBOL program is compiled with YEARWINDOW(1920), the 100-year window
| for the program is 1920 through 2019. When the program is run in the year 2020, this error
| message would occur since the current year is not within the 100-year window.
| Programmer Response: Examine the application design to determine if it will support a change
| to the YEARWINDOW option value. If the application can run with a change to the
| YEARWINDOW option value, then compile the program with an appropriate YEARWINDOW option
| value. If the application cannot run with a change to the YEARWINDOW option value, then
| convert all date fields to expanded dates and compile the program with NODATEPROC.
| System Action: The application was terminated.

IWZ813S Insufficient storage was available to satisfy a get storage request.

Explanation: There was not enough free storage available to satisfy a get storage or reallocate
request. This message indicates that storage management could not obtain sufficient storage from
the operating system.
Programmer Response: Ensure that you have sufficient storage available to run your applica-
tion.
System Action: No storage is allocated.
Symbolic Feedback Code: CEE0PD

IWZ901W Message variants include:


Ÿ Program exits due to severe or critical error.
Ÿ Program exits: more than ERRCOUNT errors occurred.

Explanation: Every severe or critical message is followed by an IWZ901 message. An IWZ901


message is also issued if you have used the ERRCOUNT run-time option and the number of
warning messages exceeds ERRCOUNT.
Programmer Response: See the severe or critical message, or increase ERRCOUNT.
System Action: The application was terminated.

IWZ902W The system detected a decimal-divide exception.

Explanation: An attempt to divide a number by 0 was detected.


Programmer Response: Modify the program. For example, add ON SIZE ERROR to the
flagged statement.
System Action: No system action was taken.

Appendix F. Run-Time Messages 553


IWZ907W ŸIWZ995C

IWZ907W Message variants include:


Ÿ Insufficient storage.
Ÿ Insufficient storage. Cannot get number-bytes bytes of space for
storage.

Explanation: The run-time library requested virtual memory space and the operating system
denied the request.
Programmer Response: Your program uses a large amount of virtual memory and it ran out of
space. The problem is usually not due to a particular statement, but is associated with the
program as a whole. Look at your use of OCCURS clauses and reduce the size of your tables.
System Action: No system action was taken.

IWZ993W Insufficient storage. Cannot find space for message message-number.

Explanation: The run-time library requested virtual memory space and the operating system
denied the request.
Programmer Response: Your program uses a large amount of virtual memory and it ran out of
space. The problem is usually not due to a particular statement, but is associated with the
program as a whole. Look at your use of OCCURS clauses and reduce the size of your tables.
System Action: No system action was taken.

IWZ994W Cannot find message message-number in %s.

Explanation: The run-time library cannot find either the message catalog or a particular message
in the message catalog.
Programmer Response: Check that the COBOL library and messages were correctly installed
and that NLSPATH is specified correctly.
System Action: No system action was taken.

| IWZ995C Message variants include:


Ÿ system exception signal received while executing routine
Ÿ system exception signal received while executing code at location 0x
offset-value. routine-name at offset 0x offset-value.

Explanation: The operating system has detected an illegal action, such as an attempt to store
into a protected area of memory or the operating system has detected that you pressed the inter-
rupt key (typically the Control-C key, but it can be reconfigured).
Programmer Response: If the signal was due to an illegal action, run the program under the
debugger and it will give you more precise information as to where the error occurred. An
example of this type of error is a pointer with an illegal value.
System Action: The application was terminated.

554 COBOL Set for AIX Programming Guide


IWZ2502S ŸIWZ2506S

IWZ2502S The UTC/GMT was not available from the system.

Explanation: A call to CEEUTC or CEEGMT failed because the system clock was in an invalid
state. The current time could not be determined.
Programmer Response: Notify systems support personnel that the system clock is in an invalid
state.
System Action: All output values are set to 0.
Symbolic Feedback Code: CEE2E6

IWZ2503S The offset from UTC/GMT to local time was not available from the system.

Explanation: A call to CEEGMTO failed because either (1) the current operating system could
not be determined, or (2) the time zone field in the operating system control block appears to
contain invalid data.
Programmer Response: Notify systems support personnel that the local time offset stored in the
operating system appears to contain invalid data.
System Action: All output values are set to 0.
Symbolic Feedback Code: CEE2E7

IWZ2505S The input_seconds value in a call to CEEDATM or CEESECI was not within
the supported range.

Explanation: The input_seconds value passed in a call to CEEDATM or CEESECI was not a
floating-point number between 86,400.0 and 265,621,679,999.999 The input parameter should rep-
resent the number of seconds elapsed since 00:00:00 on 14 October 1582, with 00:00:00.000 15
October 1582 being the first supported date/time, and 23:59:59.999 31 December 9999 being the
last supported date/time.
Programmer Response: Verify that input parameter contains a floating-point value between
86,400.0 and 265,621,679,999.999.
System Action: For CEEDATM, the output value is set to blanks. For CEESECI, all output
parameters are set to 0.
Symbolic Feedback Code: CEE2E9

IWZ2506S Japanese (<JJJJ>) or Republic of China (<CCCC> or <CCCCCCCC>) Era


was used in a picture string passed to CEEDATM, but the input number-of-
seconds value was not within the supported range. The era could not be
determined.

Explanation: In a CEEDATM call, the picture string indicates that the input value is to be con-
verted to a Japanese or Republic of China Era; however the input value that was specified lies
outside the range of supported eras.
Programmer Response: Verify that the input value contains a valid number-of-seconds value
within the range of supported eras.
System Action: The output value is set to blanks.

Appendix F. Run-Time Messages 555


IWZ2507S ŸIWZ2510S

IWZ2507S Insufficient data was passed to CEEDAYS or CEESECS. The Lilian value
was not calculated.

Explanation: The picture string passed in a CEEDAYS or CEESECS call did not contain enough
information. For example, it is an error to use the picture string ‘MM/DD’ (month and day only) in
a call to CEEDAYS or CEESECS, because the year value is missing. The minimum information
required to calculate a Lilian value is either (1) month, day and year, or (2) year and Julian day.
Programmer Response: Verify that the picture string specified in a call to CEEDAYS or
CEESECS specifies, as a minimum, the location in the input string of either (1) the year, month,
and day, or (2) the year and Julian day.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EB

IWZ2508S The date value passed to CEEDAYS or CEESECS was invalid.

Explanation: In a CEEDAYS or CEESECS call, the value in the DD or DDD field is not valid for
the given year and/or month. For example, ‘MM/DD/YY’ with ‘02/29/90’, or ‘YYYY.DDD’ with
‘1990.366’ are invalid because 1990 is not a leap year. This code may also be returned for any
non-existent date value such as June 31st, January 0.
Programmer Response: Verify that the format of the input data matches the picture string spec-
ification and that input data contains a valid date.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EC

IWZ2509S The Japanese or Republic of China Era passed to CEEDAYS or CEESECS


was not recognized.

Explanation: The value in the <JJJJ>, <CCCC>, or <CCCCCCCC> field passed in a call to
CEEDAYS or CEESECS does not contain a supported Japanese or Republic of China Era name.
Programmer Response: Verify that the format of the input data matches the picture string spec-
ification and that the spelling of the Japanese or ROC Era name is correct. Note that the era
name must be a proper DBCS string where the '<' position must contain the first byte of the era
name.
System Action: The output value is set to 0.

IWZ2510S The hours value in a call to CEEISEC or CEESECS was not recognized.

Explanation: (1) In a CEEISEC call, the hours parameter did not contain a number between 0
and 23, or (2) in a CEESECS call, the value in the HH (hours) field does not contain a number
between 0 and 23, or the “AP” (a.m./p.m.) field is present and the HH field does not contain a
number between 1 and 12.
Programmer Response: For CEEISEC, verify that the hours parameter contains an integer
between 0 and 23. For CEESECS, verify that the format of the input data matches the picture
string specification, and that the hours field contains a value between 0 and 23, (or 1 and 12 if the
“AP” field is used).

556 COBOL Set for AIX Programming Guide


IWZ2511S ŸIWZ2513S

System Action: The output value is set to 0.


Symbolic Feedback Code: CEE2EE

IWZ2511S The day parameter passed in a CEEISEC call was invalid for year and
month specified.

Explanation: The day parameter passed in a CEEISEC call did not contain a valid day number.
The combination of year, month, and day formed an invalid date value. Examples: year=1990,
month=2, day=29; or month=6, day=31; or day=0.
Programmer Response: Verify that the day parameter contains an integer between 1 and 31,
and that the combination of year, month, and day represents a valid date.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EF

IWZ2512S The Lilian date value passed in a call to CEEDATE or CEEDYWK was not
within the supported range.

Explanation: The Lilian day number passed in a call to CEEDATE or CEEDYWK was not a
number between 1 and 3,074,324.
Programmer Response: Verify that the input parameter contains an integer between 1 and
3,074,324.
System Action: The output value is set to blanks.
Symbolic Feedback Code: CEE2EG

IWZ2513S The input date passed in a CEEISEC, CEEDAYS, or CEESECS call was not
within the supported range.

Explanation: The input date passed in a CEEISEC, CEEDAYS, or CEESECS call was earlier
than 15 October 1582, or later than 31 December 9999.
Programmer Response: For CEEISEC, verify that the year, month, and day parameters form a
date greater than or equal to 15 October 1582. For CEEDAYS and CEESECS, verify that the
format of the input date matches the picture string specification, and that the input date is within
the supported range.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EH

Appendix F. Run-Time Messages 557


IWZ2514S ŸIWZ2517S

IWZ2514S The year value passed in a CEEISEC call was not within the supported
range.

Explanation: The year parameter passed in a CEEISEC call did not contain a number between
1582 and 9999.
Programmer Response: Verify that the year parameter contains valid data, and that the year
parameter includes the century, for example, specify year 1990, not year 90.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EI

IWZ2515S The milliseconds value in a CEEISEC call was not recognized.

Explanation: In a CEEISEC call, the milliseconds parameter (input_milliseconds) did not contain
a number between 0 and 999.
Programmer Response: Verify that the milliseconds parameter contains an integer between 0
and 999.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EJ

IWZ2516S The minutes value in a CEEISEC call was not recognized.

Explanation: (1) In a CEEISEC call, the minutes parameter (input_minutes) did not contain a
number between 0 and 59, or (2) in a CEESECS call, the value in the MI (minutes) field did not
contain a number between 0 and 59.
Programmer Response: For CEEISEC, verify that the minutes parameter contains an integer
between 0 and 59. For CEESECS, verify that the format of the input data matches the picture
string specification, and that the minutes field contains a number between 0 and 59.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EK

IWZ2517S The month value in a CEEISEC call was not recognized.

Explanation: (1) In a CEEISEC call, the month parameter (input_month) did not contain a
number between 1 and 12, or (2) in a CEEDAYS or CEESECS call, the value in the MM field did
not contain a number between 1 and 12, or the value in the MMM, MMMM, etc. field did not
contain a correctly spelled month name or month abbreviation in the currently active National Lan-
guage.
Programmer Response: For CEEISEC, verify that the month parameter contains an integer
between 1 and 12. For CEEDAYS and CEESECS, verify that the format of the input data matches
the picture string specification. For the MM field, verify that the input value is between 1 and 12.
For spelled-out month names (MMM, MMMM, etc.), verify that the spelling or abbreviation of the
month name is correct in the currently active National Language.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EL

558 COBOL Set for AIX Programming Guide


IWZ2518S ŸIWZ2521S

IWZ2518S An invalid picture string was specified in a call to a date/time service.

Explanation: The picture string supplied in a call to one of the date/time services was invalid.
Only one era character string can be specified.
Programmer Response: Verify that the picture string contains valid data. If the picture string
contains more than one era descriptor, such as both Japanese (<JJJJ>) and Republic of China
(<CCCC>) being specified, then change the picture string to use only one era.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EM

IWZ2519S The seconds value in a CEEISEC call was not recognized.

Explanation: (1) In a CEEISEC call, the seconds parameter (input_seconds) did not contain a
number between 0 and 59, or (2) in a CEESECS call, the value in the SS (seconds) field did not
contain a number between 0 and 59.
Programmer Response: For CEEISEC, verify that the seconds parameter contains an integer
between 0 and 59. For CEESECS, verify that the format of the input data matches the picture
string specification, and that the seconds field contains a number between 0 and 59.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EN

IWZ2520S CEEDAYS detected non-numeric data in a numeric field, or the date string
did not match the picture string.

Explanation: The input value passed in a CEEDAYS call did not appear to be in the format
described by the picture specification, for example, non-numeric characters appear where only
numeric characters are expected.
Programmer Response: Verify that the format of the input data matches the picture string spec-
ification and that numeric fields contain only numeric data.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2EO

IWZ2521S The Japanese (<JJJJ>) or Chinese (<CCCC>) year-within-Era value passed


to CEEDAYS or CEESECS was zero.

Explanation: In a CEEDAYS or CEESECS call, if the YY or ZYY picture token is specified, and if
the picture string contains one of the era tokens such as <CCCC> or <JJJJ>, then the year value
must be greater than or equal to 1 and must be a valid year value for the era. In this context, the
YY or ZYY field means year within Era.
Programmer Response: Verify that the format of the input data matches the picture string spec-
ification and that the input data is valid.
System Action: The output value is set to 0.

Appendix F. Run-Time Messages 559


IWZ2522S ŸIWZ2527S

IWZ2522S Japanese (<JJJJ>) or Republic of China (<CCCC> or <CCCCCCCC>) Era


was used in a picture string passed to CEEDATE, but the Lilian date value
was not within the supported range. The era could not be determined.

Explanation: In a CEEDATE call, the picture string indicates that the Lilian date is to be con-
verted to a Japanese or Republic of China Era, but the Lilian date lies outside the range of sup-
ported eras.
Programmer Response: Verify that the input value contains a valid Lilian day number within the
range of supported eras.
System Action: The output value is set to blanks.

IWZ2525S CEESECS detected non-numeric data in a numeric field, or the timestamp


string did not match the picture string.

Explanation: The input value passed in a CEESECS call did not appear to be in the format
described by the picture specification. For example, non-numeric characters appear where only
numeric characters are expected, or the a.m./p.m. field (AP, A.P., etc.) did not contain the strings
‘AM’ or ‘PM’.
Programmer Response: Verify that the format of the input data matches the picture string spec-
ification and that numeric fields contain only numeric data.
System Action: The output value is set to 0.
Symbolic Feedback Code: CEE2ET

| IWZ2526S The date string returned by CEEDATE was truncated.

Explanation: In a CEEDATE call, the output string was not large enough to contain the formatted
date value.
Programmer Response: Verify that the output string variable is large enough to contain the
entire formatted date. Ensure that the output parameter is at least as long as the picture string
parameter.
System Action: The output value is truncated to the length of the output parameter.
Symbolic Feedback Code: CEE2EU

| IWZ2527S The timestamp string returned by CEEDATM was truncated.

Explanation: In a CEEDATM call, the output string was not large enough to contain the for-
matted timestamp value.
Programmer Response: Verify that the output string variable is large enough to contain the
entire formatted timestamp. Ensure that the output parameter is at least as long as the picture
string parameter.
System Action: The output value is truncated to the length of the output parameter.
Symbolic Feedback Code: CEE2EV

560 COBOL Set for AIX Programming Guide


IWZ2531S ŸIWZ2534W

IWZ2531S The local time was not available from the system.

Explanation: A call to CEELOCT failed because the system clock was in an invalid state. The
current time cannot be determined.
Programmer Response: Notify systems support personnel that the system clock is in an invalid
state.
System Action: All output values are set to 0.
Symbolic Feedback Code: CEE2F3

IWZ2533S The value passed to CEESCEN was not between 0 and 100.

Explanation: The century_start value passed in a CEESCEN call was not between 0 and 100,
inclusive.
Programmer Response: Ensure that the input parameter is within range.
System Action: No system action is taken; the 100-year window assumed for all 2-digit years is
unchanged.
Symbolic Feedback Code: CEE2F5

IWZ2534W Insufficient field width was specified for a month or weekday name in a call
to CEEDATE or CEEDATM. Output set to blanks.

Explanation: The CEEDATE or CEEDATM callable services issues this message whenever the
picture string contained MMM, MMMMMZ, WWW, Wwww, etc., requesting a spelled out month
name or weekday name, and the month name currently being formatted contained more charac-
ters than can fit in the indicated field.
Programmer Response: Increase the field width by specifying enough Ms or Ws to contain the
longest month or weekday name being formatted.
System Action: The month name and weekday name fields that are of insufficient width are set
to blanks. The rest of the output string is unaffected. Processing continues.
Symbolic Feedback Code: CEE2F6

Appendix F. Run-Time Messages 561


Bibliography

COBOL Set for AIX CICS


Administration Guide, SC33-1562
Fact Sheet, GC26-8484
Administration Reference, SC33-1563
Getting Started, GC26-8425
Application Programming Guide, SC33-1568
Language Reference, SC26-9046
Application Programming Reference, SC33-1569
LPEX User's Guide and Reference, SC09-2202
Encina for CICS, SC33-1567
Program Builder User's Guide, SC09-2201
Intercommunication Guide, SC33-1564
Programming Guide, SC26-8423
Messages and Codes, SC33-1566
Planning and Installation Guide, GC33-1561
Related Publications
Problem Determination Guide, SC33-1565

COBOL for OS/390 & VM


DB2
Compiler and Run-Time Migration Guide,
GC26-4764 Application Programming Guide, S20H-4643

Debug Tool User's Guide and Reference, DATABASE 2 AIX/6000 Command Reference,
SC09-2137 SC09-1575

Diagnosis Guide, GC26-9047 SQL Reference, S20H-4665

Fact Sheet, GC26-9048


SMARTdata Utilities for AIX
Installation and Customization under OS/390,
GC26-9045 Data Description and Conversion A Data Language
Reference, SC26-7092
Language Reference, SC26-9046
Data Description and Conversion, SC26-7066
Licensed Program Specifications, GC26-9044
VSAM in a Distributed Environment, SC26-7064
Programming Guide, SC26-9049

SOMobjects for AIX


VisualAge COBOL
SOMobjects Base Toolkit Programmer's Reference,
Building Parts for Fun and Profit, GC26-9038 SC23-2681-01
COBOL Resource Catalog, GC26-8488 SOMobjects Base Toolkit Quick Reference Guide,
Fact Sheet, GC26-9052 SC23-2682-01
Getting Started on OS/2, GC26-9051 SOMobjects Base Toolkit User's Guide,
SC23-2680-01
Getting Started on Windows, GC26-8944
SOMobjects Developer's Toolkit Programming Guide
Introducing Redeveloper, SC26-9056
Language Reference, SC26-9046
Other
Programming Guide, SC26-9050
AIX System Management Guide: Communications
Technology Brochure, GC26-9060 and Networks, GC23-2487
Visual Builder User's Guide, SC26-9053 Structured File Server Programmer's Guide and Ref-
erence for AIX, SC33-1610

562  Copyright IBM Corp. 1996, 1998


Glossary
The terms in this glossary are defined in accordance alphanumeric-edited character. A character within an
with their meaning in COBOL. These terms may or may alphanumeric character-string that contains at least one
not have the same meaning in other languages. B, 0 (zero), or / (slash).

IBM is grateful to the American National Standards Insti- * alphanumeric function. A function whose value is
tute (ANSI) for permission to reprint its definitions from composed of a string of one or more characters from the
the following publications: computer's character set.
Ÿ American National Standard Programming Lan-
* alternate record key. A key, other than the prime
guage COBOL, ANSI X3.23-1985 (Copyright 1985
record key, whose contents identify a record within an
American National Standards Institute, Inc.), which
indexed file.
was prepared by Technical Committee X3J4, which
had the task of revising American National Standard ANSI (American National Standards Institute). An
COBOL, X3.23-1974. organization consisting of producers, consumers, and
Ÿ American National Dictionary for Information Proc- general interest groups, that establishes the procedures
essing Systems (Copyright 1982 by the Computer by which accredited organizations create and maintain
and Business Equipment Manufacturers Associ- voluntary industry standards in the United States.
ation).
* argument. An identifier, a literal, an arithmetic
American National Standard definitions are preceded by expression, or a function-identifier that specifies a value
an asterisk (*). to be used in the evaluation of a function.

* arithmetic expression. An identifier of a numeric ele-


A mentary item, a numeric literal, such identifiers and
literals separated by arithmetic operators, two arithmetic
* abbreviated combined relation condition. The com- expressions separated by an arithmetic operator, or an
bined condition that results from the explicit omission of arithmetic expression enclosed in parentheses.
a common subject or a common subject and common
relational operator in a consecutive sequence of relation * arithmetic operation. The process caused by the
conditions. execution of an arithmetic statement, or the evaluation of
an arithmetic expression, that results in a mathematically
abend. Abnormal termination of program. correct solution to the arguments presented.

* access mode. The manner in which records are to * arithmetic operator. A single character, or a fixed
be operated upon within a file. two-character combination that belongs to the following
set:
* actual decimal point. The physical representation, Character Meaning
using the decimal point characters period (.) or comma + addition
(,), of the decimal point position in a data item. - subtraction
* multiplication
* alphabet-name. A user-defined word, in the
/ division
SPECIAL-NAMES paragraph of the ENVIRONMENT
** exponentiation
DIVISION, that assigns a name to a specific character
set and/or collating sequence. * arithmetic statement. A statement that causes an
arithmetic operation to be executed. The arithmetic
* alphabetic character. A letter or a space character.
statements are the ADD, COMPUTE, DIVIDE, MUL-
TIPLY, and SUBTRACT statements.
* alphanumeric character. Any character in the
computer’s character set.
array. In Language Environment, an aggregate con-
sisting of data objects, each of which may be uniquely

 Copyright IBM Corp. 1996, 1998 563


referenced by subscripting. Roughly analogous to a decimal digits 0 through 9, plus an operational sign. The
COBOL table. leftmost bit of the item is the operational sign.

* ascending key. A key upon the values of which data binary search. A dichotomizing search in which, at
is ordered, starting with the lowest value of the key up to each step of the search, the set of data elements is
the highest value of the key, in accordance with the divided by two; some appropriate action is taken in the
rules for comparing data items. case of an odd number.

ASCII. American National Standard Code for Informa- * block. A physical unit of data that is normally com-
tion Interchange. The standard code, using a coded posed of one or more logical records. For mass storage
character set consisting of 7-bit coded characters (8 bits files, a block may contain a portion of a logical record.
including parity check), used for information interchange The size of a block has no direct relationship to the size
between data processing systems, data communication of the file within which the block is contained or to the
systems, and associated equipment. The ASCII set con- size of the logical record(s) that are either contained
sists of control characters and graphic characters. within the block or that overlap the block. The term is
synonymous with physical record.
Extension: IBM has defined an extension to ASCII
code (characters 128-255).
breakpoint. A place in a computer program, usually
specified by an instruction, where its execution may be
assignment-name. A name that identifies the organiza-
interrupted by external intervention or by a monitor
tion of a COBOL file and the name by which it is known
program.
to the system.
Btrieve. A key-indexed record management system
* assumed decimal point. A decimal point position
that allows applications to manage records by key value,
that does not involve the existence of an actual char-
sequential access method, or random access method.
acter in a data item. The assumed decimal point has
IBM COBOL supports COBOL sequential and indexed
logical meaning with no physical representation.
file I-O language through Btrieve.
* AT END condition. A condition caused:
buffer. A portion of storage used to hold input or output
1. During the execution of a READ statement for a data temporarily.
sequentially accessed file, when no next logical
record exists in the file, or when the number of sig- built-in function. See “intrinsic function.”
nificant digits in the relative record number is larger
than the size of the relative key data item, or when byte. A string consisting of a certain number of bits,
an optional input file is not present. usually eight, treated as a unit, and representing a char-
acter.
2. During the execution of a RETURN statement, when
no next logical record exists for the associated sort
or merge file.
C
3. During the execution of a SEARCH statement, when
the search operation terminates without satisfying callable services. In Language Environment, a set of
the condition specified in any of the associated services that can be invoked by a COBOL program
WHEN phrases. using the conventional Language Environment-defined
call interface, and usable by all programs sharing the
Language Environment conventions.
B
called program. A program that is the object of a
big-endian. Default format used by the mainframe and CALL statement.
the AIX workstation to store binary data. In this format,
the least significant digit is on the highest address. * calling program. A program that executes a CALL to
Compare with “little-endian.” another program.

binary item. A numeric data item represented in binary case structure. A program processing logic in which a
notation (on the base 2 numbering system). Binary series of conditions is tested in order to make a choice
items have a decimal equivalent consisting of the between a number of resulting actions.

564 COBOL Set for AIX Programming Guide


| century window. A century window is a 100-year data item consists exclusively of those characters listed
| interval within which any 2-digit year is unique. There in the definition of the class-name.
| are several types of century window available to COBOL
| programmers: class object. The run-time object representing a SOM
class.
| 1. For windowed date fields, the YEARWINDOW com-
| piler option * clause. An ordered set of consecutive COBOL
| 2. For windowing intrinsic functions character-strings whose purpose is to specify an attri-
| DATE-TO-YYYYMMDD, DAY-TO-YYYYDDD, and bute of an entry.
| YEAR-TO-YYYY, it is specified by argument-2
CMS (Conversational Monitor System). A virtual
| 3. For date and time callable services, it is specified in machine operating system that provides general interac-
| CEESCEN tive, time-sharing, problem solving, and program devel-
opment capabilities, and that operates only under the
* character. The basic indivisible unit of the language.
control of the VM/SP control program.
character position. The amount of physical storage
* COBOL character set. The complete COBOL char-
required to store a single standard data format character
acter set consists of the characters listed below:
described as USAGE IS DISPLAY.
Character Meaning
character set. All the valid characters for a program- 0,1...,9 digit
ming language or a computer system. A,B,...,Z uppercase letter
a,b,...,z lowercase letter
* character-string. A sequence of contiguous charac- ␣ space
ters that form a COBOL word, a literal, a PICTURE + plus sign
character-string, or a comment-entry. Must be delimited - minus sign (hyphen)
by separators. * asterisk
/ slant (virgule, slash)
checkpoint. A point at which information about the = equal sign
status of a job and the system can be recorded so that $ currency sign
the job step can be later restarted. , comma (decimal point)
; semicolon
* class. The entity that defines common behavior and . period (decimal point, full stop)
implementation for zero, one, or more objects. The " quotation mark
objects that share the same implementation are consid- ( left parenthesis
ered to be objects of the same class. ) right parenthesis
> greater than symbol
* class condition. The proposition, for which a truth
< less than symbol
value can be determined, that the content of an item is
: colon
wholly alphabetic, is wholly numeric, or consists exclu-
sively of those characters listed in the definition of a * COBOL word. See “word.”
class-name.
code page. An assignment of graphic characters and
* Class Definition. The COBOL source unit that control function meanings to all code points; for
defines a class. example, assignment of characters and meanings to 256
code points for 8-bit code, assignment of characters and
* class identification entry. An entry in the CLASS-ID
meanings to 128 code points for 7-bit code.
paragraph of the IDENTIFICATION DIVISION which con-
tains clauses that specify the class-name and assign * collating sequence. The sequence in which the char-
selected attributes to the class definition. acters that are acceptable to a computer are ordered for
purposes of sorting, merging, comparing, and for proc-
* class-name. A user-defined word defined in the
essing indexed files sequentially.
SPECIAL-NAMES paragraph of the ENVIRONMENT
DIVISION that assigns a name to the proposition for * column. A character position within a print line. The
which a truth value can be defined, that the content of a columns are numbered from 1, by 1, starting at the left-

Glossary 565
most character position of the print line and extending to | – Another windowed date field with date format
the rightmost position of the print line. | YYXXX
| – An expanded date field with date format
* combined condition. A condition that is the result of | YYYYXXX
connecting two or more conditions with the AND or the
OR logical operator. * compile. (1) To translate a program expressed in a
high-level language into a program expressed in an
* comment-entry. An entry in the IDENTIFICATION intermediate language, assembly language, or a com-
DIVISION that may be any combination of characters puter language. (2) To prepare a machine language
from the computer’s character set. program from a computer program written in another
programming language by making use of the overall
* comment line. A source program line represented by logic structure of the program, or generating more than
an asterisk (*) in the indicator area of the line and any one computer instruction for each symbolic statement, or
characters from the computer’s character set in area A both, as well as performing the function of an assembler.
and area B of that line. The comment line serves only
for documentation in a program. A special form of * compile time. The time at which a COBOL source
comment line represented by a slant (/) in the indicator program is translated, by a COBOL compiler, to a
area of the line and any characters from the computer’s COBOL object program.
character set in area A and area B of that line causes
page ejection prior to printing the comment. compiler. A program that translates a program written
in a higher level language into a machine language
* common program. A program which, despite being object program.
directly contained within another program, may be called
from any program directly or indirectly contained in that compiler directing statement. A statement, beginning
other program. with a compiler directing verb, that causes the compiler
to take a specific action during compilation.
| compatible dates. The meaning of the term “compat-
| ible,” when applied to date fields, depends on the compiler directing statement. A statement that speci-
| COBOL division in which the usage occurs: fies actions to be taken by the compiler during proc-
essing of a COBOL source program. Compiler
| Ÿ Data Division
directives are contained in the COBOL source program.
| Two date fields are compatible if they have identical Thus, you can specify different suboptions of the direc-
| USAGE and meet at least one of the following tive within the source program by using multiple compiler
| conditions: directive statements in the program.
| – They have the same date format.
* complex condition. A condition in which one or more
| – Both are windowed date fields, where one con- logical operators act upon one or more conditions. (See
| sists only of a windowed year, date format YY. also “negated simple condition,” “combined condition,”
| – Both are expanded date fields, where one con- and “negated combined condition.”)
| sists only of an expanded year, date format
* computer-name. A system-name that identifies the
| YYYY.
computer upon which the program is to be compiled or
| – One has date format YYXXXX, the other, run.
| YYXX.
condition. An exception that has been enabled, or
| – One has date format YYYYXXXX, the other,
recognized, by Language Environment and thus is eli-
| YYYYXX.
gible to activate user and language condition handlers.
| Ÿ Procedure Division Any alteration to the normal programmed flow of an
| Two date fields are compatible if they have the application. Conditions can be detected by the
| same date format except for the year part, which hardware/operating system and results in an interrupt.
| may be windowed or expanded. For example, a They can also be detected by language-specific gener-
| windowed date field with date format YYXXX is ated code or language library code.
| compatible with:
* condition. A status of a program at run time for
which a truth value can be determined. Where the term

566 COBOL Set for AIX Programming Guide


‘condition’ (condition-1, condition-2,...) appears in these copybook. A file or library member containing a
language specifications in or in reference to ‘condition’ sequence of code that is included in the source program
(condition-1, condition-2,...) of a general format, it is a at compile time using the COPY statement. The file can
conditional expression consisting of either a simple con- be created by the user, supplied by COBOL, or supplied
dition optionally parenthesized, or a combined condition by another product.
consisting of the syntactically correct combination of
simple conditions, logical operators, and parentheses, for CORBA. The Common Object Request Broker Archi-
which a truth value can be determined. tecture established by the Object Management Group.
IBM's Interface Definition Language used to describe the
* conditional expression. A simple condition or a interface for SOM classes is fully compliant with CORBA
complex condition specified in an EVALUATE, IF, standards.
PERFORM, or SEARCH statement. (See also “simple
condition” and “complex condition.”) * counter. A data item used for storing numbers or
number representations in a manner that permits these
* conditional phrase. A conditional phrase specifies numbers to be increased or decreased by the value of
the action to be taken upon determination of the truth another number, or to be changed or reset to zero or to
value of a condition resulting from the execution of a an arbitrary positive or negative value.
conditional statement.
cross-reference listing. The portion of the compiler
* conditional statement. A statement specifying that listing that contains information on where files, fields,
the truth value of a condition is to be determined and and indicators are defined, referenced, and modified in a
that the subsequent action of the object program is program.
dependent on this truth value.
currency sign. The character ‘$’ of the COBOL char-
* conditional variable. A data item one or more values acter set or that character defined by the CURRENCY
of which has a condition-name assigned to it. compiler option. If the NOCURRENCY compiler option
is in effect, the currency sign is defined as the character
* condition-name. A user-defined word that assigns a ‘$’.
name to a subset of values that a conditional variable
may assume; or a user-defined word assigned to a currency symbol. The character defined by the CUR-
status of an implementor defined switch or device. RENCY compiler option or by the CURRENCY SIGN
When ‘condition-name’ is used in the general formats, it clause in the SPECIAL-NAMES paragraph. If the
represents a unique data item reference consisting of a NOCURRENCY compiler option is in effect for a COBOL
syntactically correct combination of a ‘condition-name’, source program and the CURRENCY SIGN clause is
together with qualifiers and subscripts, as required for also not present in the source program, the currency
uniqueness of reference. symbol is identical to the currency sign.

* condition-name condition. The proposition, for * current record. In file processing, the record that is
which a truth value can be determined, that the value of available in the record area associated with a file.
a conditional variable is a member of the set of values
attributed to a condition-name associated with the condi- * current volume pointer. A conceptual entity that
tional variable. points to the current volume of a sequential file.

* CONFIGURATION SECTION. A section of the ENVI-


RONMENT DIVISION that describes overall specifica- D
tions of source and object programs and class
definitions. * data clause. A clause, appearing in a data
description entry in the DATA DIVISION of a COBOL
CONSOLE. A COBOL environment-name associated program, that provides information describing a particular
with the operator console. attribute of a data item.

* contiguous items. Items that are described by con- * data description entry . An entry in the DATA DIVI-
secutive entries in the Data Division, and that bear a SION of a COBOL program that is composed of a level-
definite hierarchic relationship to each other. number followed by a data-name, if required, and then
followed by a set of data clauses, as required.

Glossary 567
DATA DIVISION. One of the four main components of * debugging line. A debugging line is any line with a
a COBOL program, class definition, or method definition. ‘D’ in the indicator area of the line.
The DATA DIVISION describes the data to be processed
by the object program, class, or method: files to be * debugging section. A section that contains a USE
used and the records contained within them; internal FOR DEBUGGING statement.
working-storage records that will be needed; data to be
made available in more than one program in the COBOL * declarative sentence. A compiler directing sentence
run unit. (Note, the Class DATA DIVISION contains only consisting of a single USE statement terminated by the
the WORKING-STORAGE SECTION.) separator period.

* data item. A unit of data (excluding literals) defined * declaratives. A set of one or more special purpose
by a COBOL program or by the rules for function evalu- sections, written at the beginning of the Procedure Divi-
ation. sion, the first of which is preceded by the key word
DECLARATIVES and the last of which is followed by the
* data-name. A user-defined word that names a data key words END DECLARATIVES. A declarative is com-
item described in a data description entry. When used posed of a section header, followed by a USE compiler
in the general formats, ‘data-name’ represents a word directing sentence, followed by a set of zero, one, or
that must not be reference-modified, subscripted or qual- more associated paragraphs.
ified unless specifically permitted by the rules for the
format. * de-edit. The logical removal of all editing characters
from a numeric edited data item in order to determine
| date field. Any of the following: that item's unedited numeric value.
| Ÿ A data item whose data description entry includes a * delimited scope statement. Any statement that
| DATE FORMAT clause. includes its explicit scope terminator.
| Ÿ A value returned by one of the following intrinsic
| functions: * delimiter. A character or a sequence of contiguous
characters that identify the end of a string of characters
| DATE-OF-INTEGER and separate that string of characters from the following
| DATE-TO-YYYYMMDD string of characters. A delimiter is not part of the string
| DATEVAL of characters that it delimits.
| DAY-OF-INTEGER
| DAY-TO-YYYYDDD * descending key. A key upon the values of which
| YEAR-TO-YYYY data is ordered starting with the highest value of key
| YEARWINDOW down to the lowest value of key, in accordance with the
| Ÿ The conceptual data items DATE, DATE rules for comparing data items.
| YYYYMMDD, DAY, and DAY YYYYDDD in the
| Format 2 ACCEPT statement. digit. Any of the numerals from 0 through 9. In
COBOL, the term is not used in reference to any other
| Ÿ The result of certain arithmetic operations. symbol.
| The term date field refers to both “expanded date field”
| and “windowed date field.” See also “non-date.” * digit position. The amount of physical storage
required to store a single digit. This amount may vary
| date format. The date pattern of a date field, specified depending on the usage specified in the data description
| either: entry that defines the data item.

| Ÿ Explicitly, by the DATE FORMAT clause or * direct access. The facility to obtain data from storage
| DATEVAL intrinsic function devices or to enter data into a storage device in such a
| or way that the process depends only on the location of
that data and not on a reference to data previously
| Ÿ Implicitly, by statements and intrinsic functions that accessed.
| return date fields.
* division. A collection of zero, one or more sections or
DBCS (Double-Byte Character Set). See “Double- paragraphs, called the division body, that are formed
Byte Character Set (DBCS).” and combined in accordance with a specific set of rules.

568 COBOL Set for AIX Programming Guide


Each division consists of the division header and the
related division body. There are four (4) divisions in a E
COBOL program: Identification, Environment, Data, and
Procedure. * EBCDIC (Extended Binary-Coded Decimal Inter-
change Code). A coded character set consisting of
* division header. A combination of words followed by 8-bit coded characters.
a separator period that indicates the beginning of a divi-
sion. The division headers are: EBCDIC character. Any one of the symbols included in
the 8-bit EBCDIC (Extended Binary-Coded-Decimal
IDENTIFICATION DIVISION. Interchange Code) set.
ENVIRONMENT DIVISION.
DATA DIVISION. edited data item. A data item that has been modified
PROCEDURE DIVISION. by suppressing zeroes and/or inserting editing charac-
ters.
do construction. In structured programming, a DO
statement is used to group a number of statements in a * editing character. A single character or a fixed two-
procedure. In COBOL, an in-line PERFORM statement character combination belonging to the following set:
functions in the same way.
Character Meaning
do-until. In structured programming, a do-until loop will ␣ space
be executed at least once, and until a given condition is 0 zero
true. In COBOL, a TEST AFTER phrase used with the + plus
PERFORM statement functions in the same way. - minus
CR credit
do-while. In structured programming, a do-while loop DB debit
will be executed if, and while, a given condition is true. Z zero suppress
In COBOL, a TEST BEFORE phrase used with the * check protect
PERFORM statement functions in the same way. $ currency sign
, comma (decimal point)
Double-Byte Character Set (DBCS). A set of charac- . period (decimal point)
ters in which each character is represented by two / slant (virgule, slash)
bytes. Languages such as Japanese, Chinese, and
Korean, which contain more symbols than can be element (text element). One logical unit of a string of
represented by 256 code points, require Double-Byte text, such as the description of a single data item or
Character Sets. Because each character requires two verb, preceded by a unique code identifying the element
bytes, entering, displaying, and printing DBCS charac- type.
ters requires hardware and supporting software that are
DBCS-capable. * elementary item. A data item that is described as not
being further logically subdivided.
* dynamic access. An access mode in which specific
logical records can be obtained from or placed into a enclave. When running under the Language Environ-
mass storage file in a nonsequential manner and ment product, an enclave is analogous to a run unit. An
obtained from a file in a sequential manner during the enclave can create other enclaves on OS/390 and CMS
scope of the same OPEN statement. by a LINK, on CMS by CMSCALL, and the use of the
system () function of C.
Dynamic Storage Area (DSA). Dynamically acquired
storage composed of a register save area and an area *end class header. A combination of words, followed
available for dynamic storage allocation (such as by a separator period, that indicates the end of a
program variables). DSAs are generally allocated within COBOL class definition. The end class header is:
STACK segments managed by Language Environment. END CLASS class-name.

*end method header. A combination of words, fol-


lowed by a separator period, that indicates the end of a
COBOL method definition. The end method header is:
END METHOD method-name.

Glossary 569
* end of Procedure Division. The physical position of exponent. A number, indicating the power to which
a COBOL source program after which no further proce- another number (the base) is to be raised. Positive
dures appear. exponents denote multiplication, negative exponents
denote division, fractional exponents denote a root of a
* end program header. A combination of words, fol- quantity. In COBOL, an exponential expression is indi-
lowed by a separator period, that indicates the end of a cated with the symbol ‘**’ followed by the exponent.
COBOL source program. The end program header is:
END PROGRAM program-name. * expression. An arithmetic or conditional expression.

* entry. Any descriptive set of consecutive clauses ter- * extend mode. The state of a file after execution of an
minated by a separator period and written in the IDEN- OPEN statement, with the EXTEND phrase specified for
TIFICATION DIVISION, ENVIRONMENT DIVISION, or that file, and before the execution of a CLOSE state-
DATA DIVISION of a COBOL program. ment, without the REEL or UNIT phrase for that file.

* environment clause. A clause that appears as part extensions. Certain COBOL syntax and semantics
of an ENVIRONMENT DIVISION entry. supported by IBM compilers in addition to those
described in ANSI Standard.
ENVIRONMENT DIVISION. One of the four main com-
ponent parts of a COBOL program, class definition, or * external data. The data described in a program as
method definition. The ENVIRONMENT DIVISION external data items and external file connectors.
describes the computers upon which the source program
* external data item. A data item which is described as
is compiled and those on which the object program is
part of an external record in one or more programs of a
executed, and provides a linkage between the logical
run unit and which itself may be referenced from any
concept of files and their records, and the physical
program in which it is described.
aspects of the devices on which files are stored.
* external data record. A logical record which is
environment-name. A name, specified by IBM, that
described in one or more programs of a run unit and
identifies system logical units, printer and card punch
whose constituent data items may be referenced from
control characters, report codes, and/or program
any program in which they are described.
switches. When an environment-name is associated
with a mnemonic-name in the ENVIRONMENT DIVI-
external decimal item. A format for representing
SION, the mnemonic-name may then be substituted in
numbers in which the digit is contained in bits 4 through
any format in which such substitution is valid.
7 and the sign is contained in bits 0 through 3 of the
rightmost byte. Bits 0 through 3 of all other bytes
environment variable. Any of a number of variables
contain 1’s (hex F). For example, the decimal value of
that describe the way an operating system is going to
+123 is represented as 1111 0001 1111 0010 1111
run and the devices it is going to recognize.
0011. (Also know as “zoned decimal item.”)
execution time. See “run time.”
* external file connector. A file connector which is
execution-time environment. See “run-time environ- accessible to one or more object programs in the run
ment.” unit.

| expanded date field. A date field containing an external floating-point item. A format for representing
| expanded (4-digit) year. See also “date field” and numbers in which a real number is represented by a pair
| “expanded year.” of distinct numerals. In a floating-point representation,
the real number is the product of the fixed-point part (the
| expanded year. Four digits representing a year, first numeral), and a value obtained by raising the
| including the century (for example, 1998). Appears in implicit floating-point base to a power denoted by the
| expanded date fields. Compare with “windowed year.” exponent (the second numeral).
For example, a floating-point representation of the
* explicit scope terminator. A reserved word that ter- number 0.0001234 is: 0.1234 -3, where 0.1234 is the
minates the scope of a particular Procedure Division mantissa and -3 is the exponent.
statement.

570 COBOL Set for AIX Programming Guide


external program. The outermost program. A program number of the current record for a relative file, or indi-
that is not nested. cates that no next logical record exists, or that an
optional input file is not present, or that the at end condi-
* external switch. A hardware or software device, tion already exists, or that no valid next record has been
defined and named by the implementor, which is used to established.
indicate that one of two alternate states exists.
* File Section. The section of the DATA DIVISION that
contains file description entries and sort-merge file
F description entries together with their associated record
descriptions.
* figurative constant. A compiler-generated value ref-
erenced through the use of certain reserved words. file system. The collection of files and file management
structures on a physical or logical mass storage device,
* file. A collection of logical records. such as a diskette or minidisk.

* file attribute conflict condition. An unsuccessful * fixed file attributes. Information about a file which is
attempt has been made to execute an input-output oper- established when a file is created and cannot subse-
ation on a file and the file attributes, as specified for that quently be changed during the existence of the file.
file in the program, do not match the fixed attributes for These attributes include the organization of the file
that file. (sequential, relative, or indexed), the prime record key,
the alternate record keys, the code set, the minimum
* file clause. A clause that appears as part of any of and maximum record size, the record type (fixed or vari-
the following DATA DIVISION entries: file description able), the collating sequence of the keys for indexed
entry (FD entry) and sort-merge file description entry files, the blocking factor, the padding character, and the
(SD entry). record delimiter.

* file connector. A storage area which contains infor- * fixed length record. A record associated with a file
mation about a file and is used as the linkage between a whose file description or sort-merge description entry
file-name and a physical file and between a file-name requires that all records contain the same number of
and its associated record area. character positions.

File-Control. The name of an ENVIRONMENT DIVI- fixed-point number. A numeric data item defined with
SION paragraph in which the data files for a given a PICTURE clause that specifies the location of an
source program are declared. optional sign, the number of digits it contains, and the
location of an optional decimal point. The format may
* file control entry. A SELECT clause and all its sub- be either binary, packed decimal, or external decimal.
ordinate clauses which declare the relevant physical
attributes of a file. floating-point number. A numeric data item containing
a fraction and an exponent. Its value is obtained by
* file description entry. An entry in the File Section of multiplying the fraction by the base of the numeric data
the DATA DIVISION that is composed of the level indi- item raised to the power specified by the exponent.
cator FD, followed by a file-name, and then followed by
a set of file clauses as required. * format. A specific arrangement of a set of data.

* file-name. A user-defined word that names a file con- * function. A temporary data item whose value is
nector described in a file description entry or a sort- determined at the time the function is referenced during
merge file description entry within the File Section of the the execution of a statement.
DATA DIVISION.
* function-identifier. A syntactically correct combina-
* file organization. The permanent logical file structure tion of character-strings and separators that references a
established at the time that a file is created. function. The data item represented by a function is
uniquely identified by a function-name with its argu-
*file position indicator. A conceptual entity that con- ments, if any. A function-identifier may include a
tains the value of the current key within the key of refer- reference-modifier. A function-identifier that references
ence for an indexed file, or the record number of the an alphanumeric function may be specified anywhere in
current record for a sequential file, or the relative record

Glossary 571
the general formats that an identifier may be specified, IGZCBSN. The COBOL/370 Release 1 bootstrap
subject to certain restrictions. A function-identifier that routine. It must be link-edited with any module that con-
references an integer or numeric function may be refer- tains a COBOL/370 Release 1 program.
enced anywhere in the general formats that an arith-
metic expression may be specified. IGZCBSO. The COBOL for MVS & VM Release 2 and
IBM COBOL for OS/390 & VM bootstrap routine. It must
function-name. A word that names the mechanism be link-edited with any module that contains a COBOL
whose invocation, along with required arguments, deter- for MVS & VM Release 2 or IBM COBOL for OS/390 &
mines the value of a function. VM program.

* imperative statement. A statement that either begins


G with an imperative verb and specifies an unconditional
action to be taken or is a conditional statement that is
* global name. A name which is declared in only one delimited by its explicit scope terminator (delimited scope
program but which may be referenced from that program statement). An imperative statement may consist of a
and from any program contained within that program. sequence of imperative statements.
Condition-names, data-names, file-names, record-
names, report-names, and some special registers may * implicit scope terminator. A separator period which
be global names. terminates the scope of any preceding unterminated
statement, or a phrase of a statement which by its
* group item. A data item that is composed of subordi- occurrence indicates the end of the scope of any state-
nate data items. ment contained within the preceding phrase.

* index. A computer storage area or register, the


H content of which represents the identification of a partic-
ular element in a table.
header label. (1) A file label or data set label that pre-
cedes the data records on a unit of recording media. (2) * index data item. A data item in which the values
Synonym for beginning-of-file label. associated with an index-name can be stored in a form
specified by the implementor.
* high order end. The leftmost character of a string of
characters. indexed data-name. An identifier that is composed of a
data-name, followed by one or more index-names
enclosed in parentheses.
I * indexed file. A file with indexed organization.
IBM COBOL extension. Certain COBOL syntax and
* indexed organization. The permanent logical file
semantics supported by IBM compilers in addition to
structure in which each record is identified by the value
those described in ANSI Standard.
of one or more keys within that record.
IDENTIFICATION DIVISION. One of the four main
indexing. Synonymous with subscripting using index-
component parts of a COBOL program, class definition,
names.
or method definition. The IDENTIFICATION DIVISION
identifies the program name, class name, or method
* index-name. A user-defined word that names an
name. The IDENTIFICATION DIVISION may include the
index associated with a specific table.
following documentation: author name, installation, or
date. * inheritance (for classes). A mechanism for using the
implementation of one or more classes as the basis for
* identifier. A syntactically correct combination of
another class. A sub-class inherits from one or more
character-strings and separators that names a data item.
super-classes. By definition the inheriting class con-
When referencing a data item that is not a function, an
forms to the inherited classes.
identifier consists of a data-name, together with its qual-
ifiers, subscripts, and reference-modifier, as required for * initial program. A program that is placed into an
uniqueness of reference. When referencing a data item initial state every time the program is called in a run unit.
which is a function, a function-identifier is used.

572 COBOL Set for AIX Programming Guide


* initial state. The state of a program when it is first returned value for any possible evaluation of the func-
called in a run unit. tion.

inline. In a program, instructions that are executed integer function. A function whose category is numeric
sequentially, without branching to routines, subroutines, and whose definition does not include any digit positions
or other programs. to the right of the decimal point.

* input file. A file that is opened in the INPUT mode. interface. The information that a client must know to
use a class—the names of its attributes and the signa-
* input mode. The state of a file after execution of an tures of its methods. With direct-to-SOM compilers such
OPEN statement, with the INPUT phrase specified, for as COBOL, the interface to a class may be defined by
that file and before the execution of a CLOSE statement, native language syntax for class definitions. Classes
without the REEL or UNIT phrase for that file. implemented in other languages might have their inter-
faces defined directly in SOM Interface Definition Lan-
* input-output file. A file that is opened in the I-O guage (IDL). The COBOL compiler has a compiler
mode. option, IDLGEN, to automatically generate IDL for a
COBOL class.
* INPUT-OUTPUT SECTION. The section of the ENVI-
RONMENT DIVISION that names the files and the Interface Definition Language (IDL). The formal lan-
external media required by an object program or method guage (independent of any programming language) by
and that provides information required for transmission which the interface for a class of objects is defined in a
and handling of data during execution of the object IDL file, which the SOM compiler then interprets to
program or method definition. create an implementation template file and binding files.
SOM's Interface Definition Language is fully compliant
* Input-Output statement. A statement that causes with standards established by the Object Management
files to be processed by performing operations upon indi- Group's Common Object Request Broker Architecture
vidual records or upon the file as a unit. The input- (CORBA).
output statements are: ACCEPT (with the identifier
phrase), CLOSE, DELETE, DISPLAY, OPEN, READ, interlanguage communication (ILC). The ability of
REWRITE, SET (with the TO ON or TO OFF phrase), routines written in different programming languages to
START, and WRITE. communicate. ILC support allows the application writer
to readily build applications from component routines
* input procedure. A set of statements, to which written in a variety of languages.
control is given during the execution of a SORT state-
ment, for the purpose of controlling the release of speci- intermediate result. An intermediate field containing
fied records to be sorted. the results of a succession of arithmetic operations.

instance data. Data defining the state of an object. * internal data. The data described in a program
The instance data introduced by a class is defined in the excluding all external data items and external file con-
WORKING-STORAGE SECTION of the DATA DIVISION nectors. Items described in the LINKAGE SECTION of
of the class definition. The state of an object also a program are treated as internal data.
includes the state of the instance variables introduced by
base classes that are inherited by the current class. A * internal data item. A data item which is described in
separate copy of the instance data is created for each one program in a run unit. An internal data item may
object instance. have a global name.

* integer. (1) A numeric literal that does not include internal decimal item. A format in which each byte in
any digit positions to the right of the decimal point. a field except the rightmost byte represents two numeric
(2) A numeric data item defined in the DATA DIVISION digits. The rightmost byte contains one digit and the
that does not include any digit positions to the right of sign. For example, the decimal value +123 is repres-
the decimal point. ented as 0001 0010 0011 1111. (Also known as packed
decimal.)
(3) A numeric function whose definition provides that all
digits to the right of the decimal point are zero in the * internal file connector. A file connector which is
accessible to only one object program in the run unit.

Glossary 573
* intra-record data structure. The entire collection of
groups and elementary data items from a logical record K
which is defined by a contiguous subset of the data
description entries which describe that record. These K. When referring to storage capacity, two to the tenth
data description entries include all entries whose level- power; 1024 in decimal notation.
number is greater than the level-number of the first data
description entry describing the intra-record data struc- * key. A data item that identifies the location of a
ture. record, or a set of data items which serve to identify the
ordering of data.
intrinsic function. A pre-defined function, such as a
commonly used arithmetic function, called by a built-in * key of reference. The key, either prime or alternate,
function reference. currently being used to access records within an indexed
file.
* invalid key condition. A condition, at object time,
caused when a specific value of the key associated with * key word. A reserved word or function-name whose
an indexed or relative file is determined to be invalid. presence is required when the format in which the word
appears is used in a source program.
* I-O-CONTROL. The name of an ENVIRONMENT
DIVISION paragraph in which object program require- kilobyte (KB). One kilobyte equals 1024 bytes.
ments for rerun points, sharing of same areas by several
data files, and multiple file storage on a single input-
output device are specified. L
* I-O-CONTROL entry. An entry in the I-O-CONTROL * language-name. A system-name that specifies a par-
paragraph of the ENVIRONMENT DIVISION which con- ticular programming language.
tains clauses that provide information required for the
transmission and handling of data on named files during Language Environment-conforming. A characteristic
the execution of a program. of compiler products (COBOL for OS/390 & VM, COBOL
for MVS & VM, COBOL/370, AD/Cycle C/370, C/C++ for
* I-O-Mode. The state of a file after execution of an MVS and VM, PL/I for MVS and VM) that produce object
OPEN statement, with the I-O phrase specified, for that code conforming to the Language Environment format.
file and before the execution of a CLOSE statement
without the REEL or UNIT phase for that file. last-used state. A program is in last-used state if its
internal values remain the same as when the program
* I-O status. A conceptual entity which contains the was exited (are not reset to their initial values).
two-character value indicating the resulting status of an
input-output operation. This value is made available to * letter. A character belonging to one of the following
the program through the use of the FILE STATUS two sets:
clause in the file control entry for the file. 1. Uppercase letters: A, B, C, D, E, F, G, H, I, J, K, L,
M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
| ISPF. Interactive System Productivity Facility. An IBM
| software product that provides a menu-driven interface 2. Lowercase letters: a, b, c, d, e, f, g, h, i, j, k, l, m, n,
| to the TSO or VM user. Includes library utilities, a pow- o, p, q, r, s, t, u, v, w, x, y, z
| erful editor, and dialog management.
* level indicator. Two alphabetic characters that iden-
iteration structure. A program processing logic in tify a specific type of file or a position in a hierarchy.
which a series of statements is repeated while a condi- The level indicators in the DATA DIVISION are: CD, FD,
tion is true or until a condition is true. and SD.

* level-number. A user-defined word, expressed as a


two digit number, which indicates the hierarchical posi-
tion of a data item or the special properties of a data
description entry. Level-numbers in the range from 1
through 49 indicate the position of a data item in the
hierarchical structure of a logical record. Level-numbers

574 COBOL Set for AIX Programming Guide


in the range 1 through 9 may be written either as a * low order end. The rightmost character of a string of
single digit or as a zero followed by a significant digit. characters.
Level-numbers 66, 77 and 88 identify special properties
of a data description entry.
M
* library-name. A user-defined word that names a
COBOL library that is to be used by the compiler for a main program. In a hierarchy of programs and subrou-
given source program compilation. tines, the first program to receive control when the pro-
grams are run.
* library text. A sequence of text words, comment
lines, the separator space, or the separator pseudo-text * mass storage. A storage medium in which data may
delimiter in a COBOL library. be organized and maintained in both a sequential and
nonsequential manner.
LILIAN DATE. The number of days since the beginning
of the Gregorian calendar. Day one is Friday, October * mass storage device. A device having a large
15, 1582. The Lilian date format is named in honor of storage capacity; for example, magnetic disk, magnetic
Luigi Lilio, the creator of the Gregorian calendar. drum.

* LINAGE-COUNTER. A special register whose value * mass storage file. A collection of records that is
points to the current position within the page body. assigned to a mass storage medium.

LINKAGE SECTION. The section in the DATA DIVI- * megabyte (M). One megabyte equals 1,048,576
SION of the called program that describes data items bytes.
available from the calling program. These data items
may be referred to by both the calling and called * merge file. A collection of records to be merged by a
program. MERGE statement. The merge file is created and can
be used only by the merge function.
literal. A character-string whose value is specified
either by the ordered set of characters comprising the metaclass. A SOM class whose instances are SOM
string, or by the use of a figurative constant. class-objects. The methods defined in metaclasses are
executed without requiring any object instances of the
little-endian. Default format used by the PC to store class to exist, and are frequently used to create
binary data. In this format, the most significant digit is instances of the class.
on the highest address. Compare with “big-endian.”
method. Procedural code that defines one of the oper-
locale. A set of attributes for a program execution envi- ations supported by an object, and that is executed by
ronment indicating culturally sensitive considerations, an INVOKE statement on that object.
such as: character code page, collating sequence,
date/time format, monetary value representation, * Method Definition. The COBOL source unit that
numeric value representation, or language. defines a method.

* LOCAL-STORAGE SECTION. The section of the * method identification entry. An entry in the
DATA DIVISION that defines storage that is allocated METHOD-ID paragraph of the IDENTIFICATION DIVI-
and freed on a per-invocation basis, depending on the SION which contains clauses that specify the method-
value assigned in their VALUE clauses. name and assign selected attributes to the method
definition.
* logical operator. One of the reserved words AND,
OR, or NOT. In the formation of a condition, either * method-name. A user-defined word that identifies a
AND, or OR, or both can be used as logical connectives. method.
NOT can be used for logical negation.
* mnemonic-name. A user-defined word that is associ-
* logical record. The most inclusive data item. The ated in the ENVIRONMENT DIVISION with a specified
level-number for a record is 01. A record may be either implementor-name.
an elementary item or a group of items. The term is
synonymous with record. | MLE. See “millennium language extensions.”

Glossary 575
| millennium language extensions. IBM extension to | non-date. Any of the following:
| COBOL, enabling compiler-assisted date processing for
| Ÿ A data item whose data description entry does not
| dates containing 2-digit and 4-digit years. Language ele-
| include the DATE FORMAT clause
| ments in support of the millennium language extensions
| are: | Ÿ A literal
| Ÿ DATE FORMAT clause in data description entries | Ÿ A reference-modified date field
| Ÿ Intrinsic functions: | Ÿ The result of certain arithmetic operations that may
| include date field operands; for example, the differ-
| DATEVAL
| ence between two compatible dates.
| UNDATE
| YEARWINDOW | The value of a non-date may or may not represent a
| date.
multitasking. Mode of operation that provides for the
concurrent, or interleaved, execution of two or more * non-numeric item. A data item whose description
tasks. When running under the Language Environment permits its content to be composed of any combination
product, multitasking is synonymous with multithreading. of characters taken from the computer’s character set.
Certain categories of non-numeric items may be formed
from more restricted character sets.
N * non-numeric literal. A literal bounded by quotation
name. A word composed of not more than 30 charac- marks. The string of characters may include any char-
ters that defines a COBOL operand. acter in the computer’s character set.

* native character set. The implementor-defined char- null. Figurative constant used to assign the value of an
acter set associated with the computer specified in the invalid address to pointer data items. NULLS can be
OBJECT-COMPUTER paragraph. used wherever NULL can be used.

* native collating sequence. The implementor-defined * numeric character. A character that belongs to the
collating sequence associated with the computer speci- following set of digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
fied in the OBJECT-COMPUTER paragraph.
numeric-edited item. A numeric item that is in such a
* negated combined condition. The ‘NOT’ logical form that it may be used in printed output. It may
operator immediately followed by a parenthesized com- consist of external decimal digits from 0 through 9, the
bined condition. decimal point, commas, the dollar sign, editing sign
control symbols, plus other editing symbols.
* negated simple condition. The ‘NOT’ logical oper-
ator immediately followed by a simple condition. * numeric function. A function whose class and cate-
gory are numeric but which for some possible evaluation
nested program. A program that is directly contained does not satisfy the requirements of integer functions.
within another program.
* numeric item. A data item whose description restricts
* next executable sentence. The next sentence to its content to a value represented by characters chosen
which control will be transferred after execution of the from the digits from ‘0’ through ‘9’; if signed, the item
current statement is complete. may also contain a ‘+’, ‘-’, or other representation of an
operational sign.
* next executable statement. The next statement to
which control will be transferred after execution of the * numeric literal. A literal composed of one or more
current statement is complete. numeric characters that may contain either a decimal
point, or an algebraic sign, or both. The decimal point
* next record. The record that logically follows the must not be the rightmost character. The algebraic sign,
current record of a file. if present, must be the leftmost character.

* noncontiguous items. Elementary data items in the


WORKING-STORAGE and LINKAGE SECTIONs that
bear no hierarchic relationship to other data items.

576 COBOL Set for AIX Programming Guide


WORKING-STORAGE SECTION
O ð1 TABLE-1.
ð5 X PICS9.
object. An entity that has state (its data values) and ð5 Y OCCURS 3 TIMES
operations (its methods). An object is a way to DEPENDING ON X PIC X.
encapsulate state and behavior. X is the object of the OCCURS DEPENDING ON clause
(ODO object). The value of the ODO object determines
object code. Output from a compiler or assembler that
how many of the ODO subject appear in the table.
is itself executable machine code or is suitable for proc-
essing to produce executable machine code. ODO subject. In the example above, Y is the subject of
the OCCURS DEPENDING ON clause (ODO subject).
* OBJECT-COMPUTER. The name of an ENVIRON-
The number of Y ODO subjects that appear in the table
MENT DIVISION paragraph in which the computer envi-
depends on the value of X.
ronment, within which the object program is executed, is
described. * open mode. The state of a file after execution of an
OPEN statement for that file and before the execution of
* object computer entry. An entry in the
a CLOSE statement without the REEL or UNIT phrase
OBJECT-COMPUTER paragraph of the ENVIRONMENT
for that file. The particular open mode is specified in the
DIVISION which contains clauses that describe the com-
OPEN statement as either INPUT, OUTPUT, I-O or
puter environment in which the object program is to be
EXTEND.
executed.
* operand. Whereas the general definition of operand
object deck. A portion of an object program suitable as
is “that component which is operated upon,” for the pur-
input to a linkage editor. Synonymous with object
poses of this document, any lowercase word (or words)
module and text deck.
that appears in a statement or entry format may be con-
sidered to be an operand and, as such, is an implied ref-
object module. Synonym for object deck or text deck.
erence to the data indicated by the operand.
* object of entry. A set of operands and reserved
* operational sign. An algebraic sign, associated with
words, within a DATA DIVISION entry of a COBOL
a numeric data item or a numeric literal, to indicate
program, that immediately follows the subject of the
whether its value is positive or negative.
entry.
* optional file. A file which is declared as being not
* object program. A set or group of executable
necessarily present each time the object program is exe-
machine language instructions and other material
cuted. The object program causes an interrogation for
designed to interact with data to provide problem sol-
the presence or absence of the file.
utions. In this context, an object program is generally
the machine language result of the operation of a
* optional word. A reserved word that is included in a
COBOL compiler on a source program. Where there is
specific format only to improve the readability of the lan-
no danger of ambiguity, the word ‘program’ alone may
guage and whose presence is optional to the user when
be used in place of the phrase ‘object program.’
the format in which the word appears is used in a source
program.
* object time. The time at which an object program is
executed. The term is synonymous with execution time.
OS/2 (Operating System/2*). A multi-tasking operating
system for the IBM Personal Computer family that allows
* obsolete element. A COBOL language element in
you to run both DOS mode and OS/2 mode programs.
Standard COBOL that is to be deleted from the next
revision of Standard COBOL.
* output file. A file that is opened in either the
OUTPUT mode or EXTEND mode.
ODBC. Open Database Connectivity that provides you
access to data from a variety of databases and file
* output mode. The state of a file after execution of an
systems.
OPEN statement, with the OUTPUT or EXTEND phrase
specified, for that file and before the execution of a
ODO object. In the example below,
CLOSE statement without the REEL or UNIT phrase for
that file.

Glossary 577
* output procedure. A set of statements to which * paragraph-name. A user-defined word that identifies
control is given during execution of a SORT statement and begins a paragraph in the Procedure Division.
after the sort function is completed, or during execution
of a MERGE statement after the merge function reaches parameter. Parameters are used to pass data values
a point at which it can select the next record in merged between calling and called programs.
order when requested.
password. A unique string of characters that a
overflow condition. A condition that occurs when a program, computer operator, or user must supply to
portion of the result of an operation exceeds the capacity meet security requirements before gaining access to
of the intended unit of storage. data.

* phrase. A phrase is an ordered set of one or more


P consecutive COBOL character-strings that form a portion
of a COBOL procedural statement or of a COBOL
packed decimal item. See “internal decimal item.” clause.

* padding character. An alphanumeric character used * physical record. See “block.”


to fill the unused character positions in a physical record.
pointer data item. A data item in which address values
page. A vertical division of output data representing a can be stored. Data items are explicitly defined as
physical separation of such data, the separation being pointers with the USAGE IS POINTER clause.
based on internal logical requirements and/or external ADDRESS OF special registers are implicitly defined as
characteristics of the output medium. pointer data items. Pointer data items can be compared
for equality or moved to other pointer data items.
* page body. That part of the logical page in which
lines can be written and/or spaced. portability. The ability to transfer an application
program from one application platform to another with
* paragraph. In the Procedure Division, a paragraph- relatively few changes to the source program.
name followed by a separator period and by zero, one,
or more sentences. In the IDENTIFICATION and ENVI- preloaded. In COBOL this refers to COBOL programs
RONMENT DIVISIONs, a paragraph header followed by that remain resident in storage under IMS instead of
zero, one, or more entries. being loaded each time they are called.

* paragraph header. A reserved word, followed by the * prime record key. A key whose contents uniquely
separator period, that indicates the beginning of a para- identify a record within an indexed file.
graph in the IDENTIFICATION and ENVIRONMENT
DIVISIONs. The permissible paragraph headers in the * priority-number. A user-defined word which classifies
IDENTIFICATION DIVISION are: sections in the Procedure Division for purposes of seg-
mentation. Segment-numbers may contain only the
PROGRAM-ID. (Program IDENTIFICATION DIVISION) characters '0','1', ... , '9'. A segment-number may be
CLASS-ID. (Class IDENTIFICATION DIVISION) expressed either as a one- or two-digit number.
METHOD-ID. (Method IDENTIFICATION DIVISION)
AUTHOR.
* procedure. A paragraph or group of logically succes-
INSTALLATION.
sive paragraphs, or a section or group of logically suc-
DATE-WRITTEN.
DATE-COMPILED. cessive sections, within the Procedure Division.
SECURITY.
* procedure branching statement. A statement that
The permissible paragraph headers in the ENVIRON- causes the explicit transfer of control to a statement
MENT DIVISION are: other than the next executable statement in the
SOURCE-COMPUTER. sequence in which the statements are written in the
OBJECT-COMPUTER. source program. The procedure branching statements
SPECIAL-NAMES. are: ALTER, CALL, EXIT, EXIT PROGRAM, GO TO,
REPOSITORY. (Program or Class CONFIGURATION SECTION) MERGE, (with the OUTPUT PROCEDURE phrase),
FILE-CONTROL. PERFORM and SORT (with the INPUT PROCEDURE or
I-O-CONTROL. OUTPUT PROCEDURE phrase).

578 COBOL Set for AIX Programming Guide


Procedure Division. One of the four main component ( left parenthesis
parts of a COBOL program, class definition, or method ) right parenthesis
definition. The Procedure Division contains instructions ␣ space
for solving a problem. The Program and Method Proce- = equal sign
dure Divisions may contain imperative statements, condi-
tional statements, compiler directing statements,
paragraphs, procedures, and sections. The Class Pro- Q
cedure Division contains only method definitions.
QSAM (Queued Sequential Access Method). An
procedure integration. One of the functions of the extended version of the basic sequential access method
COBOL optimizer is to simplify calls to performed proce- (BSAM). When this method is used, a queue is formed
dures or contained programs. of input data blocks that are awaiting processing or of
PERFORM procedure integration is the process whereby output data blocks that have been processed and are
a PERFORM statement is replaced by its performed pro- awaiting transfer to auxiliary storage or to an output
cedures. Contained program procedure integration is device.
the process where a CALL to a contained program is
* qualified data-name. An identifier that is composed
replaced by the program code.
of a data-name followed by one or more sets of either of
* procedure-name. A user-defined word that is used to the connectives OF and IN followed by a data-name
name a paragraph or section in the Procedure Division. qualifier.
It consists of a paragraph-name (which may be qualified)
* qualifier.
or a section-name.
1. A data-name or a name associated with a level indi-
procedure-pointer data item. A data item in which a cator which is used in a reference either together
pointer to an entry point can be stored. A data item with another data-name which is the name of an
defined with the USAGE IS PROCEDURE-POINTER item that is subordinate to the qualifier or together
clause contains the address of a procedure entry point. with a condition-name.

* program identification entry. An entry in the 2. A section-name that is used in a reference together
PROGRAM-ID paragraph of the IDENTIFICATION DIVI- with a paragraph-name specified in that section.
SION which contains clauses that specify the program- 3. A library-name that is used in a reference together
name and assign selected program attributes to the with a text-name associated with that library.
program.

* program-name. In the IDENTIFICATION DIVISION


and the end program header, a user-defined word that
R
identifies a COBOL source program. * random access. An access mode in which the
program-specified value of a key data item identifies the
* pseudo-text. A sequence of text words, comment logical record that is obtained from, deleted from, or
lines, or the separator space in a source program or placed into a relative or indexed file.
COBOL library bounded by, but not including, pseudo-
text delimiters. * record. See “logical record.”

* pseudo-text delimiter. Two contiguous equal sign * record area. A storage area allocated for the purpose
characters (==) used to delimit pseudo-text. of processing the record described in a record
description entry in the File Section of the DATA DIVI-
* punctuation character. A character that belongs to SION. In the File Section, the current number of char-
the following set: acter positions in the record area is determined by the
Character Meaning explicit or implicit RECORD clause.
, comma
; semicolon * record description. See “record description entry.”
: colon
. period (full stop) * record description entry. The total set of data
" quotation mark description entries associated with a particular record.
The term is synonymous with record description.

Glossary 579
recording mode. The format of the logical records in a Operator Meaning
file. Recording mode can be F (fixed-length), V IS GREATER THAN Greater than
(variable-length), S (spanned), or U (undefined). IS > Greater than
IS NOT GREATER THAN Not greater than
record key. A key whose contents identify a record IS NOT > Not greater than
within an indexed file.
IS LESS THAN Less than
* record-name. A user-defined word that names a IS < Less than
record described in a record description entry in the IS NOT LESS THAN Not less than
DATA DIVISION of a COBOL program. IS NOT < Not less than

* record number. The ordinal number of a record in IS EQUAL TO Equal to


the file whose organization is sequential. IS = Equal to
IS NOT EQUAL TO Not equal to
recursion. A program calling itself or being directly or
IS NOT = Not equal to
indirectly called by a one of its called programs.
IS GREATER THAN OR EQUAL TO
recursively capable. A program is recursively capable
Greater than or equal to
(can be called recursively) if the RECURSIVE attribute is
IS >= Greater than or equal to
on the PROGRAM-ID statement.
IS LESS THAN OR EQUAL TO
reel. A discrete portion of a storage medium, the
Less than or equal to
dimensions of which are determined by each
IS <= Less than or equal to
implementor that contains part of a file, all of a file, or
any number of files. The term is synonymous with unit
* relation character. A character that belongs to the
and volume.
following set:
reentrant. The attribute of a program or routine that Character Meaning
allows more than one user to share a single copy of a
load module. > greater than
< less than
* reference format. A format that provides a standard = equal to
method for describing COBOL source programs.
* relation condition. The proposition, for which a truth
reference modification. A method of defining a new value can be determined, that the value of an arithmetic
alphanumeric data item by specifying the leftmost char- expression, data item, non-numeric literal, or index-name
acter and length relative to the leftmost character of has a specific relationship to the value of another arith-
another alphanumeric data item. metic expression, data item, non-numeric literal, or index
name. (See also “relational operator.”)
* reference-modifier. A syntactically correct combina-
tion of character-strings and separators that defines a * relative file. A file with relative organization.
unique data item. It includes a delimiting left parenthesis
separator, the leftmost character position, a colon sepa- * relative key. A key whose contents identify a logical
rator, optionally a length, and a delimiting right paren- record in a relative file.
thesis separator.
* relative organization. The permanent logical file
* relation. See “relational operator” or “relation condi- structure in which each record is uniquely identified by
tion.” an integer value greater than zero, which specifies the
record’s logical ordinal position in the file.
* relational operator. A reserved word, a relation char-
acter, a group of consecutive reserved words, or a group * relative record number. The ordinal number of a
of consecutive reserved words and relation characters record in a file whose organization is relative. This
used in the construction of a relation condition. The per- number is treated as a numeric literal which is an
missible operators and their meanings are: integer.

580 COBOL Set for AIX Programming Guide


* reserved word. A COBOL word specified in the list of by a separator period. The permissible section headers
words that may be used in a COBOL source program, in the ENVIRONMENT DIVISION are:
but that must not appear in the program as user-defined CONFIGURATION SECTION.
words or system-names. INPUT-OUTPUT SECTION.
* resource. A facility or service, controlled by the oper- The permissible section headers in the DATA DIVISION
ating system, that can be used by an executing program. are:
FILE SECTION.
* resultant identifier. A user-defined data item that is WORKING-STORAGE SECTION.
to contain the result of an arithmetic operation. LOCAL-STORAGE SECTION.
LINKAGE SECTION.
reusable environment. A reusable environment is
when you establish an assembler program as the main In the Procedure Division, a section header is composed
program by using either ILBOSTP0 programs, IGZERRE of a section-name, followed by the reserved word
programs, or the RTEREUS run-time option. SECTION, followed by a separator period.

routine. A set of statements in a COBOL program that * section-name. A user-defined word that names a
causes the computer to perform an operation or series section in the Procedure Division.
of related operations. In Language Environment, refers
selection structure. A program processing logic in
to either a procedure, function, or subroutine.
which one or another series of statements is executed,
* routine-name. A user-defined word that identifies a depending on whether a condition is true or false.
procedure written in a language other than COBOL.
* sentence. A sequence of one or more statements,
* run time. The time at which an object program is the last of which is terminated by a separator period.
executed. The term is synonymous with object time.
* separately compiled program. A program which,
run-time environment. The environment in which a together with its contained programs, is compiled sepa-
COBOL program executes. rately from all other programs.

* run unit. A stand-alone object program, or several * separator. A character or two contiguous characters
object programs, that interact via COBOL CALL state- used to delimit character-strings.
ments, which function at run time as an entity.
* separator comma. A comma (,) followed by a space
used to delimit character-strings.
S * separator period. A period (.) followed by a space
used to delimit character-strings.
SBCS (Single Byte Character Set). See “Single Byte
Character Set (SBCS).” * separator semicolon. A semicolon (;) followed by a
space used to delimit character-strings.
scope terminator. A COBOL reserved word that marks
the end of certain Procedure Division statements. It may sequence structure. A program processing logic in
be either explicit (END-ADD, for example) or implicit which a series of statements is executed in sequential
(separator period). order.
* section. A set of zero, one or more paragraphs or * sequential access. An access mode in which logical
entities, called a section body, the first of which is pre- records are obtained from or placed into a file in a con-
ceded by a section header. Each section consists of the secutive predecessor-to-successor logical record
section header and the related section body. sequence determined by the order of records in the file.
* section header. A combination of words followed by * sequential file. A file with sequential organization.
a separator period that indicates the beginning of a
section in the Environment, Data, and Procedure Divi- * sequential organization. The permanent logical file
sions. In the ENVIRONMENT and DATA DIVISIONs, a structure in which a record is identified by a
section header is composed of reserved words followed

Glossary 581
predecessor-successor relationship established when the * source computer entry. An entry in the
record is placed into the file. SOURCE-COMPUTER paragraph of the ENVIRON-
MENT DIVISION which contains clauses that describe
serial search. A search in which the members of a set the computer environment in which the source program
are consecutively examined, beginning with the first is to be compiled.
member and ending with the last.
* source item. An identifier designated by a SOURCE
* 77-level-description-entry. A data description entry clause that provides the value of a printable item.
that describes a noncontiguous data item with the level-
number 77. source program. Although it is recognized that a
source program may be represented by other forms and
* sign condition. The proposition, for which a truth symbols, in this document it always refers to a syntac-
value can be determined, that the algebraic value of a tically correct set of COBOL statements. A COBOL
data item or an arithmetic expression is either less than, source program commences with the IDENTIFICATION
greater than, or equal to zero. DIVISION or a COPY statement. A COBOL source
program is terminated by the end program header, if
* simple condition. Any single condition chosen from specified, or by the absence of additional source
the set: program lines.
Relation condition
Class condition * special character. A character that belongs to the
Condition-name condition following set:
Switch-status condition Character Meaning
Sign condition
+ plus sign
Single Byte Character Set (SBCS). A set of charac- - minus sign (hyphen)
ters in which each character is represented by a single * asterisk
byte. See also "EBCDIC (Extended Binary-Coded / slant (virgule, slash)
Decimal Interchange Code)." = equal sign
$ currency sign
slack bytes. Bytes inserted between data items or , comma (decimal point)
records to ensure correct alignment of some numeric ; semicolon
items. Slack bytes contain no meaningful data. In some . period (decimal point, full stop)
cases, they are inserted by the compiler; in others, it is " quotation mark
the responsibility of the programmer to insert them. The ( left parenthesis
SYNCHRONIZED clause instructs the compiler to insert ) right parenthesis
slack bytes when they are needed for proper alignment. > greater than symbol
Slack bytes between records are inserted by the pro- < less than symbol
grammer. : colon

SOM. See “System Object Model” * special-character word. A reserved word that is an
arithmetic operator or a relation character.
* sort file. A collection of records to be sorted by a
SORT statement. The sort file is created and can be SPECIAL-NAMES. The name of an ENVIRONMENT
used by the sort function only. DIVISION paragraph in which environment-names are
related to user-specified mnemonic-names.
* sort-merge file description entry. An entry in the
File Section of the DATA DIVISION that is composed of * special names entry. An entry in the
the level indicator SD, followed by a file-name, and then SPECIAL-NAMES paragraph of the ENVIRONMENT
followed by a set of file clauses as required. DIVISION which provides means for specifying the cur-
rency sign; choosing the decimal point; specifying sym-
* SOURCE-COMPUTER. The name of an ENVIRON-
bolic characters; relating implementor-names to
MENT DIVISION paragraph in which the computer envi-
user-specified mnemonic-names; relating alphabet-
ronment, within which the source program is compiled, is
names to character sets or collating sequences; and
described.
relating class-names to sets of characters.

582 COBOL Set for AIX Programming Guide


* special registers. Certain compiler generated storage * subscripted data-name. An identifier that is com-
areas whose primary use is to store information posed of a data-name followed by one or more sub-
produced in conjunction with the use of a specific scripts enclosed in parentheses.
COBOL feature.
* super-class. A class that is inherited by another
* standard data format. The concept used in class. See also sub-class.
describing the characteristics of data in a COBOL DATA
DIVISION under which the characteristics or properties switch-status condition. The proposition, for which a
of the data are expressed in a form oriented to the truth value can be determined, that an UPSI switch,
appearance of the data on a printed page of infinite capable of being set to an ‘on’ or ‘off’ status, has been
length and breadth, rather than a form oriented to the set to a specific status.
manner in which the data is stored internally in the com-
puter, or on a particular external medium. * symbolic-character. A user-defined word that speci-
fies a user-defined figurative constant.
* statement. A syntactically valid combination of words,
literals, and separators, beginning with a verb, written in syntax. (1) The relationship among characters or
a COBOL source program. groups of characters, independent of their meanings or
the manner of their interpretation and use. (2) The
STL. Standard Language file system: native workstation structure of expressions in a language. (3) The rules
and PC file system for COBOL and PL/I. Supports governing the structure of a language. (4) The relation-
sequential, relative, and indexed files, including the full ship among symbols. (5) The rules for the construction
ANSI 85 COBOL standard I/O language and all of the of a statement.
extensions described in IBM COBOL Language Refer-
ence, unless exceptions are explicitly noted. * system-name. A COBOL word that is used to com-
municate with the operating environment.
structured programming. A technique for organizing
and coding a computer program in which the program System Object Model (SOM). IBM's object-oriented
comprises a hierarchy of segments, each segment programming technology for building, packaging, and
having a single entry point and a single exit point. manipulating class libraries. SOM conforms to the
Control is passed downward through the structure Object Management Group's (OMG) Common Object
without unconditional branches to higher levels of the Request Broker Architecture (CORBA) standards.
hierarchy.

* sub-class. A class that inherits from another class. T


When two classes in an inheritance relationship are con-
sidered together, the sub-class is the inheritor or inher- * table. A set of logically consecutive items of data that
iting class; the super-class is the inheritee or inherited are defined in the DATA DIVISION by means of the
class. OCCURS clause.

* subject of entry. An operand or reserved word that * table element. A data item that belongs to the set of
appears immediately following the level indicator or the repeated items comprising a table.
level-number in a DATA DIVISION entry.
text deck. Synonym for object deck or object module.
* subprogram. See “called program.”
* text-name. A user-defined word that identifies library
* subscript. An occurrence number represented by text.
either an integer, a data-name optionally followed by an
integer with the operator + or -, or an index-name * text word. A character or a sequence of contiguous
optionally followed by an integer with the operator + or -, characters between margin A and margin R in a COBOL
that identifies a particular element in a table. A subscript library, source program, or in pseudo-text which is:
may be the word ALL when the subscripted identifier is Ÿ A separator, except for: space; a pseudo-text delim-
used as a function argument for a function allowing a iter; and the opening and closing delimiters for non-
variable number of arguments. numeric literals. The right parenthesis and left
parenthesis characters, regardless of context within

Glossary 583
the library, source program, or pseudo-text, are * user-defined word. A COBOL word that must be
always considered text words. supplied by the user to satisfy the format of a clause or
statement.
Ÿ A literal including, in the case of non-numeric
literals, the opening quotation mark and the closing
quotation mark that bound the literal.
V
Ÿ Any other sequence of contiguous COBOL charac-
ters except comment lines and the word ‘COPY’ * variable. A data item whose value may be changed
bounded by separators that are neither a separator by execution of the object program. A variable used in
nor a literal. an arithmetic expression must be a numeric elementary
item.
top-down design. The design of a computer program
using a hierarchic structure in which related functions * variable length record. A record associated with a
are performed at each level of the structure. file whose file description or sort-merge description entry
permits records to contain a varying number of character
top-down development. See “structured positions.
programming.”
* variable occurrence data item. A variable occur-
trailer-label. (1) A file or data set label that follows the rence data item is a table element which is repeated a
data records on a unit of recording medium. (2) variable number of times. Such an item must contain an
Synonym for end-of-file label. OCCURS DEPENDING ON clause in its data description
entry, or be subordinate to such an item.
* truth value. The representation of the result of the
evaluation of a condition in terms of one of two values: * variably located group.. A group item following, and
true or false. not subordinate to, a variable-length table in the same
level-01 record.

U * variably located item.. A data item following, and not


subordinate to, a variable-length table in the same
* unary operator. A plus (+) or a minus (-) sign, that level-01 record.
precedes a variable or a left parenthesis in an arithmetic
expression and that has the effect of multiplying the * verb. A word that expresses an action to be taken by
expression by +1 or -1, respectively. a COBOL compiler or object program.

unit. A module of direct access, the dimensions of VM/SP (Virtual Machine/System Product). An
which are determined by IBM. IBM-licensed program that manages the resources of a
single computer so that multiple computing systems
universal object reference. A data-name that can appear to exist. Each virtual machine is the functional
refer to an object of any class. equivalent of a “real” machine.

* unsuccessful execution. The attempted execution of volume. A module of external storage. For tape
a statement that does not result in the execution of all devices it is a reel; for direct-access devices it is a unit.
the operations specified by that statement. The unsuc-
cessful execution of a statement does not affect any volume switch procedures. System specific proce-
data referenced by that statement, but may affect status dures executed automatically when the end of a unit or
indicators. reel has been reached before end-of-file has been
reached.
UPSI switch. A program switch that performs the func-
tions of a hardware switch. Eight are provided: UPSI-0 VSAM/6000. A file system that supports COBOL
through UPSI-7. sequential, relative, and indexed organizations. This file
system is available as part of IBM COBOL Set for AIX.

584 COBOL Set for AIX Programming Guide


* word. A character-string of not more than 30 charac-
W ters which forms a user-defined word, a system-name, a
reserved word, or a function-name.
| windowed date field. A date field containing a win-
| dowed (2-digit) year. See also “date field” and “win- * WORKING-STORAGE SECTION. The section of the
| dowed year.” DATA DIVISION that describes working storage data
items, composed either of noncontiguous items or
| windowed year. Two digits representing a year within working storage records or of both.
| a century window (for example, 98). Appears in win-
| dowed date fields. See also “century window.”
| Compare with “expanded year.” Z
zoned decimal item. See “external decimal item.”

Glossary 585
Index
adding records
Special Characters to files 103
-c cob2 option 136 ADDRESS special register, CALL statement 336
-cmain cob2 option 136 addresses
-comprc_ok cob2 option 136 incrementing 343
-F cob2 option 136 NULL value 342
-g cob2 option 136 passing between programs 341
-host cob2 option passing entry point addresses 344
-I cob2 option 137 ADEXIT suboption of EXIT compiler option 158, 161
-main cob2 option 137 AIX profiling, setting up object file 137
-o cob2 option 137 ALL subscript 40, 62
-p cob2 option 137 ALPHABET clause, establishing collating sequence 14
-pg cob2 option 137 alternate collating sequence 15, 109
-q cob2 command 138 alternate file system
-v cob2 option 138 file system ID 130
.c files 135 using environment variables 130
.adt file 149 alternate reserved word table, CICS 359
.wlist file 168 alternate reserved-word table 184
*CBL statement 187 ANALYZE compiler option 149
*CONTROL statement 187 ANNUITY intrinsic function 42
>>CALLINT statement 187 APOST compiler option 173
applications, porting
AIX to mainframe
Numerics AIX-only language features 321
2-digit years AIX-only names 321
querying within 100-year range (CEEQCEN) 516 AIX to OS/2 322
example 517 architectural differences between platforms 316
setting within 100-year range (CEESCEN) 518 language differences between AIX and
example 519 mainframe 316
valid values for 426 mainframe to AIX
3-digit years 426 choosing compiler options 316
4-digit years 426 running mainframe applications under AIX 317
using COPY to isolate platform-specific code 317
argument
A describing in calling program 337
abbreviated run-time messages 145 arguments
abbreviations, compiler options 147 IDL passing conventions 287
abends passing between C/C++ and COBOL 330
using ERRCOUNT run-time option to induce 194 passing between COBOL and C/C++ 332, 334
ACCEPT statement 7 passing BY VALUE 332
ACCEPT statement, defining environment to main program 351
variables 133 arithmetic
accessing local files 98 calculation on dates
using environment variables 130 convert date to COBOL Integer format
accessing remote files 98 (CEECBLDY) 484
ADATA compiler option 149 convert date to Lilian format (CEEDAYS) 498
convert timestamp to number of seconds
(CEESECS) 525

586  Copyright IBM Corp. 1996, 1998


arithmetic (continued) binary data item (continued)
calculation on dates (continued) intermediate results 475
get current Greenwich Mean Time using efficiently 32
(CEEGMT) 505 binary search of a table 61
COMPUTE statement simpler to code 38 Bourne shell, impact on examples 128
error handling 117 BY VALUE, valid data types 332
with intrinsic functions 39
arithmetic comparisons 44
arithmetic evaluation C
data format conversion 35 C shell, impact on examples 128
examples 43, 45 C/C++
fixed-point versus floating-point 43 and COBOL 328
intermediate results 471 communicating with COBOL 328
precision 471 data types, correspondence with COBOL 329
arithmetic expression functions called from COBOL, example 330
as reference modifier 81 functions calling COBOL, example 332, 334
description of 39 multiple calls to a COBOL program 334
in non-arithmetic statement 478 call conventions 157
in parentheses 39 CALL identifier 392
arithmetic expressions call interface conventions
with MLE 455 with ODBC 371
arithmetic operations CALL statement
with MLE 464 . . . USING 337
ASCII BY CONTENT 336
DBCS portability 319 BY REFERENCE 336
portability considerations 318 BY VALUE 336
assembler language CALL identifier 328
LIST option 432 CALL literal 328
listing 432 effect of CALLINT option 150
assembler language programs effect of DYNAM compiler option 156
debugging 220 environment variable requirements 131
listing of 168 exception condition 126
assigning values 4 for error handling 126
assignment-name, specifying 130 handling of programs name in 172
assumed century window for non-dates 464 overflow condition 126
AT END (end-of-file) 120 to invoke date and time services 423
with ON EXCEPTION 126
with ON OVERFLOW 24, 126
B CALL statement behaviour 147
base locator 213 callable services
BASIS statement 187 CEECBLDY—convert date to COBOL Integer
Batch compilation 174 format 484
batch debugging, activating 193 CEEDATE—convert Lilian date to character
BINARY format 488
general description 32 CEEDATM—convert seconds to character
synonyms 30 timestamp 493
using efficiently 32 CEEDAYS—convert date to Lilian format 498
BINARY compiler option 150 CEEDYWK—calculate day of week from Lilian
binary data item date 502
general description 32 CEEGMT—get current Greenwich Mean Time 505

Index 587
callable services (continued) CEEGMT—get current Greenwich Mean Time
CEEGMTO—get offset from Greenwich Mean Time example 507
to local time 508 syntax 505
CEEISEC—convert integers to seconds 510 CEEGMTO—get offset from Greenwich Mean Time to
CEELOCT—get current local time 514 local time
CEEQCEN—query the century window 516 example 509
CEESCEN—set the century window 518 syntax 508
CEESECI—convert seconds to integers 521 CEEISEC—convert integers to seconds
CEESECS—convert timestamp to number of example 512
seconds 525 syntax 510
CEEUTC—get Coordinated Universal Time 530 CEELOCT—get current local time
date processing 438, 441 example 515
IGZEDT4—get current date with 4-digit year 530 syntax 514
CALLINT compiler option 150 CEEQCEN—query the century window
CALLINT statement 187 example 517
calls syntax 517
between COBOL programs 324 CEESCEN—set the century window
dynamic 327 example 519
exception condition 126 syntax 518
Linkage Section 338 CEESECI—convert seconds to integers
overflow condition 126 example 522
passing arguments 337 syntax 521
passing data 336 CEESECS—convert timestamp to number of seconds
receiving parameters 338 example 527
recursive 323 syntax 525
static 327 century encoding/compression
to date and time services 423 using as solution to the year 2000 problem 442
CANCEL statement century window
handling of programs name in 172 assumed for non-dates 464
CBL (PROCESS) statement 141 CEECBLDY callable service 486
CBL statement 187 CEEDAYS callable service 500
CEECBLDY—convert date to COBOL Integer format CEEQCEN callable service 517
example 484 CEESCEN callable service 518
syntax 484 CEESECS callable service 527
CEEDATE—convert Lilian date to character format concept 429
example 490 fixed 447
syntax 488 sliding 447
table of sample output 492 using as solution to the year 2000 problem 440
CEEDATM—convert seconds to character timestamp CESN transaction 358
CEESECI callable service 521 chained list processing 340
example 495 changing
syntax 493 characters to numbers 85
table of sample output 497 file-name 17
CEEDAYS—convert date to Lilian format title on source listing 13
example 501 CHAR compiler option 151
syntax 498 CHAR intrinsic function 86
CEEDYWK—calculate day of week from Lilian date character strings 158
example 503 character timestamp
syntax 502 converting Lilian seconds to (CEEDATM) 493
example 495

588 COBOL Set for AIX Programming Guide


character timestamp (continued) cob2_r4 command
converting to COBOL Integer format for SFS files 97
(CEECBLDY) 484 syntax and description 135
example 487 COBMSGS environment variable 131
converting to Lilian seconds (CEESECS) 525 COBOL
example 525 and C/C++
CHECK run-time option 193 called by C/C++ functions, example 332, 334
CHECK(OFF) run-time option 434 calling C/C++ functions, example 330
checking errors, flagging at run time 193 data types, correspondence with C/C++ 329
checking for valid data 37 COBOL 85 Standard
CICS definition xx
accessing CICS files from non-CICS COBOL language usage with SQL statements 356
applications 363 COBOL Set for AIX
alternate reserved word table 359 run-time messages 532
ASCII-EBCDIC differences 361 COBOPT environment variable 129
coding restrictions 359 COBPATH environment variable 131
commands relevant to COBOL 358 COBRTOPT environment variable 131
compiler options, selecting 360 code
compiler restrictions 359 optimized 431
debugging programs 368 code pages 407
effect of TRAP run-time option 195 coding
invoking COBOL methods 363 class definition 224
object-oriented COBOL 363 client definition 237
preparing COBOL applications to run under condition tests 67
CICS 359 DATA DIVISION 18
programming considerations 358 decisions 64, 66
programs 358 ENVIRONMENT DIVISION 13
run-time, selecting 361 file input/output overview 91
system date 361 for files 94
using dynamic calls 361 IDENTIFICATION DIVISION 12
WORD(CICS) compiler option 359 IF statement 64
cicsmap command 358 input/output overview 94
cicstcl command 358 loops 66, 70
cicsterm command 358 metaclass definition 258
class condition 37, 66 method definition 228
class definition 224 OO programs 222
class test 37, 66, 198 PROCEDURE DIVISION 22
client definition 237 programs to run under CICS 358
cob2 command restrictions for programs for CICS 359
examples using 138 subclass definition 242
options 136 tables 46
syntax and description 135 techniques 18, 19
tailoring configuration 139 test conditions 67
cob2 options collating sequence
modifying defaults 139 alternate 14, 15
cob2_r command ASCII 14
CICS example 367 EBCDIC 14
syntax and description 135 HIGH-VALUE 14
tailoring configuration 139 ISO 7-bit code 14
threading example 405 LOW-VALUE 14

Index 589
collating sequence (continued) compiler options (continued)
MERGE 14 COMPILE 153
NATIVE 14 CURRENCY 154
non-numeric comparisons 14 DATEPROC 155
SEARCH ALL 14 DYNAM 433
SORT 14 ENTRYINT 157
specifying 14 EXIT 157
symbolic character in the 15 FLAG 162, 202
the ordinal position of a character 86 FLAGSTD 163
COLLSEQ compiler option 153 FLOAT 165
columns in tables 46 for application portability 316
command line arguments 351 for debugging 202
command prompt, defining environment variables 128 IDLGEN 165
COMMON attribute 13, 325 LIB 167
COMP (COMPUTATIONAL) 32 LINECOUNT 168
COMP-1 (COMPUTATIONAL-1) 33 LIST 168, 215
COMP-2 (COMPUTATIONAL-2) 33 MAP 169, 206, 211
COMP-3 (COMPUTATIONAL-3) 32 MAXMEM 169
COMP-4 (COMPUTATIONAL-4) 32 NOCOMPILE 205
compatible dates NUMBER 170, 210
with MLE 462 on compiler invocation 209
compilation OPTIMIZE 171, 432, 434
statistics 210 performance considerations 148
COMPILE compiler option 153 PGMNAME 172
use NOCOMPILE to find syntax errors 205 PROFILE 173
compile-time considerations QUOTE 173
compiling programs 136 selecting for CICS 360
executing programs 138 SEPOBJ 174
invoking the compiler 135 SEQUENCE 175, 205
compile-time error messages SIZE 176
choosing severity to be flagged 202 SOURCE 176, 210
embedding in source listing 202 SPACE 177
compiler specifying
calculation of intermediate results 471 order of precedence 141
limits 18 using COBOPT 129
compiler environment variables 128 using PROCESS (CBL) statement 141
compiler error messages 142 SPILL 177
correcting mistakes 144 SQL 177, 354
determining what severity level to produce 162 SSRANGE 178, 206, 434
generating a list of 145 status 209
severity levels 143 TERMINAL 178
compiler options TEST 179, 435
abbreviations 147 THREAD 179
ADATA 149 TRUNC 180
ANALYZE 149 TRUNC(STD|OPT|BIN) 435
APOST 173 TYPECHK 183
BINARY 150 VBREF 184, 215
CALLINT 150 WORD 184
CHAR 151 WSCLEAR 185
COLLSEQ 153 XREF 185, 205, 216

590 COBOL Set for AIX Programming Guide


compiler options (continued) continuation, syntax checking 153
YEARWINDOW 186 CONTINUE statement 64
ZWB 187 control
compiler-directing statements 187 in nested programs 325
assigning a NULL value 342 program flow 64
description 342 transfer 323
list 25 CONTROL statement 187
overview 25 conversion of data formats 35
SET statement, in 342 convert character format to Lilian date (CEEDAYS) 498
value to designate end of list 342 convert Lilian date to character format (CEEDATE) 488
compiling converting data items
IDL files 270 characters to numbers 85
completion code, sort 111 INSPECT statement 82
complex OCCURS DEPENDING ON reversing order of characters 84
basic forms of 59, 479 to integers 82
complex ODO item 480 to uppercase or lowercase 84
variably-located data item 479 with intrinsic functions 84
variably-located group 479 Coordinated Universal Time
COMPUTATIONAL (COMP) 32 See Greenwich Mean Time
COMPUTATIONAL-1 (COMP-1) 33 copy code, obtaining from user-supplied module 157
COMPUTATIONAL-2 (COMP-2) 33 COPY files
COMPUTATIONAL-3 (COMP-3) 32 searching for 137
COMPUTATIONAL-4 (COMP-4) 32 with ODBC 371
concatenating data items 73 COPY statement 187
condition handling 194 form and definition 190
date and time services and 424 nested 160
condition testing 67 uses for portability 317
conditional expression copybook 190
EVALUATE statement 66 ODBC sample 377
IF statement 64 search rules 190
PERFORM statement 66 with ODBC 371
conditional statement core file 145
in EVALUATE statement 66 counting data items 82
list of 24 cross-reference
overview 24 data- and procedure-names 216
with NOT phrase 24 embedded 218
configuration file program-name 218
default 139 special definition symbols 219
stanzas 140 verbs 215
tailoring 140 cross-reference list 184, 185
CONFIGURATION SECTION 13 CURRENCY compiler option 154
considerations current date
system/390 host data type 469 how to obtain 444
CONSOLE environment variable 133 CURRENT-DATE intrinsic function 41
constant customizing
figurative 4 setting environment variables 128
constructor method 261
contained program integration 432
continuation
of program 118

Index 591
data item (continued)
D reversing characters 84
data splitting 75
See also numeric data variably-located 479
checking validity 37 data items
concatenating 73 unused 171
format conversion 35 data representations, portability 318
format, numeric types 30 data types
grouping 339 correspondence between COBOL and C/C++ 329
incompatible 37 data- and procedure-name cross reference,
joining 73 description 216
numeric 29 data-manipulation
passing 336 non-numeric data 73
splitting 75 data-name
validation 37 in MAP listing 212
data areas, dynamic 156 reference modification 108
data definition 212 date and time
data definition attribute codes 212 format
data description entry, description 18 converting from character format to COBOL
DATA DIVISION Integer format (CEECBLDY) 484
class 225, 226 converting from character format to Lilian format
client 238 (CEEDAYS) 498
coding 18 converting from integers to seconds
description 18 (CEEISEC) 510
FD entry 18 converting from Lilian format to character format
FILE SECTION 18 (CEEDATE) 488
limits 18 converting from seconds to character timestamp
LINKAGE SECTION 21 (CEEDATM) 493
listing 211 converting from seconds to integers
mapping of items 211 (CEESECI) 521
method 229 converting from timestamp to number of seconds
OCCURS clause 46 (CEESECS) 525
restrictions 18 getting date and time (CEELOCT) 514
WORKING-STORAGE SECTION 19 services
DATA DIVISION items, mapping 169 CEECBLDY—convert date to COBOL Integer
data item format 484
common, in subprogram linkage 338 CEEDATE—convert Lilian date to character
concatenating 73 format 488
converting 82 CEEDATM—convert seconds to character
converting characters to numbers 85 timestamp 493
converting to uppercase/lowercase 84 CEEDAYS—convert date to Lilian format 498
converting with intrinsic functions 84 CEEDYWK—calculate day of week from Lilian
counting 82 date 502
evaluating with intrinsic functions 86 CEEGMT—get current Greenwich Mean
finding the smallest/largest in group 86 Time 505
index 48 CEEGMTO—get offset from Greenwich Mean
numeric 29 Time to local time 508
reference modification 79 CEEISEC—convert integers to seconds 510
referencing substrings 79 CEELOCT—get current local time 514
replacing 82 CEEQCEN—query the century window 517
CEESCEN—set the century window 518

592 COBOL Set for AIX Programming Guide


date and time (continued) DB2 (continued)
services (continued) package name 355
CEESECI—convert seconds to integers 521 package name, default 355
CEESECS—convert timestamp to number of return codes 354
seconds 525 SQL INCLUDE statement 356
CEEUTC—get Coordinated Universal Time 530 SQL statements 354
condition handling 424 SQL statements supported 357
examples of using 430 DB2DBDFT environment variable 130
feed-back code 423 DBCS user-defined words, listed in XREF output 216
invoking with a CALL statement 423 dce_login, and CICS 358
list of 422 DD statements
overview 422 See environment variables
performing calculations with 428 DEBUG run-time option 193, 200
picture strings 425 debugging
return code 423 activating batch features 193
RETURN-CODE special register 423 assembler 220
date and time information, formatting 132 CICS programs 368
date arithmetic 462 producing information 136
date comparisons useful compiler options 202
with MLE 454 user exits 220
date field expansion 451 using COBOL language features 197
advantages 453 debugging, language features
using intrinsic functions 438 class test 198
DATE FORMAT clause 447 debugging declaratives 199
date operations error declaratives 198
intrinsic functions 10 file status keys 199
date processing with internal bridges INITIALIZE statements 198
advantages 450 scope terminators 198
date windowing SET statements 198
advantages 449 declarative procedures
how to control 458 EXCEPTION/ERROR 120, 198
the MLE approach 447 USE FOR DEBUGGING 199
using intrinsic functions 440 defaults, specifying 128
when not supported 457 defining
DATE-COMPILED paragraph 12 files
DATE-OF-INTEGER intrinsic function 42 in COBOL programs 94
DATEPROC compiler option 155 files, overview 91
eliminating warning-level diagnostic messages 460 DELETE statement 187
DATEVAL intrinsic function 458 deleting records from file 104
day of week, calculating with CEEDYWK 502 delimited scope statement
DB2 description of 26
bind file name 355 nested 27
bind file name, default 355 depth in tables 47
co-processor 354 describing
COBOL language usage with SQL statements 356 data 19
coding considerations 354 files 18
DB2DBDFT environment variable 354 the computer 13
ignored options 356 diagnostic messages
in a multithreading environment 402 from millennium language extensions 460
options 354

Index 593
diagnostics, program 210 entry point (continued)
differences with host COBOL 466 passing entry addresses of 344
direct-access procedure-pointer data item 344
direct indexing 50 entry points, call convention 157
DISPLAY (USAGE IS) 31 ENTRY statement
DISPLAY statement handling of programs name in 172
using in debugging 197 ENTRYINT compiler option 157
DISPLAY statement, defining environment ENV environment variable 128
variables 133 environment differences, System/390 and AIX 320
displaying compile and link steps 138 ENVIRONMENT DIVISION
Distributed Computing Environment (DCE), support class 224
for 398 client 238
documentation of program 13 collating sequence coding 14
dumps, when not produced 195 CONFIGURATION SECTION 13
DYNAM compiler option 156 description 13
description 156 INPUT-OUTPUT SECTION 16
performance considerations 433 method 229
dynamic calls subclass 244
using in a CICS environment 361 environment file 128
dynamic link libraries environment variables
CICS considerations 362 assignment-name 130
dynamic linking 327 COBMSGS 131
linker resolution of shared library references 387 COBOPT 129
terminology 387 DB2DBDFT 130
dynamically called programs, locating 131 defining multiple directory paths 134
EBCDIC_CODEPAGE 131
for file names 130
E for library-name 129
E-level error message 202 for text-name 129
E-level message 143 LIBPATH 132
EBCDIC library-name 190
DBCS portability 319 LOCPATH 132
portability considerations 318 requirements when running programs 145
EBCDIC_CODEPAGE environment variable 131 run time 130
EJECT statement 187 setting 128
embedded cross-reference 218, 219 SYSLIB 129
embedded error messages 202 System Object Model (SOM) 270
embedded MAP summary 206, 213 text-name 190
embedded SQL TZ 133
advantages 370 environment-name 13
Encina SFS files environment, pre-initializing 334
accessing 90, 130, 363 ERRCOUNT run-time options 194
compiling for (cob2_r4) 135 ERRMSG, for generating a listing of compiler
processing files 90 messages 145
Encina SFS files, accessing 96, 97 error
enclave 323 arithmetic 117
end-of-file phrase (AT END) 120 example of message table 54
ENTER statement 187 handling 116
entry point messages, compiler
ENTRY label 323 choosing severity to be flagged 202
embedding in source listing 202

594 COBOL Set for AIX Programming Guide


error messages exit modules (continued)
abbreviated or incomplete, cause of 145 when used in place of library-name 160
compiler 142 when used in place of SYSLIB 160
compiler-detected 142 when used in place of SYSPRINT 161
correcting mistakes 144 EXIT PROGRAM statement
determining what severity level to produce 162 in subprogram 324
displaying error line number 145 expanded IF statement 64
generating a list of 145 explicit scope terminator 25
severity levels 143 exponentiation
when core file is created 145 evaluated in fixed-point arithmetic 473
errors, flagging at run time 193 evaluated in floating-point arithmetic 477
ESTAE exits, affected by TRAP run-time option 195 export command 128
EVALUATE statement export statement
case structure 66 specifying multiple path names 129
evaluating data item contents EXTERNAL clause
class test 37, 66 example for files 347—351
INSPECT statement 82 for data items 346
intrinsic functions 86 for files 19
examples used for input/output 346
CEECBLDY—convert date to COBOL Integer external data
format 487 sharing 346
CEEDATE—convert Lilian date to character external decimal data item 31
format 490 external file 19, 346
CEEDATM—convert seconds to character external floating-point data item 31
format 495
CEEDAYS—convert date to Lilian format 501
CEEDYWK—calculate day of week from Lilian F
date 503 field expansion
CEEGMT—get current GMT 507 using as solution to the year 2000 problem 437
CEEGMTO—get offset from Greenwich Mean Time figurative constant 4
to local time 509 file access mode
CEEISEC—convert integers to seconds 512 dynamic 93
CEELOCT—get current local time 515 for indexed files 93
CEEQCEN—query century window 517 for relative files 93
CEESCEN—set century window 519 for sequential files 93
CEESECI—convert seconds to integers 522 random 93
CEESECS—convert timestamp to number of sequential 93
seconds 527 summary table of 91
IGZEDT4—get current date with 4-digit year 531 file conversion
exception condition 126 with millennium language extensions 451
EXCEPTION/ERROR declarative file organization
description 120 indexed 92
file status key 122 line sequential 92
exceptions, intercepting 195 overview 91
executing compile and link steps 138 relative 92
EXIT compiler option 157 sequential 91
exit modules file position indicator 100, 102
called for SYSADATA data set 161 FILE SECTION
debugging 220 description 18
loading and invoking 159 EXTERNAL clause 19

Index 595
FILE SECTION (continued) finding the length of data items 88
GLOBAL clause 19 finding the smallest or largest data item 86
FILE STATUS clause fixed century window 447
file loading 100 fixed-point arithmetic
using 121 comparisons 44
with VSAM return code 123 evaluation 43
file status key example evaluations 45
checking for successful OPEN 121, 122 fixed-point data
set for error handling 199 binary 32
to check for I/O errors 121 conversions between fixed- and floating-point
used with VSAM return code 123 data 36
file system ID 130 external decimal 31
file system support intermediate results 473
Encina SFS 194 packed decimal 32
STL 194 fixed-point exponentiation 473
using FILESYS run-time option to access 194 FLAG compiler option 162
VSAM 194 compiler output 203
file-name description 202
change 17 flags 67
files FLAGSTD compiler option 163
accessing local files 98 FLOAT compiler option 165
accessing remote files 98 floating-point arithmetic
accessing using environment variables 130 comparisons 44
adding records to 103 evaluation 43
affected by TRAP run-time option 195 example evaluations 45
associating program files to external files 13 floating-point data 319
COBOL coding conversions between fixed- and floating-point
overview 94 data 36
comparison of file organizations 92 external floating-point 31
compiling multiple files 135 intermediate results 477
deleting records from 104 internal 33
Encina SFS 363 floating-point exponentiation 477
file position indicator 100, 102 four-digit year dates 436
input/output error processing 118 full date field expansion
opening 100 advantages 453
path search order 134
processing
Encina SFS files 90 G
STL files 90 GETMAIN, saving address of 158
VSAM files 90 GLOBAL clause for files 19
reading records from 101 global names 327
rejected by the linker 135 GMT
replacing records in 104 See Greenwich Mean Time
RSD 96 GOBACK statement
STL 96 in main program 324
updating records 102 in subprogram 324
usage explanation 17 Greenwich Mean Time (GMT)
VSAM 96 getting offset to local time from (CEEGMTO) 508
FILESYS run-time options 194 return Lilian date and Lilian seconds
(CEEGMT) 505

596 COBOL Set for AIX Programming Guide


Gregorian character string IDL type (continued)
returning local time as a (CEELOCT) 514 enum 280
example 515 float 281
group item interface 281
variably-located 479 long 281
grouping data 339 object reference
See IDL type, interface
octet 282
H pointer 282
header on listing 13 sequence 286
help files short 282
indicating language display 132 string 282, 290
specifying path name 132 struct 286
HEXADECIMAL union 287
portability considerations 319 unsigned long 284
host data type unsigned short 284
See system/390 host data type void 284
IDLGEN compiler option 165
IEEE
I portability considerations 319
I-level error message 202 IF statement
I-level message 143 coding 64
IDENTIFICATION DIVISION nested 64
class 224 with null branch 64
coding 12 IGYCCICS, alternate reserved word table 359
DATE-COMPILED paragraph 12 IGZEDT4—get current date with 4-digit year 530
errors 13 imperative statement, list 24
listing header example 13 implicit scope terminator 25
method 228 incompatible data 37
PROGRAM-ID paragraph 12 incomplete run-time messages 145
required paragraphs 12 incrementing addresses 343
TITLE statement 13 index data item 51
IDL 275 index key, detecting faulty 125
access intent specifiers 288 index range checking 206
attributes 278 index-name subscripting 49
common types 279 index, table 48
complex types 284 indexed file organization 92
files 302 Indexed files
identifiers 277 file access mode 93
literal arguments 289 indexing
mapping to COBOL 276 example 56
operations 277 restrictions 50
parameter-passing conventions 287 tables 49
passing complex types 290 INEXIT suboption of EXIT option 158, 159
IDL type INITIAL attribute 13, 324
any 285 INITIALIZE statement
array 285 examples 4
boolean 279 loading table values 52
char 280 using for debugging 198
double 280

Index 597
initializing intrinsic functions (continued)
a table 52 compatibility with CEELOCT callable service 514
input converting character data items 84
overview 91 DATEVAL 458
input procedure evaluating data items 86
requires RELEASE or RELEASE FROM 110 example of
restrictions 111 ANNUITY 42
using 109 CHAR 86
INPUT-OUTPUT SECTION 16 CURRENT-DATE 41
input/output INTEGER 82
checking for errors 121 INTEGER-OF-DATE 41
coding overview 94 LENGTH 41, 87, 88
introduction 91 LOG 43
logic flow after error 118 LOWER-CASE 84
processing errors for files 118 MAX 63, 86, 87
input/output coding MEAN 43
AT END (end-of-file) phrase 120 MEDIAN 43, 63
checking for successful operation 121 MIN 82
checking VSAM return codes 123 NUMVAL 85
detecting faulty index key 125 NUMVAL-C 41, 85
error handling techniques 118 ORD 86
EXCEPTION/ERROR declaratives 120 ORD-MAX 63, 87
INSERT statement 187 PRESENT-VALUE 42
INSPECT statement 82 RANGE 43, 63
inspecting data 82 REM 43
integer format date REVERSE 84
using as solution to the year 2000 problem 442 SQRT 43
INTEGER intrinsic function 82 SUM 63
INTEGER-OF-DATE intrinsic function 41 UPPER-CASE 84
integers WHEN-COMPILED 88
converting Lilian seconds to (CEESECI) 521 intermediate results 475, 477
converting to Lilian seconds (CEEISEC) 510 introduction to 9
Interface Repository (IR) nesting 10
accessing 269 numeric functions
definition 269 examples of 40
populating 269 nested 40
interlanguage communication special registers as arguments 40
between COBOL and C/C++ 328 table elements as arguments 40
intermediate results 471 type of—integer, floating-point, mixed 40
internal bridges uses for 40
advantages 450 processing table elements 62
for date processing 449 reference modification of 81
internal bridging simplifies coding 422
date processing solution 439 UNDATE 459
internal floating-point data INVALID KEY phrase 125
bytes required 33 INVOKE statement
defining 33 use with PROCEDURE DIVISION RETURNING 345
uses for 33 invoking
intrinsic functions date and time services 423
as reference modifier 82

598 COBOL Set for AIX Programming Guide


invoking the compiler and linker 135 limits of the compiler 18
line number 211
line numbers, on listing 210
J line sequential file organization 92
job stream 323 Line sequential files
file access mode 93
LINECOUNT compiler option 168
K LINKAGE SECTION
Kanji 66 description 338
keywords xxi GLOBAL clause 22
run unit 21
with recursive calls 21
L with the THREAD option 21
linkages, data 329
LANG environment variable 132
language features for debugging linker
See also debugging, language features resolution of references to shared libraries 387
DISPLAY statements 197 linker, invoking 135
last-used state 324 linking
LC_COLLATE environment variable 132 dynamic 328
LC_MESSAGES environment variable 132 static 328, 386
LC_TIME environment variable 132 linking, executing 138
LENGTH intrinsic function LIST compiler option 168
example 41, 88 conflict with OFFSET option 215
variable length results 87 getting output 215
versus LENGTH OF special register 88 terms used in output 214
length of data items, finding 88 listings
LENGTH OF special register 88, 337 See also SYSADATA
level assembler expansion of procedure division 215
88 item 66, 67 compiler options affecting 147
level definition 212 data- and procedure-name cross reference 216
LIB compiler option embedded cross-reference 218
description and syntax 167 embedded MAP summary 212
when required for -I option 137 generating a short listing 207
LIBEXIT suboption of EXIT option 158, 160 including your source code 210
LIBPATH environment variable 132 line numbers, user-supplied 210
library text mapping DATA DIVISION Items 211
specifying path for 190 sorted cross reference of program names 218
library-name terms used in MAP output 214
specifying path for library text 190 verb cross-reference 215
library-name, when not used 160 with error messages embedded 202
Lilian date loading a table, dynamically 52
calculate day of week from (CEEDYWK) 502 local name 327
convert date to (CEEDAYS) 498 local time
convert date to COBOL Integer format getting (CEELOCT) 514
(CEECBLDY) 484 LOCAL-STORAGE section 20
convert output_seconds to (CEEISEC) 511 locale 413
convert to character format (CEEDATE) 488 locale information database
get current local date or time as a (CEELOCT) 514 specifying search path name 132
get GMT as a (CEEGMT) 505 LOCPATH environment variable 132
using as input to CEESECI callable service 522

Index 599
LOG intrinsic function 43 metaclass definition 258
loops method definition 228
coding 70 METHOD-ID paragraph 229
conditional 71 methods 240
in a table 71 invoking from CICS programs 363
performed a definite number of times 71 PROCEDURE DIVISION RETURNING 345
LOWER-CASE intrinsic function 84 millennium bug 446
lowercase 84 millennium language extensions 446
assumed century window 464
compatible dates 462
M compiler options affecting 147
main program concepts 462
and subprograms 323 date windowing 447
arguments to 351 DATEPROC compiler option 155
specifying with cob2 136, 137 non-dates 463
MAP compiler option 169, 206, 211 objectives 461
embedded MAP summary 212 performance aspects 444
example 211, 214 principles 461
nested program map 214 YEARWINDOW compiler option 186
terms used in output 214 MIN intrinsic function 82, 86
mapping of DATA DIVISION items 211 MIXED suboption of PGMNAME 173
maps and listings 147 MLE 446
mathematics mnemonic-name
intrinsic functions 40, 43 SPECIAL-NAMES paragraph 13
MAX intrinsic function 63, 86, 87 modules, exit
MAXMEM compiler option 169 loading and invoking 159
MEAN intrinsic function 43, 63 MOVE statement 7
MEDIAN intrinsic function 43, 63 multiple PROCESS statements 142
merge multiple thread environment, running in 179
concepts 105 multitasking 398
description 105 multithreading
files, describing 105 control transfer issues 401
successful 111 limitations on COBOL 402
MERGE statement overview 397
description 111 preparing COBOL programs for 397
MERGE work files 133 scope of language elements
messages program invocation instance scoped
abbreviated or incomplete, cause of 145 elements 400
compile-time error run-unit scoped elements 400
choosing severity to be flagged 202 synchronizing access to resources 402
embedding in source listing 202 terminology 397
compiler 142 THREAD compiler option
determining what severity level to produce 162 recursion 401
displaying error line number 145 restrictions under 400
formatting time and date information 132 when to choose 400
indicating language display 132
run-time 532
specifying path name 132 N
when core file is created 145 naming
when not produced 195 programs 12

600 COBOL Set for AIX Programming Guide


National Language Support (NLS) numeric data (continued)
code pages 407 format conversions between fixed- and
considerations 407 floating-point 35
locale sensitivity 413 internal floating-point 33
national language, specifying 132 USAGE IS COMPUTATIONAL-1 (COMP-1) 33
nested COPY statement 160 USAGE IS COMPUTATIONAL-2 (COMP-2) 33
nested delimited scope statements 27 internal storage formats 30
nested IF statement overview 29
CONTINUE statement 64 packed-decimal 32
description 64 USAGE IS COMPUTATIONAL-3 (COMP-3) 32
EVALUATE statement preferred 64 USAGE IS PACKED-DECIMAL 32
with null branches 64 PICTURE clause 29, 30
nested intrinsic functions 40 numeric editing symbol 30
nested program integration 432 numeric intrinsic functions
nested program map 214 example of
nested programs ANNUITY 42
calling 325 CURRENT-DATE 41
conventions for using 325 INTEGER 82
map 214 INTEGER-OF-DATE 41
scope of names 327 LENGTH 41, 87
structure 324 LOG 43
transfer of control 325 MAX 63, 86, 87
nesting level MEAN 43
program 211, 215 MEDIAN 43, 63
statement 211 MIN 82
NLSPATH environment variable 132 NUMVAL 85
NOCOMPILE compiler option NUMVAL-C 41, 85
use of to find syntax errors 205 ORD 86
non-dates ORD-MAX 63
with MLE 463 PRESENT-VALUE 42
NOSSRANGE compiler option RANGE 43, 63
affect on checking errors 193 REM 43
null branch 64 SQRT 43
null-terminated strings 78, 339 SUM 63
NUMBER compiler option 210 nested 40
effect on compiler messages 143 special registers as arguments 40
syntax and description 170 table elements as arguments 40
numeric class test 37 types of—integer, floating-point, mixed 40
numeric data uses for 40
binary 32 numeric-edited data item 30
USAGE IS BINARY 32 NUMVAL intrinsic function 85
USAGE IS COMPUTATIONAL (COMP) 32 NUMVAL-C intrinsic function 41, 85
USAGE IS COMPUTATIONAL-4 (COMP-4) 32
conversions between fixed- and floating-point
data 36 O
conversions between fixed-point data 36 object code
editing symbols 30 controlling 147
external decimal 31 generating 153
USAGE IS DISPLAY 31 object deck generation 147
external floating-point
USAGE IS DISPLAY 31

Index 601
object file, setting up 137 optimization
object module, naming 137 contained program integration 432
object references 239 effect of compiler options on 433
OBJECT-COMPUTER paragraph 13 nested program integration 432
object-oriented COBOL unused data items 171
generating IDL definitions 165 OPTIMIZE compiler option 171
restrictions for DYNAM compiler option 156 affect on performance 432
support under CICS 363 description 432
objectives of millennium language extensions 461 performance considerations 434
OCCURS clause 46 optimizer 431
OCCURS DEPENDING ON (ODO) clause optional words xxi
complex 59, 479 ORD intrinsic function 86
initializing ODO elements 53 ORD-MAX intrinsic function 63, 87
simple 56 ORD-MIN intrinsic function 87
variable-length tables 56 order of precedence, compiler option specification 141
ODBC 369 OS/2, porting to 322
accessing return values 376 output
advantages 370 overview 91
background 369 output procedure
CALL interface convention 371 requires RETURN or RETURN INTO statement 110
driver manager 369 restrictions 111
embedded SQL 370 using 110
mapping of C data types 373 overflow condition 116, 126
passing a COBOL pointer to 373
sample program 377
supplied copybooks 371 P
supplied odbc3.cpy 377 packed decimal data item
supplied odbc3d.cpy 377 general description 32
supplied odbc3p.cpy 377 using efficiently 32
using APIs from COBOL 370 PACKED-DECIMAL
using the drivers 370 general description 32
odbc3.cpy 377 synonym 30
odbc3d.cpy 377 using efficiently 32
odbc3p.cpy 377 page header 209, 210, 211
ODO (OCCURS DEPENDING ON) clause paragraph
simple 56 grouping 72
variable-length tables 56 introduction 23
OMITTED parameters 423 parameter
ON SIZE ERROR phrase describing in called program 338
with windowed date fields 456 in main program 351
OO COBOL parameter list
generating IDL definitions 165 address of with INEXIT 159
Open Database Connectivity (see ODBC) 369 for ADEXIT 161
OPEN operation code 159 for PRTEXIT 161
OPEN statement passing addresses between programs 341
file availability 100 passing data between programs
file status key 121 BY CONTENT 336
opening files 100 BY REFERENCE 336
using environment variables 130 BY VALUE 336
called program 337

602 COBOL Set for AIX Programming Guide


passing data between programs (continued) picture strings
calling program 337 date and time services and 425
EXTERNAL data 346 platform differences 320
language used 337 pointer data item
path name incrementing addresses with 343
adding to a directory search 137 NULL value 342
for COPY files search 190 used to pass addresses 341
library text 129, 190 used to process chained list 340
multiple, specifying 190 portability 316
search order for files 134 environment differences 320
specifying for catalogs and help files 132 run-time differences between mainframe and
specifying for COBOL run-time library 132 OS/2 320
specifying for dynamic programs 131 porting applications
specifying for library 129 AIX to mainframe
specifying for locale information database 132 AIX-only language features 321
specifying with LIB compiler option 167 AIX-only names 321
PC and workstation COBOL AIX to OS/2 322
differences from host 466 architectural differences between platforms 316
PERFORM statement language differences between AIX and
. . .THRU 72 mainframe 316
coding loops 70 mainframe to AIX
for a table 54 choosing compiler options 316
indexing 51 running mainframe applications under AIX 317
performed a definite number of times 71 using COPY to isolate platform-specific code 317
TIMES 71 porting your program 29
UNTIL 71 pre-initializing the COBOL environment 334
VARYING 71 prefix for compiler messages 143
VARYING WITH TEST AFTER 71 PRESENT-VALUE intrinsic function 42
WITH TEST AFTER . . . UNTIL 71 printer files 92
WITH TEST BEFORE . . . UNTIL 71 procedure and data-name cross reference,
performance description 216
coding tables 63 PROCEDURE DIVISION
compiler option considerations 148 client 239
DYNAM compiler option 433 description 22
effect of compiler options on 433 in subprograms 338
OPTIMIZE compiler option 432, 434 method 230
optimizer 431 RETURNING 23
SSRANGE compiler option 434 statements
TEST compiler option 435 compiler-directing 25
TRUNC compiler option 180 conditional 24
TRUNC(STD|OPT|BIN) compiler option 435 delimited scope 26
variable subscript data format 49 imperative 24
performing calculations terminology 22
date and time services and 428 USING 23
period, as scope terminator 25 PROCEDURE DIVISION RETURNING
PGMNAME compiler option 172 methods, use of 345
phase with errors, identifying 143 procedure-pointer data item
PICTURE clause entry address for entry point 344
determining symbol used 154 passing parameters to callable services 344
numeric data 29 rules for using 344

Index 603
procedure-pointer data item (continued) record (continued)
SET statement and 344 format 91
PROCESS (CBL) statement 141 records, affected by TRAP run-time option 195
processes 397 recursive calls 12, 323
processing and the LINKAGE SECTION 21
chained list 340 reference modification
tables 54 example 80
using indexing 56 of an intrinsic function, example 81
using subscripting 55 out-of-range values 80
PROFILE compiler option 173 tables 51, 82
profiling support, PROFILE option 173 reference modifier
program arithmetic expression as 81
attribute codes 215 intrinsic function as 82
decisions variables as 80
EVALUATE statement 66 relate items to system-names 13
IF statement 64 relation condition 66
loops 71 relative file organization 92
PERFORM statement 71 Relative files
switches and flags 67 file access mode 93
diagnostics 210 RELEASE FROM statement
main 323 compared to RELEASE 110
nesting level 211 example 110
statistics 210 RELEASE statement
structure 12 compared to RELEASE FROM 110
sub 323 with SORT 108, 110
PROGRAM COLLATING SEQUENCE clause 14 REM intrinsic function 43
program entry points, call convention 157 REPLACE statement 187
program names, handling of case 172 replacing
PROGRAM-ID paragraph data items 82
COMMON attribute 13 records in file 104
description 12 REPOSITORY paragraph 13, 225
INITIAL attribute 13 representation
program-name cross-reference 218 data 37
programs, running 145 sign 37
PRTEXIT suboption of EXIT option 158, 161 required words xx
reserved word table
CICS 359
Q restrictions
QUOTE compiler option 173 indexing 50
input/output procedures 111
subscripting 49
R return code
RANGE intrinsic function 43, 63 feedback code from date and time services 423
reading records from files from DB2 357
dynamically 102 RETURN-CODE special register 345, 423
randomly 102 VSAM files 123
sequentially 101 when control returns to operating system 345
receiving field 75 RETURN INTO statement 110
record RETURN statement 110
description 18

604 COBOL Set for AIX Programming Guide


RETURN-CODE special register run-time options (continued)
considerations for DB2 357 UPSI 196
value after call to date and time service 423 run-unit
when control returns to operating system 345 role in multithreading 397
RETURNING phrase running programs 145
methods, use of 345
REVERSE intrinsic function 84
reversing characters 84 S
rows in tables 47 S-level error message 202
RSD files, accessing 96 S-level message 143
run time scope terminator
changing file-name 17 aids in debugging 198
run unit 323 explicit 25, 26
run-time implicit 25
differences between platforms 318 SEARCH ALL statement
messages 532 binary search 61
run-time arguments 351 indexing 49, 60
run-time environment variables 128 ordered table 61
assignment-name 130 SEARCH statement
COBPATH 131 examples 61
COBRTOPT 131 indexing 49, 51
LANG 132 nesting 60
LC_COLLATE 132 serial search 60
LC_MESSAGES 132 searching a table 60
LC_TIME 132 section
NLSPATH 132 declarative 27
SYSIN, SYSIPT, SYSOUT, SYSLIST, SYSLST, description of 23
CONSOLE, SYSPUNCH, SYSPCH 133 grouping 72
TEMP 133 SELECT clause
run-time error messages vary input/output file 17
abbreviated or incomplete, cause of 145 SELECT OPTIONAL 100
displaying error line number 145 sending field 75
formatting time and date information 132 sentence 23
indicating language display 132 separate digit sign 29
specifying path name 132 SEPOBJ compiler option 174
when core file is created 145 SEQUENCE compiler option 175, 205
run-time library sequential file organization 91
specifying path name 132 Sequential files
run-time loading 394 file access mode 93
run-time options serial search 60
CHECK 193 SET condition-name TO TRUE statement
CHECK(OFF) 434 description 69
DEBUG 193, 200 example 71
ERRCOUNT 194 SET statement
FILESYS 194 for procedure-pointer data items 344
selecting for CICS 361 handling of programs name in 172
specifying 131 indicates path search order 134
supported 193 using for debugging 198
TRAP 195 setting
ON SIZE ERROR 117 switches and flags 68

Index 605
severe errors, creates core file 145 SORT statement
severity codes for error messages 143 description 107
SFS (Encina) files SORT work files 133
processing files 90 SORT-RETURN special register 112
SFS files (Encina) source code
accessing 90, 130, 363 line number 211, 212, 215
compiling for (cob2_r4) 135 listing, description 210
SFS files (Encina), accessing 96, 97 SOURCE compiler option 176, 210
shared libraries SOURCE-COMPUTER paragraph 13
advantages and disadvantages 386 SPACE compiler option 177
building 386 special feature specification 13
linker resolution of references 387 special register
overview 386 ADDRESS 336
overview of shared libraries 386 arguments in intrinsic functions 40
purpose 386 LENGTH OF 88, 337
subprograms and outermost programs 387 WHEN-COMPILED 88
terminology 387 special registers
sharing SORT 112
See also passing data SORT-CONTROL 112
data 327, 346 SORT-RETURN 112
files 19, 327, 346 SPECIAL-NAMES paragraph 13
sign condition 66 for collating sequence 14
sign representation 37 SPILL compiler option 177
SIZE compiler option 176 splitting data items 75
SKIP1/2/3 statement 187 SQL compiler option 177, 354
sliding century window 447 SQL INCLUDE statement 356
SMARTdata Utilities 98 SQL statements 354
SOM 275 SQL statements supported 357
CORBA-style exceptions 297 SQLCA 354
environment arguments 297 SQLCODE 357
errors and exceptions 297 SQLSTATE 357
COBOL example 298 SQRT intrinsic function 43
initializers 301 SSRANGE compiler option 178
memory management with 304 CHECK(OFF) run-time option 434
SOMerror-style exceptions 297 description 206
sort performance considerations 434
alternate collating sequence 109 stacked words xxi
concepts 105 statement
criteria 108 compiler-directing 25
description 105 conditional 24
files, describing 105 definition 24
more than one 105 delimited scope 26
restrictions on input/output procedures 111 explicit scope terminator 25
special registers 112 imperative 24
successful 111 implicit scope terminator 25
terminating 112 statement nesting level 211
using input procedures 109 static linking 327
using output procedures 110 advantages and disadvantages 386
Sort File Description (SD) entry overview 386
example 106 terminology 387

606 COBOL Set for AIX Programming Guide


statistics SYSIN, SYSIPT, SYSOUT, SYSLIST, SYSLST,
intrinsic functions 43 CONSOLE, SYSPUNCH, SYSPCH environment vari-
STL file system 113 ables 133
STL files, accessing 96 SYSLIB
STOP RUN statement supplying alternative modules 157
in main program 324 when not used 160
in subprogram 324 SYSLIB environment variable 129
STRING statement SYSPRINT
description 73 supplying alternative modules 157
example of 73 when not used 161
overflow condition 116 system date
strings under CICS 361
null-terminated 339 System Object Model (see also "SOM") 275
structured programming System Object Model (SOM)
PROCEDURE DIVISION 22 compiling IDL files 270
subclass definition 242 environment variables 270
subprogram initialization 272
and main program 323 Interface Repository (IR) 269
definition of 323 methods and functions 271
linkage 323 services 271
linkage, common data items 338 somFree 239
subprograms somNEW 239
Procedure Division in 338 system-name 13
subscript range checking 206 system/390 host data type
subscripting considerations 469
example of processing a table 55
index-names 49
literal 48 T
reference modification 51 table
relative 49 assigning values 52
restrictions 49 columns 46
variable 49 defining 46
substrings depth 47
See also reference modification dynamically loading 52
of data 79 efficient coding of 63
referencing table items 82 handling 46
SUM intrinsic function 63 index 48
switch-status condition 66 initialize 52
switches 67 intrinsic functions 62
SYMBOLIC CHARACTER clause 15 loading values in 52
syntax errors looping through 71
finding with NOCOMPILE compiler option 205 making reference 48
SYSADATA file 149 one-dimensional 46
SYSADATA records reference modification 51
exit module called 161 referencing table entry substrings 82
supplying modules 157 rows 47
SYSIN searching 60
supplying alternative modules 157 subscripts 48
use in ACCEPT and DISPLAY statements 133 three-dimensional 47
two-dimensional 47

Index 607
table (continued) UNDATE intrinsic function 459
variable-length 56 UNSTRING statement
TALLYING option 82 description 75
TEMP environment variable 133 example 75
TERMINAL compiler option 178 overflow condition 116
terminal, sending messages to 178 updating records 102
terminology UPPER suboption of PGMNAME 172
introduction to COBOL terms 2 UPPER-CASE intrinsic function 84
static and dynamic linking 387 uppercase 84
terms used in MAP output 214 UPSI run-time options 196
test UPSI switches, setting 196
data 66 USAGE clause
for values 66 incompatible data 37
numeric operand 66 IS INDEX 51
UPSI switch 66 USE EXCEPTION/ERROR declaratives 198
TEST compiler option 179 USE FOR DEBUGGING declarative 193
performance considerations 435 USE FOR DEBUGGING declaratives 199
THREAD compiler option 179 USE statement 187
and the LINKAGE SECTION 21 user-defined condition 66
use cob2_r 135 user-exit work area 158
threading (see "multithreading") UTC (Coordinated Universal Time)
time and date information, formatting 132 See Greenwich Mean Time
time zone information
specifying with TZ 133
time, getting local (CEELOCT) 514 V
timestamp 493, 525 valid data 37
TITLE statement 187 VALUE clause
controlling header on listing 13 assigning table values 52
titles Data Description entry 54
controlling header on listing 13 VALUE IS NULL 342
transferring control variable
between COBOL programs 324 as reference modifier 80
called program 323 COBOL term for 2
calling program 323 variable-length table 56
main and subprograms 323 variables, environment 128
translating CICS into COBOL 358 COBMSGS 131
TRAP run-time option 195 EBCDIC_CODEPAGE 131
ON SIZE ERROR 117 LIBPATH 132
TRUNC compiler option 32, 180 library-name 129, 190
TRUNC(STD|OPT|BIN) compiler option 435 LOCPATH 132
trunction, binary 32 SYSLIB 129
tuning considerations, performance 433 text-name 129, 190
TYPECHK compiler option 183 TZ 133
TZ environment variable 133 variably-located data item 479
variably-located group 479
VBREF compiler option 184, 215
U verb cross-reference listing
U-level error message 202 description 215
U-level message 143 verbs used in program 215

608 COBOL Set for AIX Programming Guide


VSAM year 2000 problem extensions 446
accessing local files 98 year expansion
accessing remote files 98 using intrinsic functions 438
I/O in a multithreading environment 402 year field expansion 451
VSAM files year windowing
logic flow after I/O error 118 advantages 449
processing files 90 how to control 458
return codes 123 the MLE approach 447
VSAM files, accessing 96 using intrinsic functions 440
when not supported 457
YEARWINDOW
W compiler option 186
W-level error message 202
W-level message 143
WHEN phrase Z
SEARCH statement 60 ZWB compiler option 187
WHEN-COMPILED intrinsic function
example 88
versus WHEN-COMPILED special register 88
WHEN-COMPILED special register 88
WITH DEBUGGING MODE clause 193
wlist file 168
WORD compiler option 184
working storage
defining program data 19
initializing 185
WORKING-STORAGE SECTION
class 226
description 19
method 230
workstation and PC COBOL
differences from host 466
writing compatible code 321
WSCLEAR compiler option 185

X
XREF compiler option 185, 205, 216

Y
year 2000 Problem
century encoding/compression solution 442
century window solution 440
explanation 436
field expansion solution 437
integer format date solution 442
internal bridging 439
mixed solution 441

Index 609
We'd Like to Hear from You
COBOL Set for AIX
Programming Guide
Release 1
Publication No. SC26-8423-03

Please use one of the following ways to send us your comments about this book:
Ÿ Mail—Use the Readers' Comments form on the next page. If you are sending the form from a
country other than the United States, give it to your local IBM branch office or IBM represen-
tative for mailing.
Ÿ Fax—Use the Readers' Comments form on the next page and fax it to this U.S. number:
800-426-7773.
Ÿ Electronic mail—Use one of the following network IDs:
– IBMMail: USIB2VVG at IBMMAIL
– IBMLink: COBPUBS at STLVM27
– Internet: [email protected]
Be sure to include the following with your comments:
– Title and publication number of this book
– Your name, address, and telephone number if you would like a reply

Your comments should pertain only to the information in this book and the way the information is
presented. To request additional publications, or to comment on other IBM information or the
function of IBM products, please give your comments to your IBM representative or to your IBM
authorized remarketer.

IBM may use or distribute your comments without obligation.


Readers' Comments
COBOL Set for AIX
Programming Guide
Release 1
Publication No. SC26-8423-03

How satisfied are you with the information in this book?

Very Very
Satisfied Satisfied Neutral Dissatisfied Dissatisfied
Technically accurate Ø Ø Ø Ø Ø
Complete Ø Ø Ø Ø Ø
Easy to find Ø Ø Ø Ø Ø
Easy to understand Ø Ø Ø Ø Ø
Well organized Ø Ø Ø Ø Ø
Applicable to your tasks Ø Ø Ø Ø Ø
Grammatically correct and con-
sistent Ø Ø Ø Ø Ø
Graphically well designed Ø Ø Ø Ø Ø
Overall satisfaction Ø Ø Ø Ø Ø

Please tell us how we can improve this book:

May we contact you to discuss your comments? Ø Yes Ø No

Name Address

Company or Organization

Phone No.
Cut or Fold
Readers' Comments

IBM
Along Line
SC26-8423-03

Fold and Tape Please do not staple Fold and Tape

NO POSTAGE
NECESSARY
IF MAILED IN THE
UNITED STATES

BUSINESS REPLY MAIL


FIRST-CLASS MAIL PERMIT NO. 40 ARMONK, NEW YORK

POSTAGE WILL BE PAID BY ADDRESSEE

Department J58
International Business Machines Corporation
PO BOX 49023
SAN JOSE CA 95161-9945

Fold and Tape Please do not staple Fold and Tape

Cut or Fold
SC26-8423-03 Along Line
IBM 

Program Number: 5765-548

Printed in the United States of America


on recycled paper containing 10%
recovered post-consumer fiber.

COBOL Set for AIX


GC26-8484 Fact Sheet
GC26-8425 Getting Started
SC26-9046 Language Reference
SC09-2202 LPEX User's Guide and Reference
SC09-2201 Program Builder User's Guide
SC26-8423 Programming Guide

SC26-8423-ð3
Spine information:

IBM COBOL Set for AIX Programming Guide Release 1

You might also like