Programming Guide
Programming Guide
6.2
Programming Guide
IBM
SC27-8714-01
Note
Before using this information and the product it supports, be sure to read the general information under
“Notices” on page 867.
Tables.................................................................................................................xix
Preface.............................................................................................................. xxv
About this information..............................................................................................................................xxv
How this information will help you..................................................................................................... xxv
Abbreviated terms...............................................................................................................................xxv
Comparison of commonly used terms...............................................................................................xxvi
How to read syntax diagrams............................................................................................................xxvii
How examples are shown................................................................................................................ xxviii
Additional documentation and support................................................................................................ xxviii
Summary of changes............................................................................................................................... xxix
Version 6 Release 2 with PTFs installed............................................................................................xxix
Version 6 Release 2...........................................................................................................................xxxii
How to send your comments.................................................................................................................xxxiii
iii
Assigning input from a screen or file (ACCEPT)............................................................................. 35
Displaying values on a screen or in a file (DISPLAY)........................................................................... 35
Displaying data on the system logical output device.....................................................................36
Using WITH NO ADVANCING..........................................................................................................37
Using intrinsic functions (built-in functions)....................................................................................... 38
Using tables (arrays) and pointers....................................................................................................... 39
Storage and its addressability..............................................................................................................39
iv
Chapter 5. Selecting and repeating program actions............................................................................... 91
Selecting program actions................................................................................................................... 91
Coding a choice of actions.............................................................................................................. 91
Coding conditional expressions......................................................................................................95
Repeating program actions.................................................................................................................. 99
Choosing inline or out-of-line PERFORM....................................................................................... 99
Coding a loop................................................................................................................................ 100
Looping through a table................................................................................................................101
Executing multiple paragraphs or sections................................................................................. 101
v
Processing Chinese GB 18030 data.................................................................................................. 144
Comparing national (UTF-16) data....................................................................................................145
Comparing two class national operands......................................................................................145
Comparing class national and class numeric operands.............................................................. 146
Comparing national numeric and other numeric operands.........................................................146
Comparing national and other character-string operands.......................................................... 147
Comparing national data and alphanumeric-group operands.................................................... 147
Coding for use of DBCS support.........................................................................................................147
Defining DBCS data.......................................................................................................................148
Using DBCS literals....................................................................................................................... 148
Testing for valid DBCS characters................................................................................................ 149
Processing alphanumeric data items that contain DBCS data....................................................149
vi
Handling errors in VSAM files............................................................................................................ 194
Protecting VSAM files with a password............................................................................................. 194
Example: password protection for a VSAM indexed file..............................................................195
Working with VSAM data sets under z/OS and z/OS UNIX............................................................... 195
Defining VSAM files.......................................................................................................................196
Creating alternate indexes........................................................................................................... 196
Allocating VSAM files....................................................................................................................198
Sharing VSAM files through RLS...................................................................................................199
Allocation of record areas for VSAM files.......................................................................................... 201
Improving VSAM performance...........................................................................................................201
Extended addressability support.......................................................................................................202
vii
Handling errors in joining and splitting strings..................................................................................232
Handling errors in arithmetic operations.......................................................................................... 232
Example: checking for division by zero........................................................................................ 233
Handling errors in input and output operations................................................................................ 233
Using the end-of-file condition (AT END).....................................................................................236
Coding ERROR declaratives..........................................................................................................236
Using file status keys.................................................................................................................... 237
Example: file status key................................................................................................................238
Using VSAM status codes (VSAM files only)................................................................................ 238
Example: checking VSAM status codes....................................................................................... 239
Coding INVALID KEY phrases.......................................................................................................240
Example: FILE STATUS and INVALID KEY................................................................................... 241
Handling errors when calling programs............................................................................................ 241
Writing routines for handling errors...................................................................................................242
viii
Creating a DLL under z/OS UNIX.................................................................................................. 276
Example: using cob2 to compile and link under z/OS UNIX....................................................... 276
cob2 syntax and options...............................................................................................................277
cob2 input and output files.......................................................................................................... 279
Compiling using scripts...................................................................................................................... 280
ix
LINECOUNT........................................................................................................................................ 331
LIST.....................................................................................................................................................331
MAP.....................................................................................................................................................332
MAXPCF.............................................................................................................................................. 333
MDECK................................................................................................................................................ 334
NAME.................................................................................................................................................. 335
NSYMBOL........................................................................................................................................... 335
NUMBER............................................................................................................................................. 336
NUMCHECK........................................................................................................................................ 336
NUMPROC...........................................................................................................................................340
OBJECT...............................................................................................................................................341
OFFSET............................................................................................................................................... 341
OPTFILE..............................................................................................................................................342
OPTIMIZE........................................................................................................................................... 343
OUTDD................................................................................................................................................ 344
PARMCHECK.......................................................................................................................................344
PGMNAME.......................................................................................................................................... 345
QUALIFY............................................................................................................................................. 347
RENT................................................................................................................................................... 348
RMODE................................................................................................................................................349
RULES................................................................................................................................................. 350
SEQUENCE..........................................................................................................................................352
SERVICE............................................................................................................................................. 352
SOURCE.............................................................................................................................................. 353
SPACE................................................................................................................................................. 353
SQL......................................................................................................................................................354
SQLCCSID........................................................................................................................................... 355
SQLIMS............................................................................................................................................... 355
SSRANGE............................................................................................................................................ 356
STGOPT...............................................................................................................................................357
SUPPRESS.......................................................................................................................................... 358
TERMINAL.......................................................................................................................................... 358
TEST....................................................................................................................................................359
THREAD.............................................................................................................................................. 363
TRUNC................................................................................................................................................ 364
VBREF................................................................................................................................................. 366
VLR......................................................................................................................................................366
VSAMOPENFS.....................................................................................................................................368
WORD................................................................................................................................................. 369
XMLPARSE.......................................................................................................................................... 369
XREF................................................................................................................................................... 370
ZONECHECK....................................................................................................................................... 371
ZONEDATA.......................................................................................................................................... 372
ZWB.................................................................................................................................................... 375
x
Checking for valid ranges............................................................................................................. 387
Selecting the level of error to be diagnosed................................................................................ 388
Finding program entity definitions and references......................................................................390
Listing data items..........................................................................................................................390
Using the debugger............................................................................................................................ 391
Getting listings................................................................................................................................... 391
Example: short listing................................................................................................................... 393
Example: SOURCE and NUMBER output......................................................................................396
Example: MAP output................................................................................................................... 396
Reading LIST output..................................................................................................................... 402
Example: XREF output: data-name cross-references................................................................. 420
Example: OFFSET compiler output.............................................................................................. 424
Example: VBREF compiler output................................................................................................ 424
Example: conditional compilation output....................................................................................425
Suppressing information in CEEDUMP processing (IGZ1OPT).........................................................426
xi
Separating IMS suboptions.......................................................................................................... 454
Compiling and linking COBOL programs for running under IMS.......................................................454
Using object-oriented COBOL and Java under IMS.......................................................................... 455
Calling a COBOL method from a Java application under IMS..................................................... 455
Building a mixed COBOL-Java application that starts with COBOL............................................ 456
Writing mixed-language IMS applications................................................................................... 456
Chapter 24. Developing COBOL programs in the mixed AMODE Language Environment.....................467
COBOL programs in AMODE 31 interacting with Java programs in AMODE 64............................... 467
Application calls between COBOL programs in AMODE 31 and Java programs in AMODE 64..467
Building the mixed AMODE COBOL/Java interoperability application .......................................468
Running the mixed AMODE COBOL/Java interoperability program............................................468
Examples for mixed AMODE COBOL/Java interoperability application .....................................469
xii
Specifying CALL . . . RETURNING................................................................................................. 501
Sharing data by using the EXTERNAL clause.................................................................................... 501
Sharing files between programs (external files)............................................................................... 501
Example: using external files....................................................................................................... 502
Accessing main program parameters under z/OS.............................................................................504
Example: accessing main program parameters under z/OS....................................................... 505
xiii
Parsing XML documents encoded in UTF-8.................................................................................558
Handling XML PARSE exceptions.......................................................................................................559
How the XML parser handles errors.............................................................................................561
Handling encoding conflicts......................................................................................................... 562
Terminating XML parsing................................................................................................................... 563
XML PARSE examples........................................................................................................................ 563
Example: parsing a simple document..........................................................................................564
Example: program for processing XML........................................................................................ 564
Example: parsing an XML document that uses namespaces...................................................... 569
Example: parsing an XML document one segment at a time...................................................... 572
Example: parsing XML documents with validation......................................................................574
xiv
Structuring OO applications...............................................................................................................630
Examples: COBOL applications that run using the java command............................................. 631
xv
Choosing static or dynamic calls....................................................................................................... 681
xvi
Processing of INEXIT...............................................................................................................................722
INEXIT parameters............................................................................................................................ 722
Processing of LIBEXIT............................................................................................................................. 723
Processing of LIBEXIT with nested COPY statements......................................................................724
LIBEXIT parameters...........................................................................................................................725
Processing of PRTEXIT............................................................................................................................ 726
PRTEXIT parameters..........................................................................................................................727
Processing of ADEXIT.............................................................................................................................. 728
ADEXIT parameters........................................................................................................................... 728
Processing of MSGEXIT........................................................................................................................... 729
MSGEXIT parameters.........................................................................................................................730
Customizing compiler-message severities........................................................................................731
Example: MSGEXIT user exit............................................................................................................. 733
Error handling for exit modules...............................................................................................................738
Using the EXIT compiler option with CICS, SQL and SQLIMS statements............................................ 740
xvii
Notices..............................................................................................................867
Trademarks.............................................................................................................................................. 868
Glossary............................................................................................................ 871
List of resources................................................................................................ 915
Enterprise COBOL for z/OS...................................................................................................................... 915
Related publications................................................................................................................................915
Index................................................................................................................ 919
xviii
Tables
1. FILE-CONTROL entries..................................................................................................................................6
12. INTDATE(LILIAN) and compatibility of date intrinsic functions and callable services...........................59
13. INTDATE(ANSI) and compatibility of date intrinsic functions and callable services..............................59
17. National group items that are processed with group semantics...........................................................135
18. Encoding and size of alphanumeric, DBCS, and national data.............................................................. 136
19. Summary of file organizations, access modes, and record formats of COBOL files............................. 153
xix
24. VSAM file organization, access mode, and record format..................................................................... 181
28. I/O statements for VSAM relative and indexed files.............................................................................. 187
32. Methods for checking for sort errors with NOFASTSRT......................................................................... 225
46. DISPLAY output with the DISPSIGN(COMPAT) option or the DISPSIGN(SEP) option specified:.........314
47. Setting INVDATA and NUMPROC options when migrating from earlier COBOL versions..................... 327
xx
49. Mapping of removed options to new options......................................................................................... 343
58. Compiler options required for the integrated CICS translator.............................................................. 433
60. TRUNC compiler options recommended for the separate CICS translator.......................................... 436
72. Hexadecimal values of special characters for various EBCDIC CCSIDs............................................... 558
xxi
74. XML events and special registers........................................................................................................... 569
75. XML events and special registers from parsing XML document with an undeclared namespace
prefix.........................................................................................................................................................571
89. Services that convert between jstring references and national data....................................................642
90. Services that convert between jstring references and alphanumeric data...........................................643
97. Reason codes for XML PARSE exceptions that are unique to Enterprise COBOL................................. 707
xxii
99. XML PARSE exceptions that do not allow continuation (for XMLPARSE(COMPAT))............................. 712
118. Actions possible in exit modules for CICS, SQL and SQLIMS statements.......................................... 740
xxiii
124. SYSADATA options record.................................................................................................................... 757
xxiv
Preface
Abbreviated terms
Certain terms are used in a shortened form in this information. Abbreviations for the product names used
most frequently are listed alphabetically in the following table.
Note:
1. IBM Debug for z/OS supersedes IBM Debug for z Systems and IBM Debug Tool for z/OS. Not all
references to IBM Debug for z Systems and IBM Debug Tool for z/OS have been changed in the
COBOL documentation library. It is recommended that you upgrade your debugger to the latest level
in order to have the full range of debugging features available. In some cases, you must upgrade your
debugger to a certain version depending on what level of Enterprise COBOL you are using to create
the COBOL application:
• IBM Debug Tool V13.1 supports Enterprise COBOL V5.1 and earlier versions
• IBM Debug for z Systems V14.0 supports Enterprise COBOL V6.1 and earlier versions
• IBM Debug for z Systems V14.1 supports Enterprise COBOL V6.2 and earlier versions
To find out which IBM debug product best suits
your needs, see https://www.ibm.com/support/knowledgecenter/SSQ2R2_14.2.0/
com.ibm.debug.cg.doc/common/dcompo.html?sc=SSQ2R2_latest.
In addition to these abbreviated terms, the term "85 COBOL Standard" is used to refer to the combination
of the following standards:
• ISO 1989:1985, Programming languages - COBOL
• ISO/IEC 1989/AMD1:1992, Programming languages - COBOL: Intrinsic function module
• ISO/IEC 1989/AMD2:1994, Programming languages - Correction and clarification amendment for
COBOL
• ANSI INCITS 23-1985, Programming Languages - COBOL
• ANSI INCITS 23a-1989, Programming Languages - Intrinsic Function Module for COBOL
• ANSI INCITS 23b-1993, Programming Language - Correction Amendment for COBOL
The term "2002 COBOL Standard" is used to refer to the following standard:
• INCITS/ISO/IEC 1989-2002, Information technology - Programming languages - COBOL
The term "2014 COBOL Standard" is used to refer to the following standard:
• INCITS/ISO/IEC 1989:2014, Information technology - Programming languages, their environments and
system software interfaces - Programming language COBOL
The ISO standards are identical to the American National standards.
Other terms, if not commonly understood, are shown in italics the first time that they appear, and are
listed in the glossary.
xxvi Preface
Language Environment term Enterprise COBOL equivalent
Local data Any non-EXTERNAL data item
Pass parameters directly, by value BY VALUE
Pass parameters indirectly, by reference BY REFERENCE
Pass parameters indirectly, by value BY CONTENT
Routine Program
Scalar Elementary item
required_item
required_item
optional_item
• If 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:
required_item required_choice1
required_choice2
If choosing one of the items is optional, the entire stack appears below the main path:
required_item
optional_choice1
optional_choice2
If one of the items is the default, it appears above the main path and the remaining choices are shown
below:
Preface xxvii
default_choice
required_item
optional_choice
optional_choice
• An arrow returning to the left, above the main line, indicates an item that can be repeated:
required_item repeatable_item
If the repeat arrow contains a comma, you must separate repeated items with a comma:
required_item repeatable_item
• Keywords appear in uppercase (for example, FROM). They must be spelled exactly as shown. Variables
appear in lowercase italics (for example, column-name). They represent user-supplied names or values.
• If punctuation marks, parentheses, arithmetic operators, or other such symbols are shown, you must
enter them as part of the syntax.
xxviii Preface
Summary of changes
This section lists the major changes that have been made to this document for Enterprise COBOL
Version 6 Release 2 and Version 6 Release 2 with PTFs installed. The changes that are described in
this information have an associated cross-reference for your convenience. The latest technical changes
are marked within >| and |< in the HTML version, or marked by vertical bars (|) in the left margin in the
PDF version.
For a complete list of new and improved features in Enterprise COBOL 6.2 and COBOL 6.2 with PTFs
installed, see What is new in Enterprise COBOL for z/OS 6.2 and COBOL 6.2 with PTFs installed in the
Enterprise COBOL for z/OS What's New.
Preface xxix
– PH08642: NUMCHECK: Redundant checks previously added by the NUMCHECK option have been
removed, improving performance, and some checks can be done at compile time. Specifying
NUMCHECK may also cause the compiler to produce some messages at compile time instead of at
run time. (“NUMCHECK” on page 336)
– PH09225: INITCHECK: The INITCHECK option can be specified with OPTIMIZE(0). (“INITCHECK”
on page 323)
– PH11667: NUMCHECK(BIN): NUMCHECK(BIN) will check for binary data items (COMP, COMP-4, and
USAGE BINARY) even when TRUNC(BIN) is in effect. (“NUMCHECK” on page 336)
– PH24340: NUMCHECK(ZON): New suboptions LAXREDEF | STRICTREDEF are added to the
NUMCHECK(ZON) option to control whether the compiler will check and issue warning messages
for redefined items. (“NUMCHECK” on page 336)
– PH24413: INITCHECK: New suboptions LAX | STRICT are added to the INITCHECK option to
control whether the compiler will issue warning messages for data items unless they are initialized on
at least one, or on all, logical paths to a statement. (“INITCHECK” on page 323)
– PH26794: NUMCHECK(BIN): New suboptions TRUNCBIN | NOTRUNCBIN are added to the
NUMCHECK(BIN) option to control whether the compiler will generate the checking code for binary
data items. (“NUMCHECK” on page 336)
– PH28546: A new "CONVERTING" phrase is added to the JSON GENERATE and JSON PARSE
statements so that you can generate and parse JSON boolean values. (Chapter 31, “Producing JSON
output ,” on page 535 and Chapter 30, “Processing JSON input ,” on page 529)
Note that COBOL Runtime LE APAR PH26698 must also be applied on all systems where programs
that make use of this new feature are linked or run.
– PTF UI71111 (No APAR number): New functionality is added to NUMCHECK to check alphanumeric
senders whose contents are being moved to a numeric receiver. For alphanumeric senders whose
contents are being moved to a numeric receiver, the compiler treats the sender as a numeric integer
so NUMCHECK generates an implicit numeric class test for each alphanumeric sender. (“NUMCHECK”
on page 336)
– Runtime APAR PH20569(V2R2/V2R3/V2R4): The included DWARF diagnostic information when
TEST(NOSEPARATE) is in effect can be extracted from the LLA/VLF managed programs. (TEST)
– PH36688: RULES: New suboptions LAXREDEF | NOLAXREDEF are added to the RULES option to
inform users of redefined items with mismatched lengths. (“RULES” on page 350)
– PH36690: OFFSET: The OFFSET option behavior is changed. If there are multiple blocks of
instructions for a single line of COBOL code, multiple entries will be generated for those instructions
in the OFFSET table. (“OFFSET” on page 341)
– PH41362: NUMCHECK(ZON): LAXREDEF|STRICTREDEF is deprecated but is tolerated for
compatibility, and it is replaced by the LAX|STRICT option. (“NUMCHECK” on page 336)
– PH50301: NUMCHECK: The NUMCHECK compiler option is updated to avoid generating runtime
checking code of zoned decimal senders in MOVE statements when the receiver is an alphanumeric
data item and NUMCHECK(ZON(LAX)) is in effect. (“NUMCHECK” on page 336)
• The following compiler option is deprecated:
– PH31500: ZONEDATA: This compiler option is deprecated but tolerated and is automatically mapped
to an equivalent form of the new INVDATA compiler option. (“ZONEDATA” on page 372)
Statement changes
• PI95081: A new LOC(24|31) phrase is added to the ALLOCATE statement to control the location of
dynamic storage that is acquired, which overrides the influence of the DATA compiler option. (“Storage
and its addressability” on page 39)
xxx Preface
Intrinsic function enhancements
• PI97434: Add support for processing national data items with the following intrinsic functions:
– REVERSE
– ULENGTH
– UPOS
– USUBSTR
– UWIDTH
(“Intrinsic functions and national data” on page 127)
If the updated intrinsic functions (REVERSE, ULENGTH, UPOS, USUBSTR, UWIDTH) in the May
compiler PTFs (UI56120, UI56121, UI56122) are used, then the May Runtime PTF UI56043(V2R1)/
UI56042(V2R2)/UI55861(V2R3) must also be applied to Language Environment on all systems where
these programs are linked or run.
• PI99703:
– The following intrinsic functions are added as IBM extensions:
- BIT-OF
- HEX-OF
(“Converting to hexadecimal or bit data (HEX-OF, BIT-OF)” on page 116)
– The following intrinsic functions are added as part of the 2014 COBOL Standard:
- E
- PI
- TRIM
If the new intrinsic functions (BIT-OF, HEX-OF, E, PI, TRIM) in the July compiler PTFs (UI57342,
UI57343, UI57344, UI57345) are used, then the July Runtime PTF UI57304(V2R1)/UI57303(V2R2)/
UI57302(V2R3) must also be applied to Language Environment on all systems where these programs
are linked or run.
• PH02183:
– The following intrinsic functions are added as IBM extensions:
- BIT-TO-CHAR
- HEX-TO-CHAR
(“Converting from hexadecimal or bit data (HEX-TO-CHAR, BIT-TO-CHAR)” on page 117)
– The following intrinsic functions are added as part of the 2014 COBOL Standard:
- ABS
- BYTE-LENGTH (“Finding the length of data items” on page 120)
- EXP
- EXP10
- NUMVAL-F
- SIGN
- TEST-NUMVAL
- TEST-NUMVAL-C
- TEST-NUMVAL-F
If the new intrinsic functions (BIT-TO-CHAR, HEX-TO-CHAR, NUMVAL-F, TEST-NUMVAL, TEST-NUMVAL-
C, TEST-NUMVAL-F) in the September compiler PTFs (UI58632, UI58633, UI58634) are used, then
the September Runtime PTF UI58596(V2R1)/UI58595(V2R2)/UI58603(V2R3) must also be applied to
Language Environment on all systems where these programs are linked or run.
Preface xxxi
COBOL/JNI interface enhancement
Runtime APAR PH37101(V2R3/V2R4): An enhancement is made to assist COBOL programs running in
AMODE 31 to interact with Java™ programs in AMODE 64. (“COBOL programs in AMODE 31 interacting
with Java programs in AMODE 64” on page 467)
Note: IBM SDK, Java Technology Edition V8.0.6.35 (JVM) is needed for this enhancement.
Version 6 Release 2
New statements
• The new JSON PARSE statement converts JSON text to COBOL data formats. (Chapter 30, “Processing
JSON input ,” on page 529)
Debugging changes
• TEST(SEPARATE) supports generating the debug information into side files to control module size
while retaining debugging capability. (“TEST” on page 359)
Listing changes
• Compiler diagnostic messages now appear at the end of the listing, as was the case in COBOL compilers
before Enterprise COBOL V5.
xxxii Preface
• Addition of MD5 signature to program objects and debug data to allow matching of debug data with
executables even if a program is recompiled. (“Example: MD5 signature” on page 413)
• Three new fields are added at the end of PPA4:
– Offset of the first user-defined data item in WORKING-STORAGE.
– Total length of user-defined data items in WORKING-STORAGE.
– Bit to indicate whether there are EXTERNAL data items.
(“Example: Program prolog areas” on page 415)
Usability enhancements
• Improves usability of the compiler in the z/OS UNIX System Services environment with addition of help
information for the cob2 compiler invocation command. (“cob2 syntax and options” on page 277)
Preface xxxiii
xxxiv Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Part 1. Coding your program
related tasks
“Identifying a program” on page 3
“Describing the computing environment” on page 5
“Describing the data” on page 11
“Processing the data” on page 17
“Defining a class” on page 596
“Defining a class instance method” on page 600
“Structuring OO applications” on page 630
Identifying a program
Use the IDENTIFICATION DIVISION to name a program and optionally provide other identifying
information.
You can use the optional AUTHOR, INSTALLATION, DATE-WRITTEN, and DATE-COMPILED paragraphs
for descriptive information about a program. The data you enter in the DATE-COMPILED paragraph is
replaced with the latest compilation date.
IDENTIFICATION DIVISION.
Program-ID. Helloprog.
Author. A. Programmer.
Installation. Computing Laboratories.
Date-Written. 09/04/2017.
Date-Compiled. 09/08/2017.
Use the PROGRAM-ID paragraph to name your program. The program-name that you assign is used in
these ways:
• Other programs use that name to call your program.
• The name appears in the header on each page, except the first, of the program listing that is generated
when you compile the program.
• If you use the NAME compiler option, the name is placed on the NAME binder (linkage-editor) control
statement to identify the object module that the compilation creates.
Tip: Do not use program-names that start with prefixes used by IBM products. If you use program-
names that start with any of the following prefixes, your CALL statements might resolve to IBM library
or compiler routines rather than to your intended program:
– AFB
– AFH
– CBC
– CEE
– CEH
– CEL
– CEQ
– CEU
related tasks
“Changing the header of a source listing” on page 5
“Identifying a program as recursive” on page 4
“Marking a program as callable by containing programs” on page 4
“Setting a program to an initial state” on page 4
related references
Compiler limits (Enterprise COBOL for z/OS Language Reference)
Conventions for program-names (Enterprise COBOL for z/OS Language Reference)
related tasks
“Sharing data in recursive
or multithreaded programs” on page 16
“Making recursive calls” on page 485
related concepts
“Nested programs” on page 483
4 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
• Changed GO TO statements and PERFORM statements are in their initial states.
• Non-EXTERNAL files are closed.
related tasks
“Ending and reentering main programs or subprograms” on page 474
“Making static calls” on page 476
“Making dynamic calls” on page 476
related references
“INITIAL” on page 325
PP 5655-EC6 IBM Enterprise COBOL for z/OS 6.2.0 P170724 Date 09/08/2017 Time 15:05:19
Page 1
The header indicates the compilation platform. You can customize the header on succeeding pages of the
listing by using the compiler-directing TITLE statement.
Notes:
1. If you are using the IBM Enterprise COBOL Value Unit Edition for z/OS product, the header on the first
page of a source listing is the same as that for IBM Enterprise COBOL for z/OS. The product number
will show 5655-EC6 rather than 5697-V61. The 5697-V61 product number for the Value Unit Edition
product is only significant for product ordering purposes and product registration at installation time.
2. If you are using the IBM Enterprise COBOL Developer Trial for z/OS product, the header on the first
page of a source listing will show the product identifier and current release level of the Developer Trial
product.
related references
TITLE statement (Enterprise COBOL for z/OS Language Reference)
related tasks
“Specifying the collating sequence” on page 7
“Defining symbolic characters” on page 8
“Defining a user-defined class” on page 8
“Defining files to the operating
system” on page 8
related references
Sections and paragraphs (Enterprise COBOL for z/OS Language Reference)
1. The SELECT clause chooses a file in the COBOL program to be associated with an external data set.
2. The ASSIGN clause associates the program's name for the file with the external name for the actual data
file. You can define the external name with a DD statement or an environment variable.
3. The ORGANIZATION clause describes the file's organization. For QSAM files, the ORGANIZATION clause is
optional.
4. The ACCESS MODE clause defines the manner in which the records are made available for processing:
sequential, random, or dynamic. For QSAM and line-sequential files, the ACCESS MODE clause is optional.
These files always have sequential organization.
5. For VSAM files, you might have additional statements in the FILE-CONTROL paragraph depending on the
type of VSAM file you use.
related tasks
Chapter 9, “Processing QSAM files,” on page 157
Chapter 10, “Processing VSAM files,” on page 179
6 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Chapter 11, “Processing line-sequential files,” on page 205
“Describing the computing environment” on page 5
related tasks
“Choosing alternate collating
sequences” on page 221
“Comparing national (UTF-16)
data” on page 145
IDENTIFICATION DIVISION.
. . .
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
Source-Computer. IBM-390. Object-Computer. IBM-390
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"
related tasks
“Specifying the collating sequence” on page 7
You can reference the class-name only in a class condition. (This user-defined class is not the same as an
object-oriented class.)
(1)
8 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
//OUTFILE DD DSNAME=MY.OUT171,UNIT=SYSDA,SPACE=(TRK,(50,5))
/*
(1)
export OUTFILE=DSN(MY.OUT171),UNIT(SYSDA),SPACE(TRK,(50,5))
• COBOL code:
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT CARPOOL
ASSIGN TO OUTFILE (1)
ORGANIZATION IS SEQUENTIAL.
. . .
DATA DIVISION.
FILE SECTION.
FD CARPOOL (2)
LABEL RECORD STANDARD
BLOCK CONTAINS 0 CHARACTERS
RECORD CONTAINS 80 CHARACTERS
(1)
The assignment-name in the ASSIGN clause points to the ddname OUTFILE in the DD statement or
the environment variable OUTFILE in the export command:
• //OUTFILE DD DSNAME=OUT171 . . ., or
• export OUTFILE= . . .
(2)
When you specify a file file-name in a FILE-CONTROL entry, you must describe the file in an FD entry:
SELECT CARPOOL
. . .
FD CARPOOL
related tasks
“Optimizing buffer and device space” on page 10
related references
“FILE SECTION entries” on page 12
FILE SECTION (Enterprise COBOL for z/OS Language Reference)
Assume the three possible input files are MASTER1, MASTER2, and MASTER3. Before running the program,
code one of the following DD statements in the job step that calls for program execution, or issue one of
the following export commands from the same shell from which you run the program:
//MASTERA DD DSNAME=MY.MASTER1,. . .
export MASTERA=DSN(MY.MASTER1),. . .
//MASTERA DD DSNAME=MY.MASTER2,. . .
export MASTERA=DSN(MY.MASTER2),. . .
//MASTERA DD DSNAME=MY.MASTER3,. . .
export MASTERA=DSN(MY.MASTER3),. . .
Any reference in the program to MASTER will therefore be a reference to the file that is currently assigned
to the ddname or environment-variable name MASTERA.
Notice that in this example, you cannot use the PATH(path) form of the export command to reference a
line-sequential file in the z/OS UNIX file system, because you cannot specify an organization field (S- or
AS-) with a line-sequential file.
10 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
– The program is compiled with the NOAWO compiler option
Therefore, programs should not reference data directly in the file's record area. Instead, when a file
record is read in, it should be read into a data item defined in WORKING-STORAGE or if read into the
record area, should be immediately moved to a data item in WORKING-STORAGE for use by the program.
For example:
FD MY-INPUT-FILE
LABEL RECORDS ARE STANDARD
RECORDING MODE IS V
BLOCK CONTAINS 0 RECORDS
DATA RECORD IS IN-RECORD-AREA.
01 IN-RECORD-AREA PIC X(100).
WORKING-STORAGE.
01 WS-IN-RECORD-AREA PIC X(100).
PROCEDURE DIVISION.
...
READ MY-INPUT-FILE INTO WS-IN-RECORD-AREA.
related references
“AWO” on page 302
related concepts
“Comparison of WORKING-STORAGE
and LOCAL-STORAGE” on page 14
related tasks
“Using data in input and output operations” on page 11
“Using data from another program” on page 16
related references
Compiler limits (Enterprise COBOL for z/OS Language Reference)
Programs in the same run unit can share, or have access to, common files. The method for doing this
depends on whether the programs are part of a nested (contained) structure or are separately compiled
(including programs compiled as part of a batch sequence).
You can use the EXTERNAL clause 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.
You can use the GLOBAL clause 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.
related concepts
“Nested programs” on page 483
related tasks
“Sharing files between programs
(external files)” on page 501
related references
“FILE SECTION entries” on page 12
12 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 2. FILE SECTION entries (continued)
Clause To define Notes
BLOCK CONTAINS Size of physical records If the CHARACTERS phrase is specified, size
indicates the number of bytes in a record
regardless of the USAGE of the data items in the
record.
QSAM: If provided, must match information on JCL
or data-set label. If specified as BLOCK CONTAINS
0, or not provided, the system determines the
optimal block size for you.
Line sequential: Can be specified to control
buffering for WRITE statements.
VSAM: Syntax-checked, but has no effect on
execution.
RECORD Size of logical records (fixed Integer size indicates the number of bytes in a
CONTAINS n length) record regardless of the USAGE of the data items in
the record. If the clause is provided, it must match
information on JCL or data-set label. If n is equal to
0, LRECL must be coded on JCL or data-set label.
RECORD IS Size of logical records Integer size or sizes, if specified, indicate the
VARYING (variable length) number of bytes in a record regardless of the
USAGE of the data items in the record. If the
clause is provided, it must match information on
JCL or data-set label; compiler checks that record
descriptions match.
RECORD Size of logical records The integer sizes indicate the number of bytes
CONTAINS n TO m (variable length) in a record regardless of the USAGE of the data
items in the record. If the clause is provided, it
must match information on JCL or data-set label;
compiler checks that record descriptions match.
LABEL RECORDS Labels for QSAM files VSAM: Handled as comments
STANDARD Labels exist QSAM: Handled as comments
OMITTED Labels do not exist QSAM: Handled as comments
data-name Labels defined by the user QSAM: Allowed for (optional) tape or disk
VALUE OF An item in the label records Comments only
associated with file
DATA RECORDS Names of records associated Comments only
with file
LINAGE Depth of logical page QSAM only
CODE-SET ASCII or EBCDIC files QSAM only.
When an ASCII file is identified with the CODE-
SET clause, the corresponding DD statement
might need to have DCB=(OPTCD=Q. . .) or
DCB=(RECFM=D. . .) coded if the file was not
created using VS COBOL II, COBOL for OS/390® &
VM, or IBM Enterprise COBOL for z/OS.
related references
FILE SECTION (Enterprise COBOL for z/OS Language Reference)
A separate copy of LOCAL-STORAGE data is allocated for each call of a program or invocation of a
method, and is freed on return from the program or method. If you specify a VALUE clause for a LOCAL-
STORAGE item, the item is initialized to that value on each call or invocation. If a VALUE clause is not
specified, the initial value of the item is undefined.
Threading: Each invocation of a program that runs simultaneously on multiple threads shares access to a
single copy of WORKING-STORAGE data. Each invocation has a separate copy of LOCAL-STORAGE data.
“Example: storage sections” on page 14
related tasks
“Ending and reentering main programs or subprograms” on page 474
Chapter 28, “Preparing COBOL programs
for multithreading,” on page 517
“WORKING-STORAGE SECTION for defining class instance data” on page 599
related references
WORKING-STORAGE SECTION (Enterprise COBOL for z/OS Language Reference)
LOCAL-STORAGE SECTION (Enterprise COBOL for z/OS Language Reference)
CBL pgmn(lu)
*********************************
* Recursive Program - Factorials
*********************************
IDENTIFICATION DIVISION.
Program-Id. factorial recursive.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 numb pic 9(4) value 5.
01 fact pic 9(8) value 0.
14 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
LOCAL-STORAGE SECTION.
01 num pic 9(4).
PROCEDURE DIVISION.
move numb to num.
if numb = 0
move 1 to fact
else
subtract 1 from numb
call 'factorial'
multiply num by fact
end-if.
0000! = 00000001
0001! = 00000001
0002! = 00000002
0003! = 00000006
0004! = 00000024
0005! = 00000120
The following tables show the changing values of the data items in LOCAL-STORAGE and WORKING-
STORAGE in the successive recursive calls of the program, and in the ensuing gobacks. During the
gobacks, fact progressively accumulates the value of 5! (five factorial).
Recursive calls Value for num in Value for numb in Value for fact in
LOCAL-STORAGE WORKING-STORAGE WORKING-STORAGE
Main 5 5 0
1 4 4 0
2 3 3 0
3 2 2 0
4 1 1 0
5 0 0 0
Gobacks Value for num in Value for numb in Value for fact in
LOCAL-STORAGE WORKING-STORAGE WORKING-STORAGE
5 0 0 1
4 1 0 1
3 2 0 2
2 3 0 6
1 4 0 24
Main 5 0 120
related concepts
“Comparison of WORKING-STORAGE
and LOCAL-STORAGE” on page 14
related tasks
“Sharing data in separately compiled programs” on page 16
“Sharing data in nested programs” on page 16
“Sharing data in recursive
or multithreaded programs” on page 16
“Passing data” on page 491
related tasks
“Passing data” on page 491
“Coding the LINKAGE SECTION” on page 495
related concepts
“Nested programs” on page 483
related concepts
“Multithreading” on page 517
related tasks
“Making recursive calls” on page 485
“Processing files with multithreading” on page 520
16 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related references
“THREAD” on page 363
SET statement (Enterprise COBOL for z/OS Language Reference)
PROCEDURE DIVISION.
You can code the division header to receive parameters by using the USING phrase, or to return a value by
using the RETURNING phrase.
To receive an argument that was passed by reference (the default) or by content, code the division header
for a program in either of these ways:
You can also combine USING and RETURNING in a PROCEDURE DIVISION header:
related concepts
“How logic is divided
in the PROCEDURE DIVISION” on page 18
related tasks
“Coding the LINKAGE SECTION” on page 495
“Coding the PROCEDURE DIVISION
for passing arguments” on page 496
“Using PROCEDURE DIVISION RETURNING . . .” on page 500
“Eliminating repetitive coding” on page 683
related references
The procedure division header (Enterprise COBOL for z/OS Language Reference)
The USING phrase (Enterprise COBOL for z/OS Language Reference)
CALL statement (Enterprise COBOL for z/OS Language Reference)
related concepts
“Compiler-directing statements” on page 19
“Scope terminators” on page 20
“Imperative statements” on page 18
“Conditional statements” on page 18
“Declaratives” on page 21
related references
PROCEDURE DIVISION structure
(Enterprise COBOL for z/OS Language Reference)
Imperative statements
An imperative statement (such as ADD, MOVE, INVOKE, or CLOSE) indicates an unconditional action to be
taken.
You can end an imperative statement with an implicit or explicit scope terminator.
A conditional statement that ends with an explicit scope terminator becomes an imperative statement
called a delimited scope statement. Only imperative statements (or delimited scope statements) can be
nested.
related concepts
“Conditional statements” on page 18
“Scope terminators” on page 20
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.
You can end a conditional statement with an implicit or explicit scope terminator. If you end a conditional
statement explicitly, it becomes a delimited scope statement (which is an imperative statement).
18 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
You can use a delimited scope statement in these ways:
• To delimit the range of operation for a COBOL conditional statement and to explicitly show the levels of
nesting
For example, use an END-IF phrase 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:
An explicit scope terminator is required for the inline PERFORM statement, but it is not valid for the
out-of-line PERFORM statement.
For additional program control, you can use the NOT phrase with conditional statements. For example, you
can provide instructions to be performed 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. Nested statements must be imperative statements (or delimited
scope statements) and must follow the rules for imperative statements.
The following statements are examples of conditional statements if they are coded without scope
terminators:
• Arithmetic statement with ON SIZE ERROR
• Data-manipulation statements with ON OVERFLOW
• CALL statements with ON OVERFLOW
• I/O statements with INVALID KEY, AT END, or AT END-OF-PAGE
• RETURN with AT END
related concepts
“Imperative statements” on page 18
“Scope terminators” on page 20
related tasks
“Selecting program actions” on page 91
related references
Conditional statements (Enterprise COBOL for z/OS Language Reference)
Compiler-directing statements
A compiler-directing statement causes the compiler to take specific action about the program structure,
COPY processing, listing control, or control flow.
A compiler-directing statement is not part of the program logic.
related references
Chapter 18, “Compiler-directing statements,” on page 377
Compiler-directing statements (Enterprise COBOL for z/OS Language Reference)
IF ITEM = "A"
DISPLAY "THE VALUE OF ITEM IS " ITEM
ADD 1 TO TOTAL
MOVE "C" TO ITEM
DISPLAY "THE VALUE OF ITEM IS NOW " ITEM.
IF ITEM = "B"
ADD 2 TO TOTAL.
IF ITEM = "A"
DISPLAY "THE VALUE OF ITEM IS " ITEM
ADD 1 TO TOTAL
MOVE "C" TO ITEM
DISPLAY "THE VALUE OF ITEM IS NOW " ITEM
END-IF
IF ITEM = "B"
ADD 2 TO TOTAL
END-IF
If you use implicit terminators, the end of statements can be unclear. 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 MOVE statement and the DISPLAY statement after it are performed regardless of the value of ITEM,
despite what the indentation indicates, because the first period terminates the IF statement.
For improved program clarity and to avoid unintentional ending of statements, use explicit scope
terminators, especially within paragraphs. Use implicit scope terminators only at the end of a paragraph
or the end of a program.
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
20 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
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
related concepts
“Conditional statements” on page 18
“Imperative statements” on page 18
Declaratives
Declaratives provide one or more special-purpose sections that are executed when an exception
condition occurs.
Start each declarative section with a USE statement that identifies the function of the section. In the
procedures, specify the actions to be taken when the condition occurs.
related tasks
“Finding and handling input-output
errors” on page 383
related references
Declaratives (Enterprise COBOL for z/OS Language Reference)
This information is intended to help non-COBOL programmers relate terms for data used in other
programming languages to COBOL terms. It introduces COBOL fundamentals for variables, structures,
literals, and constants; assigning and displaying values; intrinsic (built-in) functions, and tables (arrays)
and pointers.
related concepts
“Storage and its addressability” on page 39
related tasks
“Using variables, structures, literals, and constants” on page 23
“Assigning values to data items” on page 27
“Displaying values on a
screen or in a file (DISPLAY)” on page 35
“Using intrinsic functions (built-in functions)” on page 38
“Using tables (arrays) and pointers” on page 39
Chapter 7, “Processing data in an international
environment,” on page 123
related tasks
“Using variables” on page 23
“Using data items and group
items” on page 24
“Using literals” on page 25
“Using constants” on page 26
“Using figurative constants” on page 26
related references
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
Using variables
A variable is a data item whose value can change during a program. The value is restricted, however, to
the data type that you define when you specify a name and a length for the data item.
For example, if a customer name is an alphanumeric data item in your program, you could define and use
the customer name as shown below:
Data Division.
01 Customer-Name Pic X(20).
01 Original-Customer-Name Pic X(20).
. . .
Procedure Division.
Move Customer-Name to Original-Customer-Name
. . .
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Using national data (Unicode)
in COBOL” on page 129
related references
“NSYMBOL” on page 335
“Storage of character data” on page 136
PICTURE clause (Enterprise COBOL for z/OS Language Reference)
Data Division.
File Section.
FD Customer-File
Record Contains 45 Characters.
01 Customer-Record.
05 Customer-Name.
10 Last-Name Pic x(17).
10 Filler Pic x.
10 Initials Pic xx.
05 Part-Order.
10 Part-Name Pic x(15).
10 Part-Color Pic x(10).
Working-Storage Section.
01 Orig-Customer-Name.
05 Surname Pic x(17).
05 Initials Pic x(3).
01 Inventory-Part-Name Pic x(15).
. . .
Procedure Division.
Move Customer-Name to Orig-Customer-Name
Move Part-Name to Inventory-Part-Name
. . .
You could instead define Customer-Record as a national group item that is composed of two
subordinate national group items by changing the declarations in the DATA DIVISION as shown below.
National group items behave in the same way as elementary category national data items in most
operations. The GROUP-USAGE NATIONAL clause indicates that a group item and any group items
subordinate to it are national groups. Subordinate elementary items in a national group must be explicitly
or implicitly described as USAGE NATIONAL.
Data Division.
File Section.
FD Customer-File
Record Contains 90 Characters.
01 Customer-Record Group-Usage National.
24 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
05 Customer-Name.
10 Last-Name Pic n(17).
10 Filler Pic n.
10 Initials Pic nn.
05 Part-Order.
10 Part-Name Pic n(15).
10 Part-Color Pic n(10).
Working-Storage Section.
01 Orig-Customer-Name Group-Usage National.
05 Surname Pic n(17).
05 Initials Pic n(3).
01 Inventory-Part-Name Pic n(15) Usage National.
. . .
Procedure Division.
Move Customer-Name to Orig-Customer-Name
Move Part-Name to Inventory-Part-Name
. . .
In the example above, the group items could instead specify the USAGE NATIONAL clause at the group
level. A USAGE clause at the group level applies to each elementary data item in a group (and thus serves
as a convenient shorthand notation). However, a group that specifies the USAGE NATIONAL clause is not
a national group despite the representation of the elementary items within the group. Groups that specify
the USAGE clause are alphanumeric groups and behave in many operations, such as moves and compares,
like elementary data items of USAGE DISPLAY (except that no editing or conversion of data occurs).
related concepts
“Unicode and the encoding
of language characters” on page 129
“National groups” on page 132
related tasks
“Using national data (Unicode)
in COBOL” on page 129
“Using national groups” on page 133
related references
“FILE SECTION entries” on page 12
“Storage of character data” on page 136
Classes and categories of group items
(Enterprise COBOL for z/OS Language Reference)
PICTURE clause (Enterprise COBOL for z/OS Language Reference)
MOVE statement (Enterprise COBOL for z/OS Language Reference)
USAGE clause (Enterprise COBOL for z/OS Language Reference)
Using literals
A literal is a character string whose value is given by the characters themselves. If you know the value
you want a data item to have, you can use a literal representation of the data value in the PROCEDURE
DIVISION.
You do not need to define a data item for the value nor refer to it by using a data-name. For example, you
can prepare an error message for an output file by moving an alphanumeric literal:
You can compare a data item to a specific integer value by using a numeric literal. In the example below,
"Name is not valid" is an alphanumeric literal, and 03519 is a numeric literal:
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Using national literals” on page 130
“Using DBCS literals” on page 148
related references
“NSYMBOL” on page 335
Literals (Enterprise COBOL for z/OS Language Reference)
Using constants
A constant is a data item that has only one value. COBOL does not define a construct for constants.
However, you can define a data item with an initial value by coding a VALUE clause in the data description
(instead of coding an INITIALIZE statement).
Data Division.
01 Report-Header pic x(50) value "Company Sales Report".
. . .
01 Interest pic 9v9999 value 1.0265.
The example above initializes an alphanumeric and a numeric data item. You can likewise use a VALUE
clause in defining a national or DBCS constant.
related tasks
“Using national data (Unicode)
in COBOL” on page 129
“Coding for use of DBCS support” on page 147
related tasks
“Using national-character
figurative constants” on page 131
“Coding for use of DBCS support” on page 147
related references
Figurative constants (Enterprise COBOL for z/OS Language Reference)
26 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Assigning values to data items
After you have defined a data item, you can assign a value to it at any time. Assignment takes many forms
in COBOL, depending on what you want to do.
related tasks
“Initializing a structure
(INITIALIZE)” on page 31
“Assigning values to elementary
data items (MOVE)” on page 32
“Assigning values to group
data items (MOVE)” on page 33
“Assigning input from a
screen or file (ACCEPT)” on page 35
“Joining data items (STRING)” on page 103
“Splitting data items (UNSTRING)” on page 105
“Assigning arithmetic results
An INITIALIZE statement is functionally equivalent to one or more MOVE statements. The related tasks
about initializing show how you can use an INITIALIZE statement on a group item to conveniently
initialize all the subordinate data items that are in a given data category.
Initializing a data item to blanks or zeros:
INITIALIZE identifier-1
28 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
. . .
INITIALIZE ANJUST
REPLACING ALPHANUMERIC DATA BY ALPHABETIC-1
related tasks
“Initializing a structure
30 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
(INITIALIZE)” on page 31
“Initializing a table (INITIALIZE)” on page 73
“Defining numeric data” on page 43
related references
“NSYMBOL” on page 335
01 TRANSACTION-OUT.
05 TRANSACTION-CODE PIC X.
05 PART-NUMBER PIC 9(6).
05 TRANSACTION-QUANTITY PIC 9(5).
05 PRICE-FIELDS.
10 UNIT-PRICE PIC 9(5)V9(2).
10 DISCOUNT PIC V9(2).
10 SALES-PRICE PIC 9(5)V9(2).
. . .
INITIALIZE TRANSACTION-OUT
You can likewise reset the values of all the subordinate data items in a national group item by applying the
INITIALIZE statement to that group item. The following structure is similar to the preceding structure,
but instead uses Unicode UTF-16 data:
Regardless of the previous contents of the transaction record, after the INITIALIZE statement above is
executed:
• TRANSACTION-CODE contains NX"0020" (a national space).
• Each of the remaining 27 national character positions of TRANSACTION-OUT contains NX"0030" (a
national-decimal zero).
related concepts
“National groups” on page 132
related tasks
“Initializing a table (INITIALIZE)” on page 73
“Using national groups” on page 133
related references
INITIALIZE statement (Enterprise COBOL for z/OS Language Reference)
You can move an alphabetic, alphanumeric, alphanumeric-edited, DBCS, integer, or numeric-edited data
item to a category national or national-edited data item; the sending item is converted. You can move
a national data item to a category national or national-edited data item. If the content of a category
national data item has a numeric value, you can move that item to a numeric, numeric-edited, external
floating-point, or internal floating-point data item. You can move a national-edited data item only to a
category national data item or another national-edited data item. Padding or truncation might occur.
For complete details about elementary moves, see the related reference below about the MOVE
statement.
The following example shows an alphanumeric data item in the Greek language that is moved to a
national data item:
CBL CODEPAGE(00875)
. . .
01 Data-in-Unicode Pic N(100) usage national.
01 Data-in-Greek Pic X(100).
. . .
Read Greek-file into Data-in-Greek
Move Data-in-Greek to Data-in-Unicode
32 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Assigning values to group
data items (MOVE)” on page 33
“Converting to or from national (Unicode) representation” on page 136
related references
“CODEPAGE” on page 304
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
MOVE statement (Enterprise COBOL for z/OS Language Reference)
You can move a national group item (a data item that is described with the GROUP-USAGE NATIONAL
clause) to another national group item. The compiler processes the move as though each national group
item were an elementary item of category national, that is, as if each item were described as PIC N(m),
where m is the length of that item in national character positions.
You can move an alphanumeric group item to an alphanumeric group item or to a national group item.
You can also move a national group item to an alphanumeric group item. The compiler performs such
moves as group moves, that is, without consideration of the individual elementary items in the sending
or receiving group, and without conversion of the sending data item. Be sure that the subordinate
data descriptions in the sending and receiving group items are compatible. The moves occur even if a
destructive overlap could occur at run time.
You can code the CORRESPONDING phrase in a MOVE statement to move subordinate elementary items
from one group item to the identically named corresponding subordinate elementary items in another
group item:
01 Group-X.
02 T-Code Pic X Value "A".
02 Month Pic 99 Value 04.
02 State Pic XX Value "CA".
02 Filler PIC X.
01 Group-N Group-Usage National.
02 State Pic NN.
02 Month Pic 99.
02 Filler Pic N.
02 Total Pic 999.
. . .
MOVE CORR Group-X TO Group-N
In the example above, State and Month within Group-N receive the values in national representation
of State and Month, respectively, from Group-X. The other data items in Group-N are unchanged.
(Filler items in a receiving group item are unchanged by a MOVE CORRESPONDING statement.)
In a MOVE CORRESPONDING statement, sending and receiving group items are treated as group items,
not as elementary data items; group semantics apply. That is, the elementary data items within each
group are recognized, and the results are the same as if each pair of corresponding data items were
referenced in a separate MOVE statement. Data conversions are performed according to the rules for the
MOVE statement as specified in the related reference below. For details about which types of elementary
data items correspond, see the related reference about the CORRESPONDING phrase.
related concepts
“Unicode and the encoding
of language characters” on page 129
“National groups” on page 132
related references
Classes and categories of group items
(Enterprise COBOL for z/OS Language Reference)
MOVE statement (Enterprise COBOL for z/OS Language Reference)
CORRESPONDING phrase (Enterprise COBOL for z/OS Language Reference)
Move w to z
Compute z = w
In the example above, the two statements in most cases have the same effect. The MOVE statement
however carries out the assignment with truncation. You can use the DIAGTRUNC compiler option to
request that the compiler issue a warning for MOVE statements that might truncate numeric receivers.
When significant left-order digits would be lost in execution, the COMPUTE statement can detect the
condition and allow you to handle it. If 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 you do not specify
the ON SIZE ERROR phrase, the assignment is carried out with truncation. There is no ON SIZE ERROR
support for the MOVE statement.
You can also use the COMPUTE statement to assign the result of an arithmetic expression or intrinsic
function to a data item. For example:
Compute z = y + (x ** 3)
Compute x = Function Max(x y z)
You can assign the results of date, time, mathematical, and other calculations to data items by using
Language Environment callable services. Language Environment services are available through a standard
COBOL CALL statement, and the values they return are passed in the parameters of the CALL statement.
For example, you can call the Language Environment service CEESIABS to find the absolute value of a
data item by coding the following statement:
As a result of this call, data item Result is assigned the absolute value of the value in data item
Arg; data item Feedback-code contains the return code that indicates whether the service completed
successfully. You have to define all the data items in the DATA DIVISION using the correct descriptions
according to the requirements of the particular callable service. For the example above, the data items
could be defined as follows:
related references
“DIAGTRUNC” on page 312
34 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Intrinsic functions (Enterprise COBOL for z/OS Language Reference)
Language Environment Programming Reference (Callable services)
Environment Division.
Configuration Section.
Special-Names.
Console is Names-Input.
. . .
Accept Customer-Name From Names-Input
To read from a file instead of the screen, make the following change:
• Change Console to device, where device is any valid system device (for example, SYSIN). For example:
SYSIN is Names-Input
device can be a ddname that references a z/OS UNIX file system path. If this ddname is not defined and
your program is running in the z/OS UNIX environment, stdin is the input source. If this ddname is not
defined and your program is not running in the z/OS UNIX environment, the ACCEPT statement fails.
When you use the ACCEPT statement, you can assign a value to an alphanumeric or national group item,
or to an elementary data item that has USAGE DISPLAY, USAGE DISPLAY-1, or USAGE NATIONAL.
When you assign a value to a USAGE NATIONAL data item, input data from the console is converted
from the EBCDIC code page specified in the CODEPAGE compiler option to national (Unicode UTF-16)
representation. This is the only case where conversion of national data is done when you use the ACCEPT
statement. Conversion is done in this case because the input is known to be coming from a screen.
To have conversion done when the input data is from any other device, use the NATIONAL-OF intrinsic
function.
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Converting alphanumeric
or DBCS to national (NATIONAL-OF)” on page 138
related references
“CODEPAGE” on page 304
ACCEPT statement (Enterprise COBOL for z/OS Language Reference)
SPECIAL-NAMES paragraph (Enterprise COBOL for z/OS Language Reference)
Display "No entry for surname '" Customer-Name "' found in the file.".
To write data to a destination other than the system logical output device, use the UPON phrase with a
destination other than SYSOUT. For example, the following statement writes to the file that is specified in
the SYSPUNCH DD statement:
You can specify a file in the z/OS UNIX file system by using the SYSPUNCH DD statement. For example,
the following definition causes DISPLAY output to be written to the file /u/userid/cobol/demo.lst:
//SYSPUNCH DD PATH='/u/userid/cobol/demo.lst',
// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),PATHMODE=SIRWXU,
// FILEDATA=TEXT
The following statement writes to the job log or console and to the TSO screen if you are running under
TSO:
When you display the value of a USAGE NATIONAL data item to the console, the data item is converted
from Unicode (UTF-16) representation to EBCDIC based on the value of the CODEPAGE option. This is the
only case in which conversion of national data is done when you use the DISPLAY statement. Conversion
is done in this case because the output is known to be directed to a screen.
To have a national data item be converted when you direct output to a different device, use the DISPLAY-
OF intrinsic function, as in the following example:
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Displaying data on the
system logical output device” on page 36
“Using WITH NO ADVANCING” on page 37
“Converting national to
alphanumeric (DISPLAY-OF)” on page 138
“Coding COBOL programs to run under CICS” on page 429
related references
“CODEPAGE” on page 304
DISPLAY statement (Enterprise COBOL for z/OS Language Reference)
36 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
The output is directed to the ddname that you specify in the OUTDD compiler option. You can specify a file
in the z/OS UNIX file system with this ddname.
If the OUTDD ddname is not allocated and you are not running in the z/OS UNIX environment, a default
DD of SYSOUT=* is allocated. If the OUTDD ddname is not allocated and you are running in the z/OS UNIX
environment, the _IGZ_SYSOUT environment variable is used as follows:
Undefined or set to stdout
Output is routed to stdout (file descriptor 1).
Set to stderr
Output is routed to stderr (file descriptor 2).
Otherwise (set to something other than stdout or stderr)
The DISPLAY statement fails; a severity-3 Language Environment condition is raised.
When DISPLAY output is routed to stdout or stderr, the output is not subdivided into records. The output
is written as a single stream of characters without line breaks.
If OUTDD and the Language Environment runtime option MSGFILE specify the same ddname, both
DISPLAY output and Language Environment runtime diagnostics are routed to the Language Environment
message file.
related tasks
“Setting and accessing environment variables” on page 460
related references
“OUTDD” on page 344
DISPLAY statement (Enterprise COBOL for z/OS Language Reference)
DISPLAY "ABC"
DISPLAY "CDEF" WITH NO ADVANCING
DISPLAY "GHIJK" WITH NO ADVANCING
DISPLAY "LMNOPQ"
DISPLAY "RSTUVWX"
If you code the statements above, the result sent to the output device is:
ABC
CDEF
+GHIJK
+LMNOPQ
RSTUVMX
The output that is printed depends on how the output device interprets printer control characters.
If you do not specify the WITH NO ADVANCING phrase and the output is going to stdout or stderr, a
newline character is appended to the end of the stream.
related references
DISPLAY statement (Enterprise COBOL for z/OS Language Reference)
A function-identifier represents both the invocation of the function and the data value returned by the
function. Because it actually represents a data item, you can use a function-identifier in most places in the
PROCEDURE DIVISION where a data item that has the attributes of the returned value can be used.
The COBOL word function is a reserved word, but the function-names are not reserved. You can use
them in other contexts, such as for the name of a data item. For example, you could use Sqrt to invoke an
intrinsic function and to name a data item in your program:
Working-Storage Section.
01 x Pic 99 value 2.
01 y Pic 99 value 4.
01 z Pic 99 value 0.
01 Sqrt Pic 99 value 0.
. . .
Compute Sqrt = 16 ** .5
Compute z = x + Function Sqrt(y)
. . .
A function-identifier represents a value that is of one of these types: alphanumeric, national, numeric,
or integer. You can include a substring specification (reference modifier) in a function-identifier for
alphanumeric or national functions. Numeric intrinsic functions are further classified according to the
type of numbers they return.
The functions MAX and MIN can return either type of value depending on the type of arguments you
supply.
Functions can reference other functions as arguments provided that the results of the nested functions
meet the requirements for the arguments of the outer function. For example, Function Sqrt(5)
returns a numeric value. Thus, the three arguments to the MAX function below are all numeric, which is an
allowable argument type for this function:
related tasks
“Processing table items
using intrinsic functions” on page 87
“Converting data items (intrinsic functions)” on page 113
“Evaluating data items (intrinsic functions)” on page 117
38 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Using tables (arrays) and pointers
In COBOL, arrays are called tables. A table is a set of logically consecutive data items that you define in
the DATA DIVISION by using the OCCURS clause.
Pointers are data items that contain virtual storage addresses. You define them either explicitly with the
USAGE IS POINTER clause in the DATA DIVISION or implicitly as ADDRESS OF special registers.
You can perform the following operations with pointer data items:
• Pass them between programs by using the CALL . . . BY REFERENCE statement.
• Set a pointer to allocated storage or free storage by using the ALLOCATE and FREE statements.
• Move them to other pointers by using the SET statement.
• Compare them to other pointers for equality by using a relation condition.
• Initialize them to contain an invalid address by using VALUE IS NULL.
Use pointer data items to:
• Accomplish limited base addressing, particularly if you want to pass and receive addresses of a record
area that is defined with OCCURS DEPENDING ON and is therefore variably located.
• Handle a chained list.
related tasks
“Defining a table (OCCURS)” on page 67
“Using procedure and function
pointers” on page 485
40 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
in addressing mode 31. COBOL programs that run with addressing mode 24 must be linked with the
binder option RMODE(24).
Table 4. Effect of RMODE and RENT compiler options on the RMODE attribute
RMODE compiler option RENT compiler option RMODE attribute
RMODE(AUTO) RENT RMODE ANY
RMODE(AUTO) NORENT RMODE 24
RMODE(24) RENT or NORENT RMODE 24
RMODE(ANY) RENT RMODE ANY
RMODE(ANY) NORENT Compiler option conflict.
If the NORENT option is
specified, the RMODE(24)
or RMODE(AUTO) compiler
option must be specified.
Link-edit considerations: When the object code that COBOL generates has an attribute of RMODE 24, you
must link-edit it with RMODE 24. When the object code that COBOL generates has an attribute of RMODE
ANY, you can link-edit it with RMODE ANY or RMODE 24.
related concepts
“AMODE switching” on page 478
AMODE considerations for heap storage
(Language Environment Programming Guide)
related tasks
Chapter 25, “Using subprograms,” on page 473
Chapter 26, “Sharing data,” on page 491
related references
“Allocation of buffers for QSAM files” on page 176
“Allocation of record areas for VSAM files” on page 201
“DATA” on page 310
“RENT” on page 348
“RMODE” on page 349
“Performance-related compiler options” on page 676
ALLOCATE statement (Enterprise COBOL for z/OS Language Reference)
HEAP, STACK, ALL31 (Language Environment Programming Reference)
MVS Program Management: User's Guide and Reference
42 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Chapter 3. Working with numbers and arithmetic
In general, you can view COBOL numeric data as a series of decimal digit positions. However, numeric
items can also have special properties such as an arithmetic sign or a currency sign.
To define, display, and store numeric data so that you can perform arithmetic operations efficiently:
• Use the PICTURE clause and the characters 9, +, -, P, S, and V to define numeric data.
• Use the PICTURE clause and editing characters (such as Z, comma, and period) along with MOVE and
DISPLAY statements to display numeric data.
• Use the USAGE clause with various formats to control how numeric data is stored.
• Use the numeric class test to validate that data values are appropriate.
• Use ADD, SUBTRACT, MULTIPLY, DIVIDE, and COMPUTE statements to perform arithmetic.
• Use the CURRENCY SIGN clause and appropriate PICTURE characters to designate the currency you
want.
related tasks
“Defining numeric data” on page 43
“Displaying numeric data” on page 45
“Controlling how numeric data is stored” on page 46
“Checking for incompatible data (numeric class test)” on page 53
“Performing arithmetic” on page 55
“Using currency signs” on page 64
You can similarly define numeric data items to hold national characters (UTF-16). For example, Count-n
below is an external decimal data item that has USAGE NATIONAL (a national decimal item):
You can code up to 18 digits in the PICTURE clause when you compile using the default compiler option
ARITH(COMPAT) (referred to as compatibility mode). When you compile using ARITH(EXTEND) (referred
to as extended mode), you can code up to 31 digits in the PICTURE clause.
Other characters of special significance that you can code are:
P
Indicates leading or trailing zeros
S
Indicates a sign, positive or negative
V
Implies a decimal point
The field can therefore hold a positive or a negative value. The v indicates the position of an implied
decimal point, but does not contribute to the size of the item because it does not require a storage
position. An s usually does not contribute to the size of a numeric item, because by default s does not
require a storage position.
However, if you plan to port your program or data to a different machine, you might want to code the sign
for a zoned decimal data item as a separate position in storage. In the following case, the sign takes 1
byte:
This coding ensures that the convention your machine uses for storing a nonseparate sign will not cause
unexpected results on a machine that uses a different convention.
Separate signs are also preferable for zoned decimal data items that will be printed or displayed.
Separate signs are required for national decimal data items that are signed. The sign takes 2 bytes of
storage, as in the following example:
You cannot use the PICTURE clause with internal floating-point data (COMP-1 or COMP-2). However, you
can use the VALUE clause to provide an initial value for an internal floating-point literal:
For information about external floating-point data, see the examples referenced below and the related
concept about formats for numeric data.
“Examples: numeric data and internal representation” on page 50
related concepts
“Formats for numeric
data” on page 47
Appendix A, “Intermediate results and arithmetic precision,” on page 691
related tasks
“Displaying numeric data” on page 45
“Controlling how numeric data is stored” on page 46
“Performing arithmetic” on page 55
“Defining national numeric
data items” on page 132
related references
“Sign representation of zoned and packed-decimal data” on page 53
“Storage of character data” on page 136
“ARITH” on page 300
“NUMPROC” on page 340
SIGN clause (Enterprise COBOL for z/OS Language Reference)
44 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Displaying numeric data
You can define numeric items with certain editing symbols (such as decimal points, commas, dollar signs,
and debit or credit signs) to make the items easier to read and understand when you display or print
them.
For example, in the code below, Edited-price is a numeric-edited item that has USAGE DISPLAY. (You
can specify the clause USAGE IS DISPLAY for numeric-edited items; however, it is implied. It means
that the items are stored in character format.)
If the contents of Price are 0150099 (representing the value 1,500.99), $ 1,500.99 is displayed when
you run the code. The z in the PICTURE clause of Edited-price indicates the suppression of leading
zeros.
You can define numeric-edited data items to hold national (UTF-16) characters instead of alphanumeric
characters. To do so, define the numeric-edited items as USAGE NATIONAL. The effect of the editing
symbols is the same for numeric-edited items that have USAGE NATIONAL as it is for numeric-edited
items that have USAGE DISPLAY, except that the editing is done with national characters. For example,
if Edited-price is declared as USAGE NATIONAL in the code above, the item is edited and displayed
using national characters.
To display numeric or numeric-edited data items that have USAGE NATIONAL in EBCDIC, direct them
to CONSOLE. For example, if Edited-price in the code above has USAGE NATIONAL, $ 1,500.99 is
displayed when you run the program if the last statement above is:
You can cause an elementary numeric or numeric-edited item to be filled with spaces when a value of
zero is stored into it by coding the BLANK WHEN ZERO clause for the item. For example, each of the
DISPLAY statements below causes blanks to be displayed instead of zeros:
You cannot use numeric-edited items as sending operands in arithmetic expressions or in ADD,
SUBTRACT, MULTIPLY, DIVIDE, or COMPUTE statements. (Numeric editing takes place when a numeric-
edited item is the receiving field for one of these statements, or when a MOVE statement has a numeric-
edited receiving field and a numeric-edited or numeric sending field.) You use numeric-edited items
primarily for displaying or printing numeric data.
You can move numeric-edited items to numeric or numeric-edited items. In the following example, the
value of the numeric-edited item (whether it has USAGE DISPLAY or USAGE NATIONAL) is moved to the
numeric item:
related tasks
“Displaying values on a
screen or in a file (DISPLAY)” on page 35
“Controlling how numeric data is stored” on page 46
“Defining numeric data” on page 43
“Performing arithmetic” on page 55
“Defining national numeric
data items” on page 132
“Converting to or from national (Unicode) representation” on page 136
related references
MOVE statement (Enterprise COBOL for z/OS Language Reference)
BLANK WHEN ZERO clause (Enterprise COBOL for z/OS Language Reference)
The compiler converts displayable numbers to the internal representation of their numeric values before
using them in arithmetic operations. Therefore it is often more efficient if you define data items as
BINARY or PACKED-DECIMAL than as DISPLAY or NATIONAL. For example:
46 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Regardless of which USAGE clause you use to control the internal representation of a value, you use the
same PICTURE clause conventions and decimal value in the VALUE clause (except for internal floating-
point data, for which you cannot use a PICTURE clause).
“Examples: numeric data and internal representation” on page 50
related concepts
“Formats for numeric
data” on page 47
“Data format conversions” on page 51
Appendix A, “Intermediate results and arithmetic precision,” on page 691
related tasks
“Defining numeric data” on page 43
“Displaying numeric data” on page 45
“Performing arithmetic” on page 55
related references
“Conversions and precision” on page 52
“Sign representation of zoned and packed-decimal data” on page 53
The minus signs (-) do not mean that the mantissa and exponent must necessarily be negative numbers.
Instead, they mean that when the number is displayed, the sign appears as a blank for positive numbers
If Compute-Result-N is displayed, the signs appear as described above for Compute-Result, but
in national characters. To instead display Compute-Result-N in EBCDIC characters, direct it to the
console:
You cannot use the VALUE clause for external floating-point items.
As with external decimal numbers, external floating-point numbers have to be converted (by the
compiler) to an internal representation of their numeric value before they can be used in arithmetic
operations. If you compile with the default option ARITH (COMPAT), external floating-point numbers are
converted to long (64-bit) floating-point format. If you compile with ARITH (EXTEND), they are instead
converted to extended-precision (128-bit) floating-point format.
48 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 5. Ranges in value of COMP-5 data items
PICTURE Storage representation Numeric values
S9(1) through S9(4) Binary halfword (2 bytes) -32768 through +32767
S9(5) through S9(9) Binary fullword (4 bytes) -2,147,483,648 through +2,147,483,647
S9(10) through Binary doubleword (8 bytes) -9,223,372,036,854,775,808 through
S9(18) +9,223,372,036,854,775,807
9(1) through 9(4) Binary halfword (2 bytes) 0 through 65535
9(5) through 9(9) Binary fullword (4 bytes) 0 through 4,294,967,295
9(10) through 9(18) Binary doubleword (8 bytes) 0 through 18,446,744,073,709,551,615
You can specify scaling (that is, decimal positions or implied integer positions) in the PICTURE clause
of COMP-5 items. If you do so, you must appropriately scale the maximal capacities listed above. For
example, a data item you describe as PICTURE S99V99 COMP-5 is represented in storage as a binary
halfword, and supports a range of values from -327.68 through +327.67.
Large literals in VALUE clauses: Literals specified in VALUE clauses for COMP-5 items can, with a few
exceptions, contain values of magnitude up to the capacity of the native binary representation. See
Enterprise COBOL for z/OS Language Reference for the exceptions.
Regardless of the setting of the TRUNC compiler option, COMP-5 data items behave like binary data does
in programs compiled with TRUNC(BIN).
related concepts
“Unicode and the encoding
of language characters” on page 129
Appendix A, “Intermediate results and arithmetic precision,” on page 691
related tasks
“Defining numeric data” on page 43
“Defining national numeric
data items” on page 132
related references
“Storage of character data” on page 136
“TRUNC” on page 364
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
SIGN clause (Enterprise COBOL for z/OS Language Reference)
VALUE clause (Enterprise COBOL for z/OS Language Reference)
+ 1234 4E F1 F2 F3 F4
PIC S9999 DISPLAY - 1234 60 F1 F2 F3 F4
SIGN LEADING SEPARATE
+ 1234 F1 F2 F3 F4 4E
PIC S9999 DISPLAY - 1234 F1 F2 F3 F4 60
SIGN TRAILING
SEPARATE
+ 1234 00 2B 00 31 00 32 00 33 00
34
PIC S9999 NATIONAL
SIGN LEADING - 1234 00 2D 00 31 00 32 00 33 00
SEPARATE 34
+ 1234 00 31 00 32 00 33 00 34 00
2B
PIC S9999 NATIONAL
SIGN TRAILING - 1234 00 31 00 32 00 33 00 34 00
SEPARATE 2D
Binary + 1234 04 D2
PIC S9999 BINARY - 1234 FB 2E
PIC S9999 COMP
PIC S9999 COMP-4
50 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 6. Internal representation of numeric items (continued)
Numeric type PICTURE and USAGE and Value Internal representation
optional SIGN clause
Internal + 1234 01 23 4C
decimal PIC S9999 PACKED- - 1234 01 23 4D
DECIMAL
PIC S9999 COMP-3
1234 01 23 4F
PIC 9999 PACKED-
DECIMAL
PIC 9999 COMP-3
- 12.34E+02
00 2D 00 31 00 32 00 2E 00
33
00 34 00 45 00 2B 00 30 00
32
1. The example demonstrates that COMP-5 data items can contain values of magnitude up to the capacity
of the native binary representation (2, 4, or 8 bytes), rather than being limited to the value implied by the
number of 9s in the PICTURE clause.
Conversions between fixed-point data formats (external decimal, packed decimal, or binary) are without
loss of precision provided that the target field can contain all the digits of the source operand.
A loss of precision is possible in conversions between fixed-point data formats and floating-point data
formats (short floating point, long floating point, or external floating point). These conversions happen
during arithmetic evaluations that have a mixture of both fixed-point and floating-point operands.
related references
“Conversions and precision” on page 52
“Sign representation of zoned and packed-decimal data” on page 53
52 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related concepts
Appendix A, “Intermediate results and arithmetic precision,” on page 691
The COBOL NUMPROC compiler option affects sign processing for zoned decimal and internal decimal
data. NUMPROC has no effect on binary data, national decimal data, or floating-point data.
NUMPROC(PFD)
Given X'sd', where s is the sign representation and d represents the digit, when you use
NUMPROC(PFD), the compiler assumes that the sign in your data is one of three preferred signs:
Signed positive or 0:
X'C'
Signed negative:
X'D'
Unsigned or alphanumeric:
X'F'
Based on this assumption, the compiler uses whatever sign it is given to process data. The preferred
sign is generated only where necessary (for example, when unsigned data is moved to signed data).
Using the NUMPROC(PFD) option can save processing time, but you must use preferred signs with
your data for correct processing.
NUMPROC(NOPFD)
When the NUMPROC(NOPFD) compiler option is in effect, the compiler accepts any valid sign
configuration. The preferred sign is always generated in the receiver. NUMPROC(NOPFD) is less
efficient than NUMPROC(PFD), but you should use it whenever data that does not use preferred signs
might exist.
If an unsigned, zoned-decimal sender is moved to an alphanumeric receiver, the sign is unchanged
(even with NUMPROC(NOPFD) in effect).
related references
“NUMPROC” on page 340
“ZWB” on page 375
Linkage Section.
01 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
PICTURE and USAGE of the data item. For example, a packed decimal item is checked for hexadecimal
values X'0' through X'9' in the digit positions and for a valid sign value in the sign position (whether
separate or nonseparate). An external decimal data item that has USAGE DISPLAY is checked for
hexadecimal values X'0' through X'9' in the digit positions (the lower 4 bits of each byte), for a valid
zone code in the upper 4 bits of each byte and for a valid sign value in the sign position (whether separate
or nonseparate). The sign code is in the upper 4 bits of the sign byte or in a separate byte if SIGN IS
SEPARATE was specified. If the SIGN IS SEPARATE clause is used, the upper four bits of all bytes must
be x'F'.
Note: Although the INVDATA compiler option allows toleration of invalid zone codes in USAGE DISPLAY
numeric (zoned decimal) data items in numeric comparisons, invalid zone codes in zoned decimal data
items will be treated as nonnumeric by the numeric class test.
For zoned decimal and packed decimal items, the numeric class test is affected by the NUMPROC compiler
option and the NUMCLS option (which is set at installation time). To determine the NUMCLS setting used at
your installation, consult your system programmer.
If NUMCLS(PRIM) is in effect at your installation, use the following table to find the values that the
compiler considers valid for the sign.
If NUMCLS(ALT) is in effect at your installation, use the following table to find the values that the
compiler considers valid for the sign.
For more information about numeric class condition, see Class condition in the Enterprise COBOL for z/OS
Language Reference.
You can also use the NUMCHECK(ZON,PAC) option to have the compiler generate implicit numeric class
tests for zoned decimal (numeric USAGE DISPLAY) and packed decimal (COMP-3) data items that are
used as sending data items. This numeric class test validates data and also validates sign fields against
the NUMPROC compiler option to help you decide whether you can use NUMPROC(PFD) or not. For details,
see “NUMCHECK” on page 336.
For more information about other invalid data issues, in particular for COBOL migration purposes, see the
FAQ about invalid data in the Enterprise COBOL Migration Guide.
54 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related references
“NUMCHECK” on page 336
“NUMPROC” on page 340
“INVDATA” on page 326
Performing arithmetic
You can use any of several COBOL language features (including COMPUTE, arithmetic expressions,
numeric intrinsic functions, and math and date callable services) to perform arithmetic. Your choice
depends on whether a feature meets your particular needs.
For most common arithmetic evaluations, the COMPUTE statement is appropriate. If you need to use
numeric literals, numeric data, or arithmetic operators, you might want to use arithmetic expressions. In
places where numeric expressions are allowed, you can save time by using numeric intrinsic functions.
Language Environment callable services for mathematical functions and for date and time operations also
provide a means of assigning arithmetic results to data items.
related tasks
“Using COMPUTE and other arithmetic statements” on page 55
“Using arithmetic expressions” on page 56
“Using numeric intrinsic functions” on page 56
“Using math-oriented callable services” on page 58
“Using date callable services” on page 59
Compute z = a + b / c ** d - e
Compute x y z = a + b / c ** d - e
Some arithmetic calculations might be more intuitive using arithmetic statements other than COMPUTE.
For example:
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.
related concepts
“Fixed-point contrasted with floating-point arithmetic” on page 62
Appendix A, “Intermediate results and arithmetic precision,” on page 691
related tasks
“Defining numeric data” on page 43
If (a + b) > (c - d + 5) Then. . .
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.
Arithmetic operators are evaluated in the following order of precedence:
Operators at the same level of precedence are evaluated from left to right; however, you can use
parentheses to change the order of evaluation. Expressions in parentheses are evaluated before the
individual operators are evaluated. Parentheses, whether necessary or not, make your program easier to
read.
related concepts
“Fixed-point contrasted with floating-point arithmetic” on page 62
Appendix A, “Intermediate results and arithmetic precision,” on page 691
Integer
Those that return an integer
56 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Floating point
Those that return a long (64-bit) or extended-precision (128-bit) floating-point value (depending on
whether you compile using the default option ARITH(COMPAT) or using ARITH(EXTEND))
Mixed
Those that return an integer, a floating-point value, or a fixed-point number with decimal places,
depending on the arguments
You can use intrinsic functions to perform several different arithmetic operations, as outlined in the
following table.
You can reference one function as the argument of another. A nested function is evaluated independently
of the outer function (except when the compiler determines whether a mixed function should be
evaluated using fixed-point or floating-point instructions).
You can also nest an arithmetic expression as an argument to a numeric function. For example, in the
statement below, there are three function arguments (a, b, and the arithmetic expression (c / d)):
You can reference all the elements of a table (or array) as function arguments by using the ALL subscript.
You can also use the integer special registers as arguments wherever integer arguments are allowed.
Many of the capabilities of numeric intrinsic functions are also provided by Language Environment callable
services.
related concepts
“Fixed-point contrasted with floating-point arithmetic” on page 62
Appendix A, “Intermediate results and arithmetic precision,” on page 691
1. RANDOM returns a long (64-bit) floating-point result even if you pass it a 31-digit argument and compile with
ARITH(EXTEND).
Both the RANDOM intrinsic function and CEERAN0 service generate random numbers between zero and
one. However, because each uses its own algorithm, RANDOM and CEERAN0 produce different random
numbers from the same seed.
Even for functions that produce the same results, how you use intrinsic functions and Language
Environment callable services differs. The rules for the data types required for intrinsic function
arguments are less restrictive. For numeric intrinsic functions, you can use arguments that are of any
numeric data type. When you invoke a Language Environment callable service with a CALL statement,
58 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
however, you must ensure that the parameters match the numeric data types (generally COMP-1 or
COMP-2) required by that service.
The error handling of intrinsic functions and Language Environment callable services sometimes differs.
If you pass an explicit feedback token when calling the Language Environment math services, you must
check the feedback code after each call and take explicit action to deal with errors. However, if you call
with the feedback token explicitly OMITTED, you do not need to check the token; Language Environment
automatically signals any errors.
related concepts
“Fixed-point contrasted with floating-point arithmetic” on page 62
Appendix A, “Intermediate results and arithmetic precision,” on page 691
related tasks
“Using Language Environment callable
services” on page 685
related references
“ARITH” on page 300
Table 12. INTDATE(LILIAN) and compatibility of date intrinsic functions and callable services
COBOL intrinsic function Language Environment callable service Results
DATE-OF-INTEGER CEEDATE with picture string YYYYMMDD Compatible
DAY-OF-INTEGER CEEDATE with picture string YYYYDDD Compatible
INTEGER-OF-DATE CEEDAYS Compatible
INTEGER-OF-DATE CEECBLDY Incompatible
When the default setting of INTDATE(ANSI) is in effect, COBOL uses January 1, 1601 as day 1. The
following table compares the results when INTDATE(ANSI) is in effect.
Table 13. INTDATE(ANSI) and compatibility of date intrinsic functions and callable services
COBOL intrinsic function Language Environment callable service Results
INTEGER-OF-DATE CEECBLDY Compatible
DATE-OF-INTEGER CEEDATE with picture string YYYYMMDD Incompatible
DAY-OF-INTEGER CEEDATE with picture string YYYYDDD Incompatible
INTEGER-OF-DATE CEEDAYS Incompatible
related tasks
“Using Language Environment callable
services” on page 685
01 X Pic 9(2).
01 Price1 Pic x(8) Value "$8000".
01 Price2 Pic x(8) Value "$2000".
01 Output-Record.
05 Product-Name Pic x(20).
05 Product-Number Pic 9(9).
05 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 can use the
following statement:
Finance
Business investment decisions frequently require computing the present value of expected future cash
inflows to evaluate the profitability of a planned investment. 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.
60 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
For example, assume that 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
calculate the present value of those cash inflows at a 10% interest rate:
You can use the ANNUITY function 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 can calculate the monthly payment required to
repay a $15,000 loan in three years at a 12% annual interest rate (36 monthly payments, interest per
month = .12/12):
Mathematics
The following COBOL statement demonstrates that you can nest intrinsic functions, use arithmetic
expressions as arguments, and perform previously complex calculations simply:
Here in the addend the intrinsic function REM (instead of a DIVIDE statement with a REMAINDER clause)
returns the remainder of dividing X by 2.
Statistics
Intrinsic functions make calculating statistical information 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):
related tasks
“Converting to numbers (NUMVAL, NUMVAL-C, NUMVAL-F)” on page 115
• Arithmetic comparisons
Floating-point evaluations
In general, if your arithmetic coding has either of the characteristics listed below, it is evaluated in
floating-point arithmetic:
• An operand or result field is floating point.
An operand is floating point if you code it as a floating-point literal or if you code it as a data item that
is defined as USAGE COMP-1, USAGE COMP-2, or external floating point (USAGE DISPLAY or USAGE
NATIONAL with a floating-point PICTURE).
An operand that is a nested arithmetic expression or a reference to a numeric intrinsic function results
in floating-point arithmetic when any of the following conditions is true:
– 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.
An exponent contains decimal places if you use a literal that contains decimal places, give the item a
PICTURE that contains decimal places, or use an arithmetic expression or function whose result has
decimal places.
An arithmetic expression or numeric function yields a result that has decimal places if any operand or
argument (excluding divisors and exponents) has decimal places.
Fixed-point evaluations
In general, if an arithmetic operation contains neither of the characteristics listed above for floating point,
the compiler causes it to be evaluated in fixed-point arithmetic. In other words, arithmetic evaluations
are handled as fixed point only if all the operands are fixed point, the result field is defined to be fixed
point, and none of the exponents represent values with decimal places. Nested arithmetic expressions
and function references must also represent fixed-point values.
62 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Arithmetic comparisons (relation conditions)
When you compare numeric expressions using a relational operator, the numeric expressions (whether
they are data items, arithmetic expressions, function references, or some combination of these) are
comparands in the context of the entire evaluation. That is, the attributes of each can influence the
evaluation of the other: both expressions are evaluated in fixed point, or both are evaluated in floating
point. This is also true of abbreviated comparisons even though one comparand does not explicitly appear
in the comparison. For example:
if (a + d) = (b + e) and c
evaluate (a + d)
when (b + e) thru c
when (f / g) thru (h * i)
. . .
end-evaluate
01 employee-table.
05 emp-count pic 9(4).
05 employee-record occurs 1 to 1000 times
depending on emp-count.
10 hours pic +9(5)ve+99.
. . .
01 report-matrix-col pic 9(3).
01 report-matrix-min pic 9(3).
01 report-matrix-max pic 9(3).
01 report-matrix-tot pic 9(3).
01 average-hours pic 9(3)v9.
01 whole-hours pic 9(4).
To specify the symbols for displaying financial information, use the CURRENCY SIGN clause (in the
SPECIAL-NAMES paragraph in the CONFIGURATION SECTION) with the PICTURE characters that relate
to those symbols. In the following example, the PICTURE character $ indicates that the currency sign $US
is to be used:
In this example, if Invoice-Amount contained 1500.00, the display output would be:
By using more than one CURRENCY SIGN clause in your program, you can allow for multiple currency
signs to be displayed.
You can use a hexadecimal literal to indicate the currency sign value. Using a hexadecimal literal could
be useful if the data-entry method for the source program does not allow the entry of the intended
characters easily. The following example shows the hexadecimal value X'9F' used as the currency sign:
If there is no corresponding character for the euro sign on your keyboard, you need to specify it as a
hexadecimal value in the CURRENCY SIGN clause. The hexadecimal value for the euro sign is either
X'9F' or X'5A' depending on the code page in use, as shown in the following table.
64 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 14. Hexadecimal values of the euro sign
Code page Applicable countries Modified Euro sign
CCSID from
1140 USA, Canada, Netherlands, Portugal, Australia, New 037 X'9F'
Zealand
1141 Austria, Germany 273 X'9F'
1142 Denmark, Norway 277 X'5A'
1143 Finland, Sweden 278 X'5A'
1144 Italy 280 X'9F'
1145 Spain, Latin America - Spanish 284 X'9F'
1146 UK 285 X'9F'
1147 France 297 X'9F'
1148 Belgium, Canada, Switzerland 500 X'9F'
1149 Iceland 871 X'9F'
related references
“CURRENCY” on page 309
CURRENCY SIGN clause (Enterprise COBOL for z/OS Language Reference)
IDENTIFICATION DIVISION.
PROGRAM-ID. EuroSamp.
Environment Division.
Configuration Section.
Special-Names.
Currency Sign is "CHF " with Picture Symbol "F"
Currency Sign is "EUR " with Picture Symbol "U".
Data Division.
WORKING-STORAGE SECTION.
01 Deposit-in-Euro Pic S9999V99 Value 8000.00.
01 Deposit-in-CHF Pic S99999V99.
01 Deposit-Report.
02 Report-in-Franc Pic -FFFFF9.99.
02 Report-in-Euro Pic -UUUUU9.99.
01 EUR-to-CHF-Conv-Rate Pic 9V99999 Value 1.53893.
. . .
PROCEDURE DIVISION.
Report-Deposit-in-CHF-and-EUR.
Move Deposit-in-Euro to Report-in-Euro
Compute Deposit-in-CHF Rounded
= Deposit-in-Euro * EUR-to-CHF-Conv-Rate
On Size Error
Perform Conversion-Error
Not On Size Error
Move Deposit-in-CHF to Report-in-Franc
Display "Deposit in euro = " Report-in-Euro
Display "Deposit in franc = " Report-in-Franc
End-Compute
Goback.
Conversion-Error.
Display "Conversion error from EUR to CHF"
Display "Euro value: " Report-in-Euro.
The exchange rate used in this example is for illustrative purposes only.
66 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Chapter 4. Handling tables
A table is a collection of data items that have the same description, such as account totals or monthly
averages. A table consists of a table name and subordinate items called table elements. A table is the
COBOL equivalent of an array.
In the example above, 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.
Rather than defining repetitious items as separate, consecutive entries in the DATA DIVISION, you use
the OCCURS clause in the DATA DIVISION entry to define a table. This practice has these advantages:
• The code clearly shows the unity of the items (the table elements).
• You can use subscripts and indexes to refer to the table elements.
• You can easily repeat data items.
Tables are important for increasing the speed of a program, especially a program that looks up records.
related concepts
“Complex OCCURS DEPENDING
ON” on page 81
related tasks
“Defining a table (OCCURS)” on page 67
“Nesting tables” on page 69
“Referring to an item in a table” on page 70
“Putting values into a table” on page 73
“Creating variable-length
tables (DEPENDING ON)” on page 78
“Searching a table” on page 84
“Sorting
a table” on page 87
“Processing table items
using intrinsic functions” on page 87
“Working with
unbounded tables and groups” on page 88
01 table-name.
05 element-name OCCURS n TIMES.
. . . (subordinate items of the table element)
Any elementary item that is subordinate to a national group must be explicitly or implicitly described as
USAGE NATIONAL, and any subordinate numeric data item that is signed must be implicitly or explicitly
described with the SIGN IS SEPARATE clause.
To create tables of two to seven dimensions, use nested OCCURS clauses.
To create a variable-length table, code the DEPENDING ON phrase of the OCCURS clause.
To specify that table elements will be arranged in ascending or descending order based on the values in
one or more key fields of the table, code the ASCENDING or DESCENDING KEY phrases of the OCCURS
clause, or both. Specify the names of the keys in decreasing order of significance. Keys can be of class
alphabetic, alphanumeric, DBCS, national, or numeric. (If it has USAGE NATIONAL, a key can be of
category national, or can be a national-edited, numeric-edited, national decimal, or national floating-point
item.)
You must code the ASCENDING or DESCENDING KEY phrase of the OCCURS clause to do a binary search
(SEARCH ALL) of a table. You can use a format 2 SORT statement to order the table according to its
defined keys, thereby making the table searchable by the SEARCH ALL statement. Note that SEARCH
ALL will return unpredictable results if the table has not been ordered according to the keys.
“Example: binary search” on page 86
related concepts
“National groups” on page 132
related tasks
“Nesting tables” on page 69
“Referring to an item in a table” on page 70
“Putting values into a table” on page 73
“Creating variable-length
tables (DEPENDING ON)” on page 78
“Using national groups” on page 133
“Doing a binary search (SEARCH
ALL)” on page 86
“Defining numeric data” on page 43
related references
OCCURS clause (Enterprise COBOL for z/OS Language Reference)
SIGN clause (Enterprise COBOL for z/OS Language Reference)
ASCENDING KEY and DESCENDING KEY phrases
(Enterprise COBOL for z/OS Language Reference)
SORT statement (Enterprise COBOL for z/OS Language Reference)
68 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Nesting tables
To create a two-dimensional table, define a one-dimensional table in each occurrence of another one-
dimensional table.
In a two-dimensional table, the two subscripts correspond to the row and column numbers. In a three-
dimensional table, the three subscripts correspond to the depth, row, and column numbers.
related tasks
“Defining a table (OCCURS)” on page 67
“Referring to an item in a table” on page 70
“Putting values into a table” on page 73
“Creating variable-length
tables (DEPENDING ON)” on page 78
“Searching a table” on page 84
“Processing table items
using intrinsic functions” on page 87
“Handling tables efficiently” on page 672
related references
OCCURS clause (Enterprise COBOL for z/OS Language Reference)
TABLE-COLUMN (2, 2, 1)
TABLE-COLUMN (2 2 1)
In either table reference, 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.
The following reference to SAMPLE-TABLE-TWO uses variable subscripts. The reference is valid if SUB1
and SUB2 are data-names that contain positive integer values within the range of the table.
related tasks
“Subscripting” on page 71
Example: indexing
The following example shows how displacements to elements that are referenced with indexes are
calculated.
01 SAMPLE-TABLE-FOUR
05 TABLE-DEPTH OCCURS 3 TIMES INDEXED BY INX-A.
10 TABLE-ROW OCCURS 4 TIMES INDEXED BY INX-B.
15 TABLE-COLUMN OCCURS 8 TIMES INDEXED BY INX-C PIC X(8).
This reference causes the following computation of the displacement to the TABLE-COLUMN element:
related tasks
“Indexing” on page 72
70 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
• Use the data-name of the table element, along with its occurrence number (called a subscript) in
parentheses. This technique is called subscripting.
• Use the data-name of the table element, along with a value (called an index) that is added to the
address of the table to locate an item (as a displacement from the beginning of the table). This
technique is called indexing, or subscripting using index-names.
• Use both subscripts and indexes together.
related tasks
“Subscripting” on page 71
“Indexing” on page 72
Subscripting
The lowest possible subscript value is 1, which references the first occurrence of a table element. In a
one-dimensional table, the subscript corresponds to the row number.
You can use a literal or a data-name as a subscript. If a data item that has a literal subscript is of fixed
length, the compiler resolves the location of the data item.
When you use a data-name as a variable subscript, you must describe the data-name as an elementary
numeric integer. The most efficient format is COMPUTATIONAL (COMP) with a PICTURE size that is smaller
than five digits. You cannot use a subscript with a data-name that is used as a subscript. The code
generated for the application resolves the location of a variable subscript at run time.
You can increment or decrement a literal or variable subscript by a specified integer amount. For example:
You can change part of a table element rather than the whole element. To do so, refer to the character
position and length of the substring to be changed. For example:
01 ANY-TABLE.
05 TABLE-ELEMENT PIC X(10)
OCCURS 3 TIMES VALUE "ABCDEFGHIJ".
. . .
MOVE "??" TO TABLE-ELEMENT (1) (3 : 2).
The MOVE statement in the example above moves the string '??' into table element number 1, beginning
at character position 3, for a length of 2 characters.
related tasks
“Indexing” on page 72
“Putting values into a table” on page 73
“Searching a table” on page 84
“Handling tables efficiently” on page 672
The compiler calculates the value contained in the index as the occurrence number (subscript) minus
1, multiplied by the length of the table element. Therefore, for the fifth occurrence of TABLE-ITEM, the
binary value contained in INX-A is (5 - 1) * 8, or 32.
You can use an index-name to reference another table only if both table descriptions have the same
number of table elements, and the table elements are of the same length.
You can use the USAGE IS INDEX clause to create an index data item, and can use an index data item
with any table. For example, INX-B in the following code is an index data item:
The index-name INX-A is used to traverse table TABLE-ITEM above. The index data item INX-B is used
to hold the index of the last element of the table. The advantage of this type of coding is that calculation of
offsets of table elements is minimized, and no conversion is necessary for the UNTIL condition.
You can use the SET statement to assign to an index data item the value that you stored in an index-name,
as in the statement SET INX-B TO INX-A above. For example, when you load records into a variable-
length table, you can store the index value of the last record into a data item defined as USAGE IS
INDEX. Then you can test for the end of the table by comparing the current index value with the index
value of the last record. This technique is useful when you look through or process a table.
You can increment or decrement an index-name by an elementary integer data item or a nonzero integer
literal, for example:
The integer represents a number of occurrences. It is converted to an index value before being added to
or subtracted from the index.
Initialize the index-name by using a SET, PERFORM VARYING, or SEARCH ALL statement. You can then
use the index-name in SEARCH or relational condition statements. To change the value, use a PERFORM,
SEARCH, or SET statement.
Because you are comparing a physical displacement, you can directly use index data items only in
SEARCH and SET statements or in comparisons with indexes or other index data items. You cannot use
index data items as subscripts or indexes.
“Example: indexing” on page 70
related tasks
“Subscripting” on page 71
“Putting values into a table” on page 73
“Searching a table” on page 84
“Processing table items
using intrinsic functions” on page 87
“Handling tables efficiently” on page 672
72 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related references
INDEXED BY phrase (Enterprise COBOL for z/OS Language Reference)
INDEX phrase (Enterprise COBOL for z/OS Language Reference)
SET statement (Enterprise COBOL for z/OS Language Reference)
related tasks
“Loading a table dynamically” on page 73
“Loading a variable-length table” on page 80
“Initializing a table (INITIALIZE)” on page 73
“Assigning values when you define a table (VALUE)” on page 74
“Assigning values to a variable-length
table” on page 80
related references
PERFORM statement (Enterprise COBOL for z/OS Language Reference)
To move the character 'X' into each of the elementary alphanumeric data items in TABLE-ONE, you can
code the following statement:
When you use the INITIALIZE statement to initialize a table, the table is processed as a group item
(that is, with group semantics); elementary data items within the group are recognized and processed. For
example, suppose that TABLE-ONE is an alphanumeric group that is defined like this:
01 TABLE-ONE.
02 Trans-out Occurs 20.
05 Trans-code Pic X Value "R".
05 Part-number Pic XX Value "13".
05 Trans-quan Pic 99 Value 10.
05 Price-fields.
The table below shows the content that each of the twenty 12-byte elements Trans-out(n) has before
execution and after execution of the INITIALIZE statement shown above:
You can similarly use an INITIALIZE statement to load a table that is defined as a national group. For
example, if TABLE-ONE shown above specified the GROUP-USAGE NATIONAL clause, and Trans-code
and Part-number had N instead of X in their PICTURE clauses, the following statement would have the
same effect as the INITIALIZE statement above, except that the data in TABLE-ONE would instead be
encoded in UTF-16:
74 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related tasks
“Initializing each table
item individually” on page 75
“Initializing a table at
the group level” on page 76
“Initializing all occurrences
of a given table element” on page 76
“Initializing a structure
(INITIALIZE)” on page 31
***********************************************************
*** E R R O R F L A G T A B L E ***
***********************************************************
01 Error-Flag-Table Value Spaces.
88 No-Errors Value Spaces.
05 Type-Error Pic X.
05 Shift-Error Pic X.
05 Home-Code-Error Pic X.
05 Work-Code-Error Pic X.
05 Name-Error Pic X.
05 Initials-Error Pic X.
05 Duplicate-Error Pic X.
05 Not-Found-Error Pic X.
01 Filler Redefines Error-Flag-Table.
05 Error-Flag Occurs 8 Times
Indexed By Flag-Index Pic X.
In the example above, the VALUE clause at the 01 level initializes each of the table items to the same
value. Each table item could instead be described with its own VALUE clause to initialize that item to a
distinct value.
To initialize larger tables, use MOVE, PERFORM, or INITIALIZE statements.
related tasks
“Initializing a structure
(INITIALIZE)” on page 31
“Assigning values to a variable-length
table” on page 80
related references
REDEFINES clause (Enterprise COBOL for z/OS Language Reference)
OCCURS clause (Enterprise COBOL for z/OS Language Reference)
In the following example, the national group data item Table-OneN uses a VALUE clause that initializes
each of the three elements of the subordinate data item Table-TwoN (each of which is implicitly USAGE
NATIONAL). Note that you can initialize a national group data item with a VALUE clause that uses an
alphanumeric literal, as shown below, or a national literal.
related references
OCCURS clause (Enterprise COBOL for z/OS Language Reference)
GROUP-USAGE clause (Enterprise COBOL for z/OS Language Reference)
01 T2.
05 T-OBJ PIC 9 VALUE 3.
05 T OCCURS 5 TIMES
DEPENDING ON T-OBJ.
10 X PIC XX VALUE "AA".
10 Y PIC 99 VALUE 19.
10 Z PIC XX VALUE "BB".
For example, the code above 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.
related tasks
“Assigning values to a variable-length
table” on page 80
related references
OCCURS clause (Enterprise COBOL for z/OS Language Reference)
***********************************************************
*** E R R O R F L A G T A B L E ***
76 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
***********************************************************
01 Error-Flag-Table Value Spaces.
88 No-Errors Value Spaces.
05 Type-Error Pic X.
05 Shift-Error Pic X.
05 Home-Code-Error Pic X.
05 Work-Code-Error Pic X.
05 Name-Error Pic X.
05 Initials-Error Pic X.
05 Duplicate-Error Pic X.
05 Not-Found-Error Pic X.
01 Filler Redefines Error-Flag-Table.
05 Error-Flag Occurs 8 Times
Indexed By Flag-Index Pic X.
77 Error-on Pic X Value "E".
***********************************************************
*** E R R O R M E S S A G E T A B L E ***
***********************************************************
01 Error-Message-Table.
05 Filler Pic X(25) Value
"Transaction Type Invalid".
05 Filler Pic X(25) Value
"Shift Code Invalid".
05 Filler Pic X(25) Value
"Home Location Code Inval.".
05 Filler Pic X(25) Value
"Work Location Code Inval.".
05 Filler Pic X(25) Value
"Last Name - Blanks".
05 Filler Pic X(25) Value
"Initials - Blanks".
05 Filler Pic X(25) Value
"Duplicate Record Found".
05 Filler Pic X(25) Value
"Commuter Record Not Found".
01 Filler Redefines Error-Message-Table.
05 Error-Message Occurs 8 Times
Indexed By Message-Index Pic X(25).
. . .
PROCEDURE DIVISION.
. . .
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 260-Print-Report
End-If
End-Perform
. . .
***********************************************************
*** E R R O R F L A G T A B L E ***
***********************************************************
01 Error-Flag-Table Value Spaces.
88 No-Errors Value Spaces.
05 Type-Error Pic X.
05 Shift-Error Pic X.
05 Home-Code-Error Pic X.
05 Work-Code-Error Pic X.
05 Name-Error Pic X.
05 Initials-Error Pic X.
05 Duplicate-Error Pic X.
05 Not-Found-Error Pic X.
01 Filler Redefines Error-Flag-Table.
05 Error-Flag Occurs 8 Times
Indexed By Flag-Index Pic X.
77 Error-on Pic X Value "E".
***********************************************************
*** E R R O R M E S S A G E T A B L E ***
***********************************************************
01 Error-Message-Table.
In the example above, X is called the ODO subject, and Y is called the ODO object.
You can also specify unbounded tables and groups, see Variable-length tables in the Enterprise COBOL for
z/OS Language Reference for details.
Two factors affect the successful manipulation of variable-length records:
• Correct calculation of record lengths
The length of the variable portions of a group item is the product of the object of the DEPENDING ON
phrase and the length of the subject of the OCCURS clause.
• Conformance of the data in the object of the OCCURS DEPENDING ON clause to its PICTURE clause
If the content of the ODO object does not match its PICTURE clause, the program could terminate
abnormally. You must ensure that the ODO object correctly specifies the current number of occurrences
of table elements.
The following example shows a group item (REC-1) that contains both the subject and object of the
OCCURS DEPENDING ON clause. The way the length of the group item is determined depends on whether
it is sending or receiving data.
WORKING-STORAGE SECTION.
01 MAIN-AREA.
03 REC-1.
05 FIELD-1 PIC 9.
05 FIELD-2 OCCURS 1 TO 5 TIMES
DEPENDING ON FIELD-1 PIC X(05).
78 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
01 REC-2.
03 REC-2-DATA PIC X(50).
If you want to move REC-1 (the sending item in this case) to REC-2, the length of REC-1 is determined
immediately before the move, using the current value in FIELD-1. If the content of FIELD-1 conforms to
its PICTURE clause (that is, if FIELD-1 contains a zoned decimal item), the move can proceed based on
the actual length of REC-1. Otherwise, the result is unpredictable. You must ensure that the ODO object
has the correct value before you initiate the move.
When you do a move to REC-1 (the receiving item in this case), the length of REC-1 is determined using
the maximum number of occurrences. In this example, five occurrences of FIELD-2, plus FIELD-1,
yields a length of 26 bytes. In this case, you do not need to set the ODO object (FIELD-1) before
referencing REC-1 as a receiving item. However, the sending field's ODO object (not shown) must 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.
However, if you do a move to REC-1 (again the receiving item) where REC-1 is followed by a variably
located group (a type of complex ODO), the actual length of REC-1 is calculated immediately before the
move, using the current value of the ODO object (FIELD-1). In the following example, REC-1 and REC-2
are in the same record, but REC-2 is not subordinate to REC-1 and is therefore variably located:
01 MAIN-AREA
03 REC-1.
05 FIELD-1 PIC 9.
05 FIELD-3 PIC 9.
05 FIELD-2 OCCURS 1 TO 5 TIMES
DEPENDING ON FIELD-1 PIC X(05).
03 REC-2.
05 FIELD-4 OCCURS 1 TO 5 TIMES
DEPENDING ON FIELD-3 PIC X(05).
The compiler issues a message that lets you know that the actual length was used. This case requires that
you set the value of the ODO object before using the group item as a receiving field.
The following example shows how to define a variable-length table when the ODO object (LOCATION-
TABLE-LENGTH below) is outside the group:
DATA DIVISION.
FILE SECTION.
FD LOCATION-FILE
RECORDING MODE F
BLOCK 0 RECORDS
RECORD 80 CHARACTERS
LABEL RECORD STANDARD.
01 LOCATION-RECORD.
05 LOC-CODE PIC XX.
05 LOC-DESCRIPTION PIC X(20).
05 FILLER PIC X(58).
WORKING-STORAGE SECTION.
01 FLAGS.
05 LOCATION-EOF-FLAG PIC X(5) VALUE SPACE.
88 LOCATION-EOF VALUE "FALSE".
01 MISC-VALUES.
05 LOCATION-TABLE-LENGTH PIC 9(3) VALUE ZERO.
05 LOCATION-TABLE-MAX PIC 9(3) VALUE 100.
*****************************************************************
*** L O C A T I O N T A B L E ***
*** FILE CONTAINS LOCATION CODES. ***
*****************************************************************
01 LOCATION-TABLE.
05 LOCATION-CODE OCCURS 1 TO 100 TIMES
DEPENDING ON LOCATION-TABLE-LENGTH PIC X(80).
related concepts
“Complex OCCURS DEPENDING
ON” on page 81
related references
OCCURS DEPENDING ON clause
(Enterprise COBOL for z/OS Language Reference)
Variable-length tables (Enterprise COBOL for z/OS Language Reference)
DATA DIVISION.
FILE SECTION.
FD LOCATION-FILE
RECORDING MODE F
BLOCK 0 RECORDS
RECORD 80 CHARACTERS
LABEL RECORD STANDARD.
01 LOCATION-RECORD.
05 LOC-CODE PIC XX.
05 LOC-DESCRIPTION PIC X(20).
05 FILLER PIC X(58).
. . .
WORKING-STORAGE SECTION.
01 FLAGS.
05 LOCATION-EOF-FLAG PIC X(5) VALUE SPACE.
88 LOCATION-EOF VALUE "YES".
01 MISC-VALUES.
05 LOCATION-TABLE-LENGTH PIC 9(3) VALUE ZERO.
05 LOCATION-TABLE-MAX PIC 9(3) VALUE 100.
*****************************************************************
*** L O C A T I O N T A B L E ***
*** FILE CONTAINS LOCATION CODES. ***
*****************************************************************
01 LOCATION-TABLE.
05 LOCATION-CODE OCCURS 1 TO 100 TIMES
DEPENDING ON LOCATION-TABLE-LENGTH PIC X(80).
. . .
PROCEDURE DIVISION.
. . .
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
If you define the entire table by using the DEPENDING ON phrase, all the elements are initialized using the
maximum defined value of the ODO (OCCURS DEPENDING ON) object.
80 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
If the ODO object is initialized by a VALUE clause, it is logically initialized after the ODO subject has been
initialized.
For example, in the code above, the ODO subject Y(1) is initialized to 'A', Y(2) to 'B', . . ., Y(5) to 'E',
and finally the ODO object X is initialized to 3. Any subsequent reference to TABLE-THREE (such as in a
DISPLAY statement) refers to X and the first three elements, Y(1) through Y(3), of the table.
related tasks
“Assigning values when you define a table (VALUE)” on page 74
related references
OCCURS DEPENDING ON clause
(Enterprise COBOL for z/OS Language Reference)
related tasks
“Preventing index errors
when changing ODO object value” on page 83
“Preventing overlay when adding elements to a variable table” on page 83
related references
“Effects of change in ODO object value” on page 82
OCCURS DEPENDING ON clause
(Enterprise COBOL for z/OS Language Reference)
01 FIELD-A.
02 COUNTER-1 PIC S99.
02 COUNTER-2 PIC S99.
02 TABLE-1.
03 RECORD-1 OCCURS 1 TO 5 TIMES
DEPENDING ON COUNTER-1 PIC X(3).
02 EMPLOYEE-NUMBER PIC X(5). (1)
02 TABLE-2 OCCURS 5 TIMES (2)(3)
INDEXED BY INDX. (4)
03 TABLE-ITEM PIC 99. (5)
03 RECORD-2 OCCURS 1 TO 3 TIMES
Definition: In the example, COUNTER-1 is an ODO object, that is, it is the object of the DEPENDING ON
clause of RECORD-1. RECORD-1 is said to be an ODO subject. Similarly, COUNTER-2 is the ODO object of
the corresponding ODO subject, RECORD-2.
The types of complex ODO occurrences shown in the example above are as follows:
(1)
A variably located item: EMPLOYEE-NUMBER is a data item that follows, but is not subordinate to, a
variable-length table in the same level-01 record.
(2)
A variably located table: TABLE-2 is a table that follows, but is not subordinate to, a variable-length
table in the same level-01 record.
(3)
A table with variable-length elements: TABLE-2 is a table that contains a subordinate data item,
RECORD-2, whose number of occurrences varies depending on the content of its ODO object.
(4)
An index-name, INDX, for a table that has variable-length elements.
(5)
An element, TABLE-ITEM, of a table that has variable-length elements.
82 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
The value of an ODO object can change when you move data to the ODO object or to the group in which
it is contained. The value can also change if the ODO object is contained in a record that is the target of a
READ statement.
related tasks
“Preventing index errors
when changing ODO object value” on page 83
“Preventing overlay when adding elements to a variable table” on page 83
When you change the value of an ODO object, the byte offset in an associated complex-ODO index is no
longer valid because the table length has changed. Unless you take precautions, you will have unexpected
results if you then code a reference to the index-name such as:
• A reference to an element of the table
• A SET statement of the form SET integer-data-item TO index-name (format 1)
• A SET statement of the form SET index-name UP|DOWN BY integer (format 2)
To avoid this type of error, do these steps:
1. Save the index in an integer data item. (Doing so causes an implicit conversion: the integer item
receives the table element occurrence number that corresponds to the offset in the index.)
2. Change the value of the ODO object.
3. Immediately restore the index from the integer data item. (Doing so causes an implicit conversion:
the index-name receives the offset that corresponds to the table element occurrence number in the
integer item. The offset is computed according to the table length then in effect.)
The following code shows how to save and restore the index-name (shown in “Example: complex ODO”
on page 81) when the ODO object COUNTER-2 changes.
related references
SET statement (Enterprise COBOL for z/OS Language Reference)
WORKING-STORAGE SECTION.
01 VARIABLE-REC.
05 FIELD-1 PIC X(10).
05 CONTROL-1 PIC S99.
05 CONTROL-2 PIC S99.
05 VARY-FIELD-1 OCCURS 1 TO 10 TIMES
DEPENDING ON CONTROL-1 PIC X(5).
05 GROUP-ITEM-1.
10 VARY-FIELD-2
OCCURS 1 TO 10 TIMES
DEPENDING ON CONTROL-2 PIC X(9).
01 STORE-VARY-FIELD-2.
05 GROUP-ITEM-2.
10 VARY-FLD-2
OCCURS 1 TO 10 TIMES
DEPENDING ON CONTROL-2 PIC X(9).
Each element of VARY-FIELD-1 has 5 bytes, and each element of VARY-FIELD-2 has 9 bytes. If
CONTROL-1 and CONTROL-2 both contain the value 3, you can picture storage for VARY-FIELD-1 and
VARY-FIELD-2 as follows:
To add a fourth element to VARY-FIELD-1, code as follows to prevent overlaying the first 5 bytes of
VARY-FIELD-2. (GROUP-ITEM-2 serves as temporary storage for the variably located GROUP-ITEM-1.)
You can picture the updated storage for VARY-FIELD-1 and VARY-FIELD-2 as follows:
Note that the fourth element of VARY-FIELD-1 did not overlay the first element of VARY-FIELD-2.
Searching a table
COBOL provides two search techniques for tables: serial and binary.
To do serial searches, use SEARCH and indexing. For variable-length tables, you can use PERFORM with
subscripting or indexing.
84 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
To do binary searches, use SEARCH ALL and indexing.
A binary search can be considerably more efficient than a serial search. For a serial search, the number
of comparisons is of the order of n, the number of entries in the table. For a binary search, the number of
comparisons is of the order of only the logarithm (base 2) of n. A binary search, however, requires that the
table items already be sorted.
related tasks
“Doing a serial search (SEARCH)” on page 85
“Doing a binary search (SEARCH
ALL)” on page 86
You can reference only one level of a table (a table element) with each SEARCH statement. To search
multiple levels of a table, use nested SEARCH statements. Delimit each nested SEARCH statement with
END-SEARCH.
Performance: If the found condition comes after some intermediate point in the table, 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 of the table also enables more efficient serial
searching. If the table is large and is presorted, a binary search is more efficient.
“Example: serial search” on page 85
related references
SEARCH statement (Enterprise COBOL for z/OS Language Reference)
01 TABLE-ONE.
05 TABLE-ENTRY1 OCCURS 10 TIMES
INDEXED BY TE1-INDEX.
10 TABLE-ENTRY2 OCCURS 10 TIMES
INDEXED BY TE2-INDEX.
15 TABLE-ENTRY3 OCCURS 5 TIMES
ASCENDING KEY IS KEY1
INDEXED BY TE3-INDEX.
20 KEY1 PIC X(5).
20 KEY2 PIC X(10).
. . .
PROCEDURE DIVISION.
. . .
SET TE1-INDEX TO 1
SET TE2-INDEX TO 4
TE1-INDEX = 1
TE2-INDEX = 4
TE3-INDEX points to the TABLE-ENTRY3 item
that equals "A1234AAAAAAAA00"
RETURN-CODE = 0
Each key and its object of comparison must be compatible according to the rules for comparison of data
items. Note though that if a key is compared to a national literal or identifier, the key must be a national
data item.
“Example: binary search” on page 86
related tasks
“Defining a table (OCCURS)” on page 67
related references
SEARCH statement (Enterprise COBOL for z/OS Language Reference)
General relation conditions (Enterprise COBOL for z/OS Language Reference)
01 TABLE-A.
05 TABLE-ENTRY OCCURS 90 TIMES
ASCENDING KEY-1, KEY-2
DESCENDING KEY-3
INDEXED BY INDX-1.
86 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
10 PART-1 PIC 99.
10 KEY-1 PIC 9(5).
10 PART-2 PIC 9(6).
10 KEY-2 PIC 9(4).
10 PART-3 PIC 9(18).
10 KEY-3 PIC 9(5).
If an entry is found in which each of the three keys is equal to the value to which it is compared (VALUE-1,
VALUE-2, and VALUE-3, respectively), PART-1 of that entry is moved to OUTPUT-AREA. If no matching
key is found in the entries in TABLE-A, the NOENTRY routine is performed.
Sorting a table
You can sort a table by using the format 2 SORT statement. It is part of the 2002 COBOL Standard.
The format 2 SORT statement sorts table elements according to the specified table keys, and it is
especially useful for tables used with SEARCH ALL. You can specify the keys for sorting as part of the
table definition, which can also be used in the SEARCH ALL statement. Alternatively, you can also specify
the keys for sorting as part of the SORT statement, either if you want to sort the table using different keys
than those specified in the table definition, or if the table has no keys specified.
With the format 2 SORT statement, you don't need to use the input and output procedures as you do with
the format 1 SORT statement.
See the following example in which the table is sorted based on specified keys:
WORKING-STORAGE SECTION.
01 GROUP-ITEM.
05 TABL OCCURS 10 TIMES
10 ELEM-ITEM1 PIC X.
10 ELEM-ITEM2 PIC X.
10 ELEM-ITEM3 PIC X.
...
PROCEDURE DIVISION.
...
SORT TABL DESCENDING ELEM-ITEM2 ELEM-ITEM3.
IF TABL (1)...
related references
SORT statement (Enterprise COBOL for z/OS Language Reference)
“Using the format 2 SORT statement to sort a table” on page 688
You can mix scalars and array arguments for functions that accept multiple arguments:
related references
Intrinsic functions (Enterprise COBOL for z/OS Language Reference)
The following example computes various salary values for all the employees whose salaries are encoded
in Employee-Table:
01 Employee-Table.
05 Emp-Count Pic s9(4) usage binary.
05 Emp-Record Occurs 1 to 500 times
depending on Emp-Count.
10 Emp-Name Pic x(20).
10 Emp-Idme Pic 9(9).
10 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))
88 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
b. Use the LENGTH special register or the LENGTH intrinsic function to compute the total size of the
group.
c. Use the CALL statement to call a storage allocation service, such as the Language Environment
service CEEGTST. Allocate enough memory for the total length of the group. You will need a pointer
to this memory (the CEEGTST service returns a pointer).
d. Use the SET statement to establish addressability. For example, SET ADDRESS OF group TO
pointer.
4. Use the unbounded table and its containing unbounded group according to the following rules:
• You can reference unbounded tables in COBOL syntax anywhere a table can be referenced.
• You can reference unbounded groups in COBOL syntax anywhere an alphanumeric or national group
can be referenced, with the following exceptions:
– You cannot specify unbounded groups as a BY CONTENT argument in a CALL statement.
– You cannot specify unbounded groups as data-name-2 on the PROCEDURE DIVISION
RETURNING phrase.
– You cannot specify unbounded groups as arguments to intrinsic functions, except as an argument
to the LENGTH intrinsic function.
related references
“Example: Using unbounded tables for parsing XML documents” on page 89
Example: ALLOCATE and FREE storage for unbounded tables
(Enterprise COBOL for z/OS Language Reference)
Variable-length tables (Enterprise COBOL for z/OS Language Reference)
OCCURS DEPENDING ON clause
(Enterprise COBOL for z/OS Language Reference)
XML schema
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://example.org"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="G">
XML document
<?xml version="1.0" encoding="UTF-8"?>
<p:G xmlns:p="http://example.org" >
<A>Hello</A>
<B>1</B>
<B>2</B>
<B>3</B>
<C>1</C>
<C>2</C>
<C>3</C>
<C>4</C>
<C>5</C>
</p:G>
related tasks
“Working with
unbounded tables and groups” on page 88
90 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Chapter 5. Selecting and repeating program actions
Use COBOL control language to choose program actions based on the outcome of logical tests, to iterate
over selected parts of your program and data, and to identify statements to be performed as a group.
These controls include the IF, EVALUATE, and PERFORM statements, and the use of switches and flags.
related tasks
“Selecting program actions” on page 91
“Repeating program actions” on page 99
related tasks
“Coding a choice of actions” on page 91
“Coding conditional expressions” on page 95
related references
IF statement (Enterprise COBOL for z/OS Language Reference)
EVALUATE statement (Enterprise COBOL for z/OS Language Reference)
IF condition-p
statement-1
ELSE
statement-2
END-IF
When one of two processing choices is no action, code the IF statement with or without ELSE. Because
the ELSE clause is optional, you can code the IF statement as follows:
IF condition-q
statement-1
END-IF
Such coding is suitable for simple cases. For complex logic, you probably need to use the ELSE clause.
For example, suppose you have nested IF statements in which there is an action for only one of the
processing choices. You could 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
IF condition-r
statement-1
ELSE
CONTINUE or NEXT SENTENCE
END-IF
*> CONTINUE goes to statement-2
statement-2
statement-3.
*> NEXT SENTENCE goes to statement-4
statement-4
For details about NEXT SENTENCE, see IF statement in the Enterprise COBOL for z/OS Language
Reference.
The EVALUATE statement is an expanded form of the IF statement that allows you to avoid nesting IF
statements, a common source of logic errors and debugging problems.
related tasks
“Using nested IF statements” on page 92
“Using the EVALUATE statement” on page 93
“Coding conditional expressions” on page 95
IF condition-p
IF condition-q
statement-1
ELSE
statement-2
END-IF
statement-3
ELSE
statement-4
END-IF
In the pseudocode above, an IF statement and a sequential structure are nested in one branch of the
outer IF. In this structure, the END-IF that closes the nested IF is very important. Use END-IF instead
of a period, because a period would end the outer IF structure also.
The following figure shows the logic structure of the pseudocode above.
92 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related tasks
“Coding a choice of actions” on page 91
related references
Explicit scope terminators (Enterprise COBOL for z/OS Language Reference)
You can also use the EVALUATE statement to cause multiple conditions to lead to the same processing, as
shown in these examples:
In an EVALUATE statement, the operands before the WHEN phrase are referred to as selection subjects,
and the operands in the WHEN phrase are called the selection objects. Selection subjects can be identifiers,
literals, conditional expressions, or the word TRUE or FALSE. Selection objects can be identifiers, literals,
conditional or arithmetic expressions, or the word TRUE, FALSE, or ANY.
You can separate multiple selection subjects with the ALSO phrase. You can separate multiple selection
objects with the ALSO phrase. The number of selection objects within each set of selection objects must
be equal to the number of selection subjects, as shown in this example:
“Example: EVALUATE testing several conditions” on page 95
Identifiers, literals, or arithmetic expressions that appear within a selection object must be valid operands
for comparison to the corresponding operand in the set of selection subjects. Conditions or the word TRUE
or FALSE that appear in a selection object must correspond to a conditional expression or the word TRUE
or FALSE in the set of selection subjects. (You can use the word ANY as a selection object to correspond
to any type of selection subject.)
The execution of the EVALUATE statement ends when one of the following conditions occurs:
• The statements associated with the selected WHEN phrase are performed.
related tasks
“Coding a choice of actions” on page 91
related references
EVALUATE statement (Enterprise COBOL for z/OS Language Reference)
General relation conditions (Enterprise COBOL for z/OS Language Reference)
EVALUATE CARPOOL-SIZE
WHEN 1
MOVE "SINGLE" TO PRINT-CARPOOL-STATUS
WHEN 2
MOVE "COUPLE" TO PRINT-CARPOOL-STATUS
WHEN 3 THRU 6
MOVE "SMALL GROUP" TO PRINT-CARPOOL STATUS
WHEN OTHER
MOVE "BIG GROUP" TO PRINT-CARPOOL STATUS
END-EVALUATE
IF CARPOOL-SIZE = 1 THEN
MOVE "SINGLE" TO PRINT-CARPOOL-STATUS
ELSE
IF CARPOOL-SIZE = 2 THEN
MOVE "COUPLE" TO PRINT-CARPOOL-STATUS
ELSE
IF CARPOOL-SIZE >= 3 and CARPOOL-SIZE <= 6 THEN
MOVE "SMALL GROUP" TO PRINT-CARPOOL-STATUS
ELSE
MOVE "BIG GROUP" TO PRINT-CARPOOL-STATUS
END-IF
END-IF
END-IF
EVALUATE MARITAL-CODE
WHEN "M"
ADD 2 TO PEOPLE-COUNT
WHEN "S"
WHEN "D"
WHEN "W"
ADD 1 TO PEOPLE-COUNT
END-EVALUATE
94 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
ADD 2 TO PEOPLE-COUNT
ELSE
IF MARITAL-CODE = "S" OR
MARITAL-CODE = "D" OR
MARITAL-CODE = "W" THEN
ADD 1 TO PEOPLE-COUNT
END-IF
END-IF
Identification Division.
Program-ID. MiniEval.
Environment Division.
Configuration Section.
Source-Computer. IBM-390. Data Division.
Working-Storage Section.
01 Age Pic 999.
01 Sex Pic X.
01 Description Pic X(15).
01 A Pic 999.
01 B Pic 9999.
01 C Pic 9999.
01 D Pic 9999.
01 E Pic 99999.
01 F Pic 999999.
Procedure Division.
PN01.
Evaluate True Also True
When Age < 13 Also Sex = "M"
Move "Young Boy" To Description
When Age < 13 Also Sex = "F"
Move "Young Girl" To Description
When Age > 12 And Age < 20 Also Sex = "M"
Move "Teenage Boy" To Description
When Age > 12 And Age < 20 Also Sex = "F"
Move "Teenage Girl" To Description
When Age > 19 Also Sex = "M"
Move "Adult Man" To Description
When Age > 19 Also Sex = "F"
Move "Adult Woman" To Description
When Other
Move "Invalid Data" To Description
End-Evaluate
Evaluate True Also True
When A + B < 10 Also C = 10
Move "Case 1" To Description
When A + B > 50 Also C = ( D + E ) / F
Move "Case 2" To Description
When Other
Move "Case Other" To Description
End-Evaluate
Stop Run.
related concepts
“Switches and flags” on page 96
related tasks
“Defining switches and flags” on page 97
“Resetting switches and flags” on page 98
“Checking for incompatible data (numeric class test)” on page 53
“Comparing national (UTF-16)
data” on page 145
“Testing for valid DBCS
characters” on page 149
related references
General relation conditions (Enterprise COBOL for z/OS Language Reference)
Class condition (Enterprise COBOL for z/OS Language Reference)
Rules for condition-name entries (Enterprise COBOL for z/OS Language Reference)
Sign condition (Enterprise COBOL for z/OS Language Reference)
Combined conditions (Enterprise COBOL for z/OS Language Reference)
related tasks
“Defining switches and flags” on page 97
“Resetting switches and flags” on page 98
96 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Defining switches and flags
In the DATA DIVISION, define level-88 items that will act as switches or flags, and give them meaningful
names.
To test for more than two values with flags, assign more than one condition-name to a field by using
multiple level-88 items.
The reader can easily follow your code if you choose meaningful condition-names and if the values
assigned to them have some association with logical values.
Example: switches
The following examples show how you can use level-88 items to test for various binary-valued (on-off)
conditions in your program.
For example, to test for the end-of-file condition for an input file named Transaction-File, you can use the
following data definitions:
WORKING-STORAGE SECTION.
01 Switches.
05 Transaction-EOF-Switch Pic X value space.
88 Transaction-EOF value "y".
The level-88 description says that a condition named Transaction-EOF is in effect when
Transaction-EOF-Switch has value 'y'. Referencing Transaction-EOF in the PROCEDURE
DIVISION expresses the same condition as testing Transaction-EOF-Switch = "y". For example,
the following statement causes a report to be printed only if Transaction-EOF-Switch has been set to
'y':
If Transaction-EOF Then
Perform Print-Report-Summary-Lines
End-if
Example: flags
The following examples show how you can use several level-88 items together with an EVALUATE
statement to determine which of several conditions in a program is true.
Consider for example a program that updates a master file. The updates are read from a transaction
file. The records in the file contain a field that indicates which of the three functions is to be performed:
add, change, or delete. In the record description of the input file, code a field for the function code using
level-88 items:
01 Transaction-Input Record
05 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 to determine which function is
to be performed might look like this:
Evaluate True
When Add-Transaction
Perform Add-Master-Record-Paragraph
When Change-Transaction
Perform Update-Existing-Record-Paragraph
When Delete-Transaction
Using the SET statement and meaningful condition-names makes it easier for readers to follow your code.
01 Switches
05 Transaction-EOF-Switch Pic X Value space.
88 Transaction-EOF Value "y".
. . .
Procedure Division.
000-Do-Main-Logic.
Perform 100-Initialize-Paragraph
Read Update-Transaction-File
At End Set Transaction-EOF to True
End-Read
The following example shows how to assign a value to a field in an output record based on the transaction
code of an input record:
01 Input-Record.
05 Transaction-Type Pic X(9).
01 Data-Record-Out.
05 Data-Record-Type Pic X.
88 Record-Is-Active Value "A".
88 Record-Is-Suspended Value "S".
88 Record-Is-Deleted Value "D".
05 Key-Field Pic X(5).
. . .
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
98 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Example: set switch off
The following example shows how you can set a switch off by coding a MOVE statement that moves the
condition name value to the conditional variable.
For example, you can use a data item called SWITCH-OFF to set an on-off switch to off, as in the following
code, which resets a switch to indicate that end-of-file has not been reached:
01 Switches
05 Transaction-EOF-Switch Pic X Value space.
88 Transaction-EOF Value "y".
01 SWITCH-OFF Pic X Value "n".
. . .
Procedure Division.
. . .
Move SWITCH-OFF to Transaction-EOF-Switch
related tasks
“Choosing inline or out-of-line PERFORM” on page 99
“Coding a loop” on page 100
“Looping through a table” on page 101
“Executing multiple paragraphs
or sections” on page 101
related references
PERFORM statement (Enterprise COBOL for z/OS Language Reference)
Perform 100-Initialize-Paragraph
* The following statement is an inline PERFORM:
Perform Until Transaction-EOF
Read Update-Transaction-File Into WS-Transaction-Record
At End
Set Transaction-EOF To True
Not At End
Perform 200-Edit-Update-Transaction
If No-Errors
Perform 300-Update-Commuter-Record
Else
Perform 400-Print-Transaction-Errors
* End-If is a required scope terminator
End-If
Perform 410-Re-Initialize-Fields
* End-Read is a required scope terminator
End-Read
End-Perform
Coding a loop
Use the PERFORM . . . TIMES statement to execute a procedure a specified number of times.
In the example above, when control reaches the PERFORM statement, the code for the procedure 010-
PROCESS-ONE-MONTH is executed 12 times before control is transferred to the INSPECT statement.
Use the PERFORM . . . UNTIL statement to execute a procedure until a condition you choose is
satisfied. You can use either of the following forms:
Use the PERFORM . . . WITH TEST AFTER . . . UNTIL statement if you want to execute the
procedure at least once, and test before any subsequent execution. This statement is equivalent to a
do-until structure:
In the following example, the implicit WITH TEST BEFORE phrase provides a do-while structure:
PERFORM 010-PROCESS-ONE-MONTH
UNTIL MONTH GREATER THAN 12
INSPECT . . .
100 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
When control reaches the PERFORM statement, the condition MONTH GREATER THAN 12 is tested. If the
condition is satisfied, control is transferred to the INSPECT statement. If the condition is not satisfied,
010-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.)
The following section of code shows an example of looping through a table to check for invalid data:
When control reaches the PERFORM statement above, 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 the condition 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.
The loop above controls input-checking for the 12 fields of item WS-DATA. Empty fields are not allowed in
the application, so the section of code loops and issues error messages as appropriate.
related tasks
“Processing table items
using intrinsic functions” on page 87
related references
EXIT PERFORM or EXIT PERFORM CYCLE statement
(Enterprise COBOL for z/OS Language Reference)
EXIT PARAGRAPH or EXIT SECTION statement
(Enterprise COBOL for z/OS Language Reference)
COBOL provides language constructs for performing many different operations on string data items.
For example, you can:
• Join or split data items.
• Manipulate null-terminated strings, such as count or move characters.
• Refer to substrings by their ordinal position and, if needed, length.
• Tally and replace data items, such as count the number of times a specific character occurs in a data
item.
• Convert data items, such as change to uppercase or lowercase.
• Evaluate data items, such as determine the length of a data item.
related tasks
“Joining data items (STRING)” on page 103
“Splitting data items (UNSTRING)” on page 105
“Manipulating null-terminated
strings” on page 108
“Referring to substrings
of data items” on page 109
“Tallying and replacing
data items (INSPECT)” on page 112
“Converting data items (intrinsic functions)” on page 113
“Evaluating data items (intrinsic functions)” on page 117
Chapter 7, “Processing data in an international
environment,” on page 123
related references
STRING statement (Enterprise COBOL for z/OS Language Reference)
01 RCD-01.
05 CUST-INFO.
10 CUST-NAME PIC X(15).
10 CUST-ADDR PIC X(35).
05 BILL-INFO.
10 INV-NO PIC X(6).
10 INV-AMT PIC $$,$$$.99.
10 AMT-PAID PIC $$,$$$.99.
10 DATE-PAID PIC X(8).
10 BAL-DUE PIC $$,$$$.99.
10 DATE-DUE PIC X(8).
The record RCD-01 contains the following information (the symbol b indicates a blank space):
J.B.bSMITHbbbbb
444bSPRINGbST.,bCHICAGO,bILL.bbbbbb
A14275
$4,736.85
$2,400.00
09/22/76
$2,336.85
10/22/76
In the PROCEDURE DIVISION, these settings occur before the STRING statement:
• RPT-LINE is set to SPACES.
• LINE-POS, the data item to be used as the POINTER field, is set to 4.
Here is the 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.
Because the POINTER field LINE-POS has value 4 before the STRING statement is performed, data is
moved into the receiving field RPT-LINE beginning at character position 4. Characters in positions 1
through 3 are unchanged.
The sending items that specify DELIMITED BY SIZE are moved in their entirety to the receiving field.
Because BAL-DUE is delimited by DEC-POINT, the moving of BAL-DUE to the receiving field stops when a
decimal point (the value of DEC-POINT) is encountered.
104 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
STRING results
When the STRING statement is performed, items are moved into RPT-LINE as shown in the table below.
Item Positions
LINE-NO 4-8
Space 9
CUST-INFO 10 - 59
INV-NO 60 - 65
Space 66
DATE-DUE 67 - 74
Space 75
Portion of BAL-DUE that precedes the decimal point 76 - 81
After the STRING statement is performed, the value of LINE-POS is 82, and RPT-LINE has the values
shown below.
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Handling errors in joining and splitting strings” on page 232
related references
UNSTRING statement (Enterprise COBOL for z/OS Language Reference)
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
In the PROCEDURE DIVISION, these settings occur before the UNSTRING statement:
• A period (.) is placed in DBY-1 for use as a delimiter.
• CHAR-CT (the POINTER field) is set to 3.
• The value zero (0) is placed in FLDS-FILLED (the TALLYING field).
• Data is read into record INV-RCD, whose format is as shown below.
106 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Here is the UNSTRING statement:
Because the POINTER field CHAR-CT has value 3 before the UNSTRING statement is performed, the two
character positions of the CONTROL-CHARS field in INV-RCD are ignored.
UNSTRING 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 four 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 five contiguous space characters in positions 19
through 23 are considered to be one occurrence of the delimiter.
3. Positions 24 through 29 (707890) are placed in INV-NO. The delimiter character slash (/) is placed in
DLTR-1, and the value 6 is placed in CTR-2.
4. Positions 31 through 33 (BBA) are placed in INV-CLASS. The delimiter is SPACE, but because no field
has been defined as a receiving area for delimiters, the space in position 34 is bypassed.
5. Positions 35 through 40 (475120) are placed in M-UNITS. The value 6 is placed in CTR-3. The
delimiter is SPACE, but because no field has been defined as a receiving area for delimiters, the space
in position 41 is bypassed.
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 zero (0). The delimiter is SPACE, but because no field was defined as a
receiving area for delimiters, the space in position 47 is bypassed.
7. Positions 48 through 53 (000379) are placed in DISPLAY-DOLS. The period (.) delimiter in DBY-1 is
placed in DLTR-2, and the value 6 is placed in CTR-4.
8. Because all receiving fields have been acted on and two characters in INV-RCD have not been
examined, the ON OVERFLOW statement is executed. Execution of the UNSTRING statement is
completed.
After the UNSTRING statement is performed, the fields contain the values shown below.
Field Value
DISPLAY-REC 707890 FOUR-PENNY-NAILS 000379
WORK-REC 475120000122BBA
CHAR-CT (the POINTER field) 55
FLDS-FILLED (the TALLYING field) 6
MOVE 0 TO char-count
INSPECT source-field TALLYING char-count
FOR CHARACTERS
BEFORE X"00"
• Use an UNSTRING statement to move characters in a null-terminated string to a target field, and get the
character count:
WORKING-STORAGE SECTION.
01 source-field PIC X(1001).
01 char-count COMP-5 PIC 9(4).
01 target-area.
02 individual-char OCCURS 1 TO 1000 TIMES DEPENDING ON char-count
PIC X.
. . .
PROCEDURE DIVISION.
UNSTRING source-field DELIMITED BY X"00"
INTO target-area
COUNT IN char-count
ON OVERFLOW
DISPLAY "source not null terminated or target too short"
END-UNSTRING
• Use a SEARCH statement to locate trailing null or space characters. Define the string being examined as
a table of single characters.
• Check each character in a field in a loop (PERFORM). You can examine each character in a field by using a
reference modifier such as source-field (I:1).
“Example: null-terminated strings” on page 108
related tasks
“Handling null-terminated
strings” on page 497
related references
Alphanumeric literals (Enterprise COBOL for z/OS Language Reference)
108 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
into N.
. . .
* Concatenate two null-terminated strings to produce another:
String L delimited by x'00'
M delimited by x'00'
X'00' delimited by size
into N.
You code a reference modifier in parentheses immediately after the data item. As the example shows, a
reference modifier can contain two values that are separated by a colon, in this order:
1. Ordinal position (from the left) of the character that you want the substring to start with
2. (Optional) Length of the required substring in character positions
The reference-modifier position and length for an item that has USAGE DISPLAY are expressed in
terms of single-byte characters. The reference-modifier position and length for items that have USAGE
DISPLAY-1 or NATIONAL are expressed in terms of DBCS character positions and national character
positions, respectively.
If you omit the length in a reference modifier (coding only the ordinal position of the first character,
followed by a colon), the substring extends to the end of the item. Omit the length where possible as a
simpler and less error-prone coding technique.
You can refer to substrings of USAGE DISPLAY data items, including alphanumeric groups,
alphanumeric-edited data items, numeric-edited data items, display floating-point data items, and zoned
decimal data items, by using reference modifiers. When you reference-modify any of these data items, the
result is of category alphanumeric. When you reference-modify an alphabetic data item, the result is of
category alphabetic.
You can refer to substrings of USAGE NATIONAL data items, including national groups, national-edited
data items, numeric-edited data items, national floating-point data items, and national decimal data
items, by using reference modifiers. When you reference-modify any of these data items, the result is of
category national. For example, suppose that you define a national decimal data item as follows:
You can refer to substrings of table entries, including variable-length entries, by using reference
modifiers. To refer to a substring of a table entry, code the subscript expression before the reference
modifier. For example, assume that PRODUCT-TABLE is a properly coded table of character strings. To
move D to the fourth character in the second string in the table, you can code this statement:
Because numeric function identifiers can be used anywhere that arithmetic expressions can be used, you
can code a numeric function identifier in a reference modifier as the leftmost character position or as the
length, or both.
“Example: intrinsic functions as reference modifiers” on page 111
Each number in the reference modifier must have a value of at least 1. The sum of the two numbers
must not exceed the total length of the data item by more than 1 character position so that you do not
reference beyond the end of the substring.
If the leftmost character position or the length value is a fixed-point noninteger, truncation occurs to
create an integer. If either is a floating-point noninteger, rounding occurs to create an integer.
The SSRANGE compiler option detects out-of-range reference modifiers, and flags violations with a
runtime message.
related concepts
“Reference modifiers” on page 110
“Unicode and the encoding
of language characters” on page 129
related tasks
“Referring to an item in a table” on page 70
related references
“SSRANGE” on page 356
Reference modification (Enterprise COBOL for z/OS Language Reference)
Function definitions (Enterprise COBOL for z/OS Language Reference)
Reference modifiers
Reference modifiers let you easily refer to a substring of a data item.
For example, 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 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 modifiers, you would have to define data items for both formats. You would also have
to write code to convert from one format to the other.
With reference modifiers, you do not need to provide names for the subfields that describe the TIME
elements. The only data definition you need is for the time as returned by the system. For example:
110 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
* 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)
related tasks
“Assigning input from a
screen or file (ACCEPT)” on page 35
“Referring to substrings
of data items” on page 109
“Using national data (Unicode)
in COBOL” on page 129
related references
Reference modification (Enterprise COBOL for z/OS Language Reference)
The program counts the number of leading spaces and, using arithmetic expressions in a reference
modifier, moves the right-justified characters into another field, justified to the left:
The MOVE statement transfers characters from RIGHTY, beginning at the position computed as I + 1 for a
length that is computed as LENGTH OF RIGHTY - I, into the field LEFTY.
If you want to use a noninteger function in a position that requires an integer function, you can use the
INTEGER or INTEGER-PART function to convert the result to an integer. For example:
related references
INTEGER (Enterprise COBOL for z/OS Language Reference)
INTEGER-PART (Enterprise COBOL for z/OS Language Reference)
related concepts
“Unicode and the encoding
of language characters” on page 129
related references
INSPECT statement (Enterprise COBOL for z/OS Language Reference)
112 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
. . .
INSPECT DATA-2
TALLYING COUNTR FOR LEADING "0"
REPLACING FIRST "A" BY "2" AFTER INITIAL "C"
In the following example, the INSPECT statement examines and replaces characters in data item
DATA-3. Each character that precedes the first instance of a quotation mark (") is replaced by the
character 0.
The following example shows the use of INSPECT CONVERTING with AFTER and BEFORE phrases to
examine and replace characters in data item DATA-4. All characters that follow the first instance of the
character / but that precede the first instance of the character ? (if any) are translated from lowercase to
uppercase.
related tasks
“Changing case (UPPER-CASE, LOWER-CASE)” on page 114
“Transforming to reverse order (REVERSE)” on page 114
“Converting to numbers (NUMVAL, NUMVAL-C, NUMVAL-F)” on page 115
“Converting from one code page to another” on page 116
“Converting
to hexadecimal or bit data (HEX-OF, BIT-OF)” on page 116
“Converting
from hexadecimal or bit data (HEX-TO-CHAR, BIT-TO-CHAR)” on page 117
The code above displays the following messages on the system logical output device:
Hello World!
HELLO WORLD!
hello world!
HELLO WORLD!
The DISPLAY statements do not change the actual contents of Item-1, but affect only how the letters
are displayed. However, the MOVE statement causes uppercase letters to replace the contents of Item-2.
Note: The UPPER-CASE and LOWER-CASE intrinsic functions do not support alphanumeric arguments
that contain UTF-8 encoded data.
related tasks
“Assigning input from a
screen or file (ACCEPT)” on page 35
“Displaying values on a
screen or in a file (DISPLAY)” on page 35
For example, the statement above reverses the order of the characters in Orig-cust-name. If the
starting value is JOHNSONbbb, the value after the statement is performed is bbbNOSNHOJ, where b
represents a blank space.
related concepts
“Unicode and the encoding
of language characters” on page 129
114 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Converting to numbers (NUMVAL, NUMVAL-C, NUMVAL-F)
The NUMVAL, NUMVAL-C and NUMVAL-F functions convert character strings (alphanumeric or national
literals, or class alphanumeric or class national data items) to numbers. Use these functions to convert
free-format character-representation numbers to numeric form so that you can process them numerically.
Use NUMVAL-C when the argument includes a currency symbol or comma or both, as shown in the
example above. You can also place an algebraic sign before or after the character string, and the sign
will be processed. The arguments must not exceed 18 digits when you compile with the default option
ARITH(COMPAT) (compatibility mode) nor 31 digits when you compile with ARITH(EXTEND) (extended
mode), not including the editing symbols.
Use NUMVAL-F when the argument includes an exponent value, as shown in the example above. You can
also place an algebraic sign before the character string, and the sign will be processed. The arguments
must not exceed 18 digits when you compile with the default option ARITH(COMPAT) (compatibility
mode) nor 31 digits when you compile with ARITH(EXTEND) (extended mode), not including the editing
symbols.
NUMVAL, NUMVAL-C and NUMVAL-F return long (64-bit) floating-point values in compatibility mode, and
return extended-precision (128-bit) floating-point values in extended mode. A reference to either of these
functions represents a reference to a numeric data item.
At most 15 decimal digits can be converted accurately to long-precision floating point (as described in
the related reference below about conversions and precision). Internally NUMVAL uses long-precision
floating calculations to convert the given number to the output, so if the argument to NUMVAL, NUMVAL-C,
or NUMVAL-F has more than 15 digits, it is recommended that you specify the ARITH(EXTEND) compiler
option so that an extended-precision function result that can accurately represent the value of the
argument is returned. Otherwise, the result may lose precision in an unexpected manner.
When you use NUMVAL, NUMVAL-C, or NUMVAL-F, you do not need to statically define numeric data in a
fixed format nor input data in a precise manner. For example, suppose you define numbers to be entered
as follows:
The user of the application must enter the numbers exactly as defined by the PICTURE clause. For
example:
+001.23
-300.00
01 A Pic x(10).
01 B Pic S999V99.
. . .
Accept A from Console
Compute B = Function Numval(A)
1.23
-300
related concepts
“Formats for numeric
data” on page 47
“Data format conversions” on page 51
“Unicode and the encoding
of language characters” on page 129
related tasks
“Converting to or from national (Unicode) representation” on page 136
related references
“Conversions and precision” on page 52
“ARITH” on page 300
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Converting to or from national (Unicode) representation” on page 136
116 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
converted. The length of the output bit string in bytes is eight times the length of the input argument
string in bytes.
For example, FUNCTION BIT-OF('Hello, world!') returns
'110010001000010110010011100100111001011001101011010000001010011010010110
10011001100100111000010001011010'.
Note: The first eight characters '11001000' of the output string correspond to the hexadecimal value
x'C8', which matches the output of the HEX-OF intrinsic function shown above and corresponds to the
EBCDIC encoding of the letter 'H'.
The argument to the BIT-OF intrinsic function can be a literal, a data item, or the result of an intrinsic
function.
related references
BIT-OF (Enterprise COBOL for z/OS Language Reference)
HEX-OF (Enterprise COBOL for z/OS Language Reference)
related references
BIT-TO-CHAR (Enterprise COBOL for z/OS Language Reference)
HEX-TO-CHAR (Enterprise COBOL for z/OS Language Reference)
related concepts
“Unicode and the encoding
of language characters” on page 129
related tasks
“Evaluating single characters
for collating sequence” on page 118
“Finding the largest or
smallest data item” on page 118
“Finding the length of data
items” on page 120
“Finding the date of compilation” on page 121
If you know the ordinal position in the collating sequence of a character, and want to find the character
that it corresponds to, use the CHAR function with the integer ordinal position as the argument. CHAR
returns the required character. For example:
The ordinal number associated with a character is not the same as the numeric value (in decimal) of
the hex value of the character. For example, if you are using the EBCDIC collating sequence, the ordinal
number of X'00' is one instead of zero. Similarly, the ordinal number of X'FF' is 256 instead of 255.
Therefore, the ordinal values returned from the ORD intrinsic function when using the EBCDIC collating
sequence range from 1 - 256, not 0 - 255 that are the decimal values of the hex values of the valid
EBCDIC characters.
related references
CHAR (Enterprise COBOL for z/OS Language Reference)
ORD (Enterprise COBOL for z/OS Language Reference)
118 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
The MAX and MIN functions return the content of one of the arguments that you supply. For example,
suppose that your program has the following data definitions:
The following statement assigns VALLEJObbb to the first 10 character positions of Customer-record,
where b represents a blank space:
The statement above assigns the integer 3 to x if the same arguments are used as in the previous
example. If you used ORD-MIN instead, the integer 2 would be returned. The examples above might be
more realistic if Arg1, Arg2, and Arg3 were successive elements of an array (table).
If you specify a national item for any argument, you must specify all arguments as class national.
related tasks
“Performing arithmetic” on page 55
“Processing table items
using intrinsic functions” on page 87
“Returning variable results
with alphanumeric or national functions” on page 119
related references
MAX (Enterprise COBOL for z/OS Language Reference)
MIN (Enterprise COBOL for z/OS Language Reference)
ORD-MAX (Enterprise COBOL for z/OS Language Reference)
ORD-MIN (Enterprise COBOL for z/OS Language Reference)
This code has the following results, which are similar to the first set of results except that these are for
national characters:
• R2 is evaluated to be larger than R1.
• The string NX"0066 0020 0020 0020 0020" (the equivalent in national characters of 'fbbbb', where
b represents a blank space), shown here in hexadecimal notation with added spaces for readability, is
moved to R3. The unfilled character positions in R3 are padded with national spaces.
• L evaluates to the value 5, the length in national character positions of R2.
You might be dealing with variable-length output from alphanumeric or national functions. Plan your
program accordingly. For example, you might need to think about using variable-length files when the
records that you are writing could be of different lengths:
File Section.
FD Output-File Recording Mode V.
01 Short-Customer-Record Pic X(50).
01 Long-Customer-Record Pic X(70).
Working-Storage Section.
01 R1 Pic x(50).
01 R2 Pic x(70).
. . .
If R1 > R2
Write Short-Customer-Record from R1
Else
Write Long-Customer-Record from R2
End-if
related tasks
“Finding the largest or
smallest data item” on page 118
“Performing arithmetic” on page 55
related references
MAX (Enterprise COBOL for z/OS Language Reference)
120 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
alphanumeric or national literal, or a data item of any type except DBCS. You can also use the BYTE-
LENGTH function to determine the length of an item in bytes.
LENGTH intrinsic function
The LENGTH function returns the length of a national item (a literal, or any item that has USAGE
NATIONAL, including national group items) as an integer equal to the length of the argument in national
character positions. It returns the length of any other data item as an integer equal to the length of the
argument in alphanumeric character positions.
The following COBOL statement demonstrates moving a data item into the field in a record that holds
customer names:
related tasks
“Performing arithmetic” on page 55
“Creating variable-length
tables (DEPENDING ON)” on page 78
“Processing table items
using intrinsic functions” on page 87
related references
BYTE-LENGTH (Enterprise COBOL for z/OS Language Reference)
LENGTH (Enterprise COBOL for z/OS Language Reference)
LENGTH OF (Enterprise COBOL for z/OS Language Reference)
YYYYMMDDhhmmsshh
You can instead use the WHEN-COMPILED special register to determine the date and time of compilation
in the following format:
MM/DD/YYhh.mm.ss
related references
WHEN-COMPILED (Enterprise COBOL for z/OS Language Reference)
122 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Chapter 7. Processing data in an international
environment
Enterprise COBOL supports Unicode UTF-16 as national character data at run time. UTF-16 provides a
consistent and efficient way to encode plain text. Using UTF-16, you can develop software that will work
with various national languages.
Use these COBOL facilities to code and compile programs that process national data:
• Data types and literals:
– Character data types, defined with the USAGE NATIONAL clause and a PICTURE clause that defines
data of category national, national-edited, or numeric-edited
– Numeric data types, defined with the USAGE NATIONAL clause and a PICTURE clause that defines
a numeric data item (a national decimal item) or an external floating-point data item (a national
floating-point item)
– National literals, specified with literal prefix N or NX
– Figurative constant ALL national-literal
– Figurative constants QUOTE, SPACE, HIGH-VALUE, LOW-VALUE, or ZERO, which have national
character (UTF-16) values when used in national-character contexts
• The COBOL statements shown in the related reference below about COBOL statements and national
data
• Intrinsic functions:
– NATIONAL-OF to convert an alphanumeric or double-byte character set (DBCS) character string to
USAGE NATIONAL (UTF-16)
– DISPLAY-OF to convert a national character string to USAGE DISPLAY in a selected code page
(EBCDIC, ASCII, EUC, or UTF-8)
– The other intrinsic functions shown in the related reference below about intrinsic functions and
national data
• The GROUP-USAGE NATIONAL clause to define groups that contain only USAGE NATIONAL data items
and that behave like elementary category national items in most operations
• Compiler options:
– CODEPAGE to specify the code page to use for alphanumeric and DBCS data in your program
– NSYMBOL to control whether national or DBCS processing is used for the N symbol in literals and
PICTURE clauses
You can also take advantage of implicit conversions of alphanumeric or DBCS data items to national
representation. The compiler performs such conversions (in most cases) when you move these items to
national data items, or compare these items with national data items.
related concepts
“Unicode and the encoding
of language characters” on page 129
“National groups” on page 132
related tasks
“Using national data (Unicode)
in COBOL” on page 129
“Converting to or from national (Unicode) representation” on page 136
“Processing UTF-8 data” on page 140
“Processing Chinese GB 18030 data” on page 144
related references
“COBOL statements and national data” on page 124
“Intrinsic functions and national data” on page 127
“CODEPAGE” on page 304
“NSYMBOL” on page 335
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
Data categories and PICTURE rules
(Enterprise COBOL for z/OS Language Reference)
MOVE statement (Enterprise COBOL for z/OS Language Reference)
General relation conditions (Enterprise COBOL for z/OS Language Reference)
124 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 15. COBOL statements and national data (continued)
COBOL Can be national Comment For more information
statement
DIVIDE All identifiers can be “Using COMPUTE and other
numeric items that arithmetic statements” on page 55
have USAGE NATIONAL.
identifier-3 (GIVING) and
identifier-4 (REMAINDER)
can be numeric-edited
with USAGE NATIONAL.
INITIALIZE identifier-1; identifier-2 If you specify REPLACING “Examples: initializing data items” on
or literal-1 of the NATIONAL or REPLACING page 28
REPLACING phrase NATIONAL-EDITED,
identifier-2 or literal-1
must be valid as a sending
operand in a move to
identifier-1.
INSPECT All identifiers and If any of these (other “Tallying and replacing data items
literals. (identifier-2, the than identifier-2, the (INSPECT)” on page 112
TALLYING integer data TALLYING identifier) have
item, can have USAGE USAGE NATIONAL, all
NATIONAL.) must be national.
INVOKE Method-name as “Invoking methods (INVOKE)” on
identifier-2 or literal-1; page 612
identifier-3 or literal-2 in
the BY VALUE phrase
JSON PARSE identifier-2 (the target identifier-1 is not Chapter 30, “Processing JSON
data item); identifier-3 supported as a national input ,” on page 529
(the NAME identifier); data item.
literal-1 (the NAME
substitution); identifier-4
(the SUPPRESS identifier)
MERGE Merge keys The COLLATING “Setting sort or merge criteria” on
SEQUENCE phrase does page 219
not apply.
MOVE Both the sender and Implicit conversions are “Assigning values to elementary data
receiver, or only the performed for valid MOVE items (MOVE)” on page 32
receiver operands.
“Assigning values to group data items
(MOVE)” on page 33
126 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 15. COBOL statements and national data (continued)
COBOL Can be national Comment For more information
statement
XML PARSE identifier-1 (the XML The XML-NTEXT special Chapter 32, “Processing XML input,”
document) register contains on page 537
national character
document fragments
during parsing. XML-
NNAMESPACE and XML-
NNAMESPACE-PREFIX
special registers
contain the associated
namespace identifier and
namespace prefix, if any,
in national characters.
related tasks
“Defining numeric data” on page 43
“Displaying numeric data” on page 45
“Using national data (Unicode)
in COBOL” on page 129
“Comparing national (UTF-16)
data” on page 145
related references
“CODEPAGE” on page 304
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
You can use national decimal arguments wherever zoned decimal arguments are allowed. You can use
national floating-point arguments wherever display floating-point arguments are allowed. (See the related
reference below about arguments for a complete list of intrinsic functions that can take integer or numeric
arguments.)
Related tasks
“Defining numeric data” on page 43
“Using national data (Unicode)
in COBOL” on page 129
Related references
Arguments (Enterprise COBOL for z/OS Language Reference)
128 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
Intrinsic functions (Enterprise COBOL for z/OS Language Reference)
related tasks
“Converting to or from national (Unicode) representation” on page 136
related references
“Storage of character data” on page 136
Character sets and code pages (Enterprise COBOL for z/OS Language Reference)
related concepts
“Unicode and the encoding
related tasks
“Defining national data
items” on page 130
“Using national literals” on page 130
“Using national-character
figurative constants” on page 131
“Defining national numeric
data items” on page 132
“Using national groups” on page 133
“Converting to or from national (Unicode) representation” on page 136
“Comparing national (UTF-16)
data” on page 145
related references
“Storage of character data” on page 136
Classes and categories of data (Enterprise COBOL for z/OS Language Reference)
related tasks
“Displaying numeric data” on page 45
related references
“NSYMBOL” on page 335
BLANK WHEN ZERO clause (Enterprise COBOL for z/OS Language Reference)
130 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
You can use either of these notations:
• N"character-data"
• N'character-data'
If you compile with the option NSYMBOL(DBCS), the literal prefix character N specifies a DBCS literal, not
a national literal.
To specify a national literal as a hexadecimal value, use the prefix NX. You can use either of these
notations:
• NX"hexadecimal-digits"
• NX'hexadecimal-digits'
Each of the following MOVE statements sets the national data item Y to the UTF-16 value of the characters
'AB':
Do not use alphanumeric hexadecimal literals in contexts that call for national literals, because such
usage is easily misunderstood. For example, the following statement also results in moving the UTF-16
characters 'AB' (not the hexadecimal bit pattern C1C2) to Y, where Y is defined as USAGE NATIONAL:
Move X"C1C2" to Y
You cannot use national literals in the SPECIAL-NAMES paragraph or as program-names. You can use
a national literal to name an object-oriented method in the METHOD-ID paragraph or to specify a method-
name in an INVOKE statement.
related tasks
“Using literals” on page 25
related references
“NSYMBOL” on page 335
National literals (Enterprise COBOL for z/OS Language Reference)
You can use the figurative constants QUOTE, SPACE, HIGH-VALUE, LOW-VALUE, or ZERO in a context that
requires national characters, such as a MOVE statement, an implicit move, or a relation condition that has
national operands. In these contexts, the figurative constant represents a national-character (UTF-16)
value.
When you use the figurative constant QUOTE in a context that requires national characters, and the
QUOTE compiler option is in effect, its value is NX'0022'. If the APOST compiler option is in effect, its
value is NX'0027'.
When you use the figurative constant HIGH-VALUE in a context that requires national characters, its
value is NX'FFFF'. When you use LOW-VALUE in a context that requires national characters, its value is
NX'0000'.
Restrictions: You must not use HIGH-VALUE or the value assigned from HIGH-VALUE in a way that
results in conversion of the value from one data representation to another (for example, between
USAGE DISPLAY and USAGE NATIONAL). X'FF' (the value of HIGH-VALUE in an alphanumeric context
The IF statement above evaluates as false even though each of its operands was set to HIGH-VALUE.
Before an elementary alphanumeric operand is compared to a national operand, the alphanumeric
operand is treated as though it were moved to a temporary national data item, and the alphanumeric
characters are converted to the corresponding national characters. When X'FF' is converted to UTF-16,
however, the UTF-16 item gets a substitution character value and so does not compare equally to
NX'FFFF'.
related tasks
“Converting to or from national (Unicode) representation” on page 136
“Comparing national (UTF-16)
data” on page 145
related references
Figurative constants (Enterprise COBOL for z/OS Language Reference)
DISPLAY-OF (Enterprise COBOL for z/OS Language Reference)
Support for Unicode: Using Unicode Services
To define a national decimal item, code a PICTURE clause that contains only the symbols 9, P, S, and V. If
the PICTURE clause contains S, the SIGN IS SEPARATE clause must be in effect for that item.
To define a national floating-point item, code a PICTURE clause that defines a floating-point item (for
example, +99999.9E-99).
You can use national decimal items in the same way that you use zoned decimal items. You can use
national floating-point items in the same way that you use display floating-point items.
related tasks
“Defining numeric data” on page 43
“Displaying numeric data” on page 45
related references
SIGN clause (Enterprise COBOL for z/OS Language Reference)
National groups
National groups, which are specified either explicitly or implicitly with the GROUP-USAGE NATIONAL
clause, contain only data items that have USAGE NATIONAL. In most cases, a national group item is
processed as though it were redefined as an elementary category national item described as PIC N(m),
where m is the number of national (UTF-16) characters in the group.
For some operations on national groups, however (just as for some operations on alphanumeric groups),
group semantics apply. Such operations (for example, MOVE CORRESPONDING and INITIALIZE)
recognize or process the elementary items within the national group.
132 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Where possible, use national groups instead of alphanumeric groups that contain USAGE NATIONAL
items. National groups provide several advantages for the processing of national data compared to the
processing of national data within alphanumeric groups:
• When you move a national group to a longer data item that has USAGE NATIONAL, the receiving item is
padded with national characters. By contrast, if you move an alphanumeric group that contains national
characters to a longer alphanumeric group that contains national characters, alphanumeric spaces are
used for padding. As a result, mishandling of data items could occur.
• When you move a national group to a shorter data item that has USAGE NATIONAL, the national
group is truncated at national-character boundaries. By contrast, if you move an alphanumeric group
that contains national characters to a shorter alphanumeric group that contains national characters,
truncation might occur between the 2 bytes of a national character.
• When you move a national group to a national-edited or numeric-edited item, the content of the group is
edited. By contrast, if you move an alphanumeric group to an edited item, no editing takes place.
• When you use a national group as an operand in a STRING, UNSTRING, or INSPECT statement:
– The group content is processed as national characters rather than as single-byte characters.
– TALLYING and POINTER operands operate at the logical level of national characters.
– The national group operand is supported with a mixture of other national operand types.
By contrast, if you use an alphanumeric group that contains national characters in these contexts, the
characters are processed byte by byte. As a result, invalid handling or corruption of data could occur.
USAGE NATIONAL groups: A group item can specify the USAGE NATIONAL clause at the group level
as a convenient shorthand for the USAGE of each of the elementary data items within the group. Such
a group is not a national group, however, but an alphanumeric group, and behaves in many operations,
such as moves and compares, like an elementary data item of USAGE DISPLAY (except that no editing or
conversion of data occurs).
related tasks
“Assigning values to group
data items (MOVE)” on page 33
“Joining data items (STRING)” on page 103
“Splitting data items (UNSTRING)” on page 105
“Tallying and replacing
data items (INSPECT)” on page 112
“Using national groups” on page 133
related references
GROUP-USAGE clause (Enterprise COBOL for z/OS Language Reference)
01 Alpha-Group-1.
02 Group-1.
04 Month PIC 99.
04 DayOf PIC 99.
04 Year PIC 9999.
02 Group-2 GROUP-USAGE NATIONAL.
04 Amount PIC 9(4).99.
In the example above, Alpha-Group-1 and Group-1 are alphanumeric groups; USAGE DISPLAY is
implied for the subordinate items in Group-1. (If Alpha-Group-1 specified USAGE NATIONAL at the
group level, USAGE NATIONAL would be implied for each of the subordinate items in Group-1. However,
Alpha-Group-1 and Group-1 would be alphanumeric groups, not national groups, and would behave
like alphanumeric groups during operations such as moves and compares.) Group-2 is a national group,
and USAGE NATIONAL is implied for the numeric-edited item Amount.
You cannot subordinate alphanumeric groups within national groups. All elementary items within a
national group must be explicitly or implicitly described as USAGE NATIONAL, and all group items within
a national group must be explicitly or implicitly described as GROUP-USAGE NATIONAL.
related concepts
“National groups” on page 132
related tasks
“Using national groups
as elementary items” on page 134
“Using national groups
as group items” on page 135
related references
GROUP-USAGE clause (Enterprise COBOL for z/OS Language Reference)
If Group-1 were instead an alphanumeric group in which each of its subordinate items had USAGE
NATIONAL (specified either explicitly with a USAGE NATIONAL clause on each elementary item, or
implicitly with a USAGE NATIONAL clause at the group level), a group move, rather than an elementary
move, would occur. Neither editing nor conversion would take place during the move. The value in the first
eight character positions of Edited-date after the move would be 06232010 in national characters, and
the value in the remaining two character positions would be 4 bytes of alphanumeric spaces.
134 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related tasks
“Assigning values to group
data items (MOVE)” on page 33
“Comparing national data
and alphanumeric-group operands” on page 147
“Using national groups
as group items” on page 135
related references
MOVE statement (Enterprise COBOL for z/OS Language Reference)
In the following example, an INITIALIZE statement that acts upon national group item Group-OneN
causes the value 15 in national characters to be moved to only the numeric items in the group:
Because only Trans-quanN in Group-OneN above is numeric, only Trans-quanN receives the value 15.
The other subordinate items are unchanged.
The table below summarizes the cases where national groups are processed with group semantics.
Table 17. National group items that are processed with group semantics
Language feature Uses of national group items Comment
CORRESPONDING phrase Specify a national group item for Elementary items within the
of the ADD, SUBTRACT, processing as a group in accordance national group are processed like
or MOVE statement with the rules of the CORRESPONDING elementary items that have USAGE
phrase. NATIONAL within an alphanumeric
group.
Host variable in EXEC Specify a national group item as a host The national group item is in effect
SQL statement variable. shorthand for the set of host
variables that are subordinate to
the group item.
INITIALIZE statement Specify a national group for processing Elementary items within the
as a group in accordance with the rules national group are initialized like
of the INITIALIZE statement. elementary items that have USAGE
NATIONAL within an alphanumeric
group.
Name qualification Use the name of a national group item Follow the same rules
to qualify the names of elementary data for qualification as for an
items and of subordinate group items in alphanumeric group.
the national group.
THROUGH phrase of the To specify a national group item in the The result is an alphanumeric
RENAMES clause THROUGH phrase, use the same rules as group item.
for an alphanumeric group item.
related tasks
“Initializing a structure
(INITIALIZE)” on page 31
“Initializing a table (INITIALIZE)” on page 73
“Assigning values to elementary
data items (MOVE)” on page 32
“Assigning values to group
data items (MOVE)” on page 33
“Finding the length of data
items” on page 120
“Generating XML output” on page 577
“Using national group items in SQL statements” on page 442
related references
Qualification (Enterprise COBOL for z/OS Language Reference)
RENAMES clause (Enterprise COBOL for z/OS Language Reference)
Table 18. Encoding and size of alphanumeric, DBCS, and national data
Characteristic DISPLAY DISPLAY-1 NATIONAL
Character encoding unit 1 byte 2 bytes 2 bytes
Code page EBCDIC EBCDIC DBCS UTF-16BE1
Encoding units per graphic 1 1 1 or 22
character
Bytes per graphic character 1 byte 2 bytes 2 or 4 bytes
1. Use the CODEPAGE compiler option to specify the EBCDIC code page that is applicable to
alphanumeric or DBCS data.
2. Most characters are represented in UTF-16 using one encoding unit. In particular, the following
characters are represented using a single UTF-16 encoding unit per character:
• COBOL characters A-Z, a-z, 0-9, space, + - * / = $ , ; . " ( ) > < :'
• All characters that are converted from an EBCDIC or ASCII code page
related concepts
“Unicode and the encoding
of language characters” on page 129
136 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
You can implicitly convert alphabetic, alphanumeric, DBCS, or integer data to national data by using the
MOVE statement. Implicit conversions also take place in other COBOL statements, such as IF statements
that compare an alphanumeric data item with a data item that has USAGE NATIONAL.
You can explicitly convert to and from national data items by using the intrinsic functions NATIONAL-OF
and DISPLAY-OF, respectively. By using these intrinsic functions, you can specify a code page for the
conversion that is different from the code page that is in effect with the CODEPAGE compiler option.
related tasks
“Converting alphanumeric,
DBCS, and integer to national (MOVE)” on page 137
“Converting alphanumeric
or DBCS to national (NATIONAL-OF)” on page 138
“Converting national to
alphanumeric (DISPLAY-OF)” on page 138
“Overriding the default code page” on page 138
“Comparing national (UTF-16)
data” on page 145
related references
“CODEPAGE” on page 304
“Conversion exceptions” on page 139
You can move the following kinds of data to category national or national-edited data items, and thus
convert the data to national representation:
• Alphabetic
• Alphanumeric
• Alphanumeric-edited
• DBCS
• Integer of USAGE DISPLAY
• Numeric-edited of USAGE DISPLAY
You can likewise move the following kinds of data to numeric-edited data items that have USAGE
NATIONAL:
• Alphanumeric
• Display floating-point (floating-point of USAGE DISPLAY)
• Numeric-edited of USAGE DISPLAY
• Integer of USAGE DISPLAY
For complete rules about moves to national data, see the related reference about the MOVE statement.
For example, the MOVE statement below moves the alphanumeric literal "AB" to the national data item
UTF16-Data:
After the MOVE statement above, UTF16-Data contains NX'00410042', the national representation of
the alphanumeric characters 'AB'.
related tasks
“Assigning values to elementary
data items (MOVE)” on page 32
“Assigning values to group
data items (MOVE)” on page 33
“Displaying numeric data” on page 45
“Coding for use of DBCS support” on page 147
related references
MOVE statement (Enterprise COBOL for z/OS Language Reference)
related references
“CODEPAGE” on page 304
NATIONAL-OF (Enterprise COBOL for z/OS Language Reference)
related references
DISPLAY-OF (Enterprise COBOL for z/OS Language Reference)
If you specify a code page as an argument to the DISPLAY-OF intrinsic function, and the code page
differs from the code page that is in effect with the CODEPAGE compiler option, do not use the function
138 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
result in any operations that involve implicit conversion (such as an assignment to, or comparison with, a
national data item). Such operations assume the EBCDIC code page that is specified with the CODEPAGE
compiler option.
related references
“CODEPAGE” on page 304
Conversion exceptions
Implicit or explicit conversion between national data and alphanumeric data can fail and generate a
severity-3 Language Environment condition.
Failure can occur if the code page that you specified implicitly or explicitly is not a valid code page.
A character that does not have a counterpart in the target CCSID does not result in a conversion
exception. Such a character is converted to a substitution character in the target code page.
related references
“CODEPAGE” on page 304
CBL CODEPAGE(00037)
* . . .
01 Data-in-Unicode pic N(100) usage national.
01 Data-in-Greek pic X(100).
01 other-data-in-US-English pic X(12) value "PRICE in $ =".
* . . .
Read Greek-file into Data-in-Greek
Move function National-of(Data-in-Greek, 00875)
to Data-in-Unicode
* . . . process Data-in-Unicode here . . .
Move function Display-of(Data-in-Unicode, 00875)
to Data-in-Greek
Write Greek-record from Data-in-Greek
The example above works correctly because the input code page is specified. Data-in-Greek is
converted as data represented in CCSID 00875 (Greek). However, the following statement results in an
incorrect conversion unless all the characters in the item happen to be among those that have a common
representation in both the Greek and the English code pages:
The MOVE statement above converts Data-in-Greek to Unicode representation based on the CCSID
00037 (U.S. English) to UTF-16 conversion. This conversion does not produce the expected results
because Data-in-Greek is encoded in CCSID 00875.
If you can correctly set the CODEPAGE compiler option to CCSID 00875 (that is, the rest of your program
also handles EBCDIC data in Greek), you can code the same example correctly as follows:
CBL CODEPAGE(00875)
* . . .
01 Data-in-Unicode pic N(100) usage national.
01 Data-in-Greek pic X(100).
* . . .
Read Greek-file into Data-in-Greek
* . . . process Data-in-Greek here ...
* . . . or do the following (if need to process data in Unicode):
Move Data-in-Greek to Data-in-Unicode
* . . . process Data-in-Unicode
Usage note: Use care if you use reference modification to refer to data encoded in UTF-8. UTF-8
characters are encoded with a varying number of bytes per character. Avoid operations that might split a
multibyte character.
related tasks
“Referring to substrings
of data items” on page 109
“Converting to or from national (Unicode) representation” on page 136
“Parsing XML documents
encoded in UTF-8” on page 558
“Using intrinsic functions to process UTF-8 encoded data” on page 140
140 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
UPOS
To determine the byte position in the string of the nth Unicode code point
UWIDTH
To determine the width in bytes of the nth Unicode code point in the string
The following code fragment illustrates UTF-8 validity checking, and the use of the auxiliary functions:
checkUTF-8-validity.
Compute u = function UVALID(UTF-8-testStr)
If u not = 0
Display 'checkUTF-8-validity failure:'
Display ' The UTF-8 representation is not valid,'
'starting at byte ' u '.'
Compute v = function ULENGTH(UTF-8-testStr(1:u - 1))
Compute u = function UPOS(UTF-8-testStr v)
Compute w = function UWIDTH(UTF-8-testStr v)
Display ' The ' v 'th and last valid code point starts '
'at byte ' u ' for ' w ' bytes.'
End-if.
In the following string, the sequence that starts with x'F5' is not valid UTF-8 because no byte can have a
value in the range x'F5' to x'FF':
x'6162D0B0E4BA8CF5646364'
checkUTF-8-validity failure:
The UTF-8 representation is not valid, starting at byte 08.
The 04th and last valid code point starts at byte 05 for 03 bytes.
The following code fragment illustrates checking for the presence of a Unicode supplementary code point,
requiring a 4-byte representation in UTF-8:
checkUTF-8-supp.
Compute u = function USUPPLEMENTARY(UTF-8-testStr)
If u not = 0
Display ' checkUTF-8-supp hit:'
Compute v = function ULENGTH(UTF-8-testStr(1:u - 1))
Compute w = function UWIDTH(UTF-8-testStr v + 1)
Display ' The ' v 'th code point of the string'
', starting at byte ' u ','
Display ' is a Unicode supplementary code point, '
'width ' w ' bytes.'
End-if.
In the following string, the sequence x'F0908C82' is a supplementary character (as is any valid UTF-8
sequence beginning with a byte in the range x'F0' to x'F4'):
x'6162D0B0E4BA8CF0908C826364'
checkUTF-8-supp hit:
The 04th code point of the string, starting at byte 08,
is a Unicode supplementary code point, width 04 bytes.
related references
“CODEPAGE” on page 304
142 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Program initials, continued
Program toHex
Identification division.
Program-id. toHex.
Data division.
Working-storage section.
1 hexv.
2 pic x(32) value '000102030405060708090A0B0C0D0E0F'.
2 pic x(32) value '101112131415161718191A1B1C1D1E1F'.
2 pic x(32) value '202122232425262728292A2B2C2D2E2F'.
2 pic x(32) value '303132333435363738393A3B3C3D3E3F'.
2 pic x(32) value '404142434445464748494A4B4C4D4E4F'.
2 pic x(32) value '505152535455565758595A5B5C5D5E5F'.
2 pic x(32) value '606162636465666768696A6B6C6D6E6F'.
Enterprise COBOL does not have explicit support for GB 18030, but does support the processing of GB
18030 characters in several ways. You can:
• Use DBCS data items to process GB 18030 characters that are represented in CCSID 1388.
• Use national data items to define and process GB 18030 characters that are represented in UTF-16,
CCSID 01200.
• Process data in any code page (including CCSID 1388 or 1392) by converting the data to
UTF-16, processing the UTF-16 data, and then converting the data back to the original code-page
representation.
When you need to process Chinese GB 18030 data that requires conversion, first convert the input data
to UTF-16 in a national data item. After you process the national data item, convert it back to Chinese
GB 18030 for output. For the conversions, use the intrinsic functions NATIONAL-OF and DISPLAY-OF,
respectively, and specify code page 1388 or 1392 as the second argument of each function.
The following example illustrates these conversions:
144 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related tasks
“Converting to or from national (Unicode) representation” on page 136
“Coding for use of DBCS support” on page 147
related references
“Storage of character data” on page 136
related tasks
“Comparing two class national
operands” on page 145
“Comparing class national
and class numeric operands” on page 146
“Comparing national numeric
and other numeric operands” on page 146
“Comparing national and
other character-string operands” on page 147
“Comparing national data
and alphanumeric-group operands” on page 147
related references
Relation conditions (Enterprise COBOL for z/OS Language Reference)
General relation conditions (Enterprise COBOL for z/OS Language Reference)
National comparisons (Enterprise COBOL for z/OS Language Reference)
Group comparisons (Enterprise COBOL for z/OS Language Reference)
Either operand (or both) can be any of the following types of items:
• A national group
• An elementary category national or national-edited data item
One of the operands can instead be a national literal or a national intrinsic function.
When you compare two class national operands that have the same length, they are determined to be
equal if all pairs of the corresponding characters are equal. Otherwise, comparison of the binary values of
the first pair of unequal characters determines the operand with the larger binary value.
When you compare operands that have unequal lengths, the shorter operand is treated as if it were
padded on the right with default UTF-16 space characters (NX'0020') to the length of the longer
operand.
The PROGRAM COLLATING SEQUENCE clause does not affect the comparison of two class national
operands.
related concepts
“National groups” on page 132
related tasks
“Using national groups” on page 133
related references
National comparisons (Enterprise COBOL for z/OS Language Reference)
You can also compare national literals or class national data items to floating-point data items (that is,
display floating-point or national floating-point items).
Numeric operands are converted to national (UTF-16) representation if they are not already in national
representation. A comparison is made of the national character values of the operands.
related references
General relation conditions (Enterprise COBOL for z/OS Language Reference)
You can compare the algebraic values of numeric operands regardless of their USAGE. Thus you can
compare a national decimal item or a national floating-point item with a binary item, an internal-decimal
item, a zoned decimal item, a display floating-point item, or any other numeric item.
related tasks
“Defining national numeric
data items” on page 132
related references
General relation conditions (Enterprise COBOL for z/OS Language Reference)
146 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Comparing national and other character-string operands
You can compare the character value of a national literal or class national data item with the character
value of any of the following other character-string operands: alphabetic, alphanumeric, alphanumeric-
edited, DBCS, or numeric-edited of USAGE DISPLAY.
These operands are treated as if they were moved to an elementary national data item. The characters
are converted to national (UTF-16) representation, and the comparison proceeds with two national
character operands.
related tasks
“Using national-character
figurative constants” on page 131
related references
National comparisons (Enterprise COBOL for z/OS Language Reference)
Neither operand is converted. The national operand is treated as if it were moved to an alphanumeric
group item of the same size in bytes as the national operand, and the two groups are compared.
An alphanumeric comparison is done regardless of the representation of the subordinate items in the
alphanumeric group operand.
For example, Group-XN is an alphanumeric group that consists of two subordinate items that have USAGE
NATIONAL:
01 Group-XN.
02 TransCode PIC NN Value "AB" Usage National.
02 Quantity PIC 999 Value 123 Usage National.
. . .
If N"AB123" = Group-XN Then Display "EQUAL"
Else Display "NOT EQUAL".
When the IF statement above is executed, the 10 bytes of the national literal N"AB123" are compared
byte by byte to the content of Group-XN. The items compare equally, and "EQUAL" is displayed.
related references
Group comparisons (Enterprise COBOL for z/OS Language Reference)
related references
“DBCS” on page 311
You can specify a DBCS data item by using the USAGE DISPLAY-1 clause. When you use PICTURE
symbol G, you must specify USAGE DISPLAY-1. When you use PICTURE symbol N but omit the USAGE
clause, USAGE DISPLAY-1 or USAGE NATIONAL is implied depending on the setting of the NSYMBOL
compiler option.
If you use a VALUE clause with the USAGE clause in the definition of a DBCS item, you must specify a
DBCS literal or the figurative constant SPACE or SPACES.
For the purpose of handling reference modifications, each character in a DBCS data item is considered to
occupy the number of bytes that corresponds to the code-page width (that is, 2).
related references
“NSYMBOL” on page 335
That is, you can specify a DBCS literal in either of these ways:
• N'dbcs characters' (provided that the compiler option NSYMBOL(DBCS) is in effect)
• G'dbcs characters'
You can use quotation marks (") or apostrophes (') as the delimiters of a DBCS literal irrespective of the
setting of the APOST or QUOTE compiler option. You must code the same opening and closing delimiter for
a DBCS literal.
The shift-out (SO) control character X'0E' must immediately follow the opening delimiter, and the
shift-in (SI) control character X'0F' must immediately precede the closing delimiter.
In addition to DBCS literals, you can use alphanumeric literals to specify any character in one of the
supported code pages. However, any string of DBCS characters that is within an alphanumeric literal must
be delimited by the SO and SI characters, and the DBCS compiler option must be in effect for the SO and
SI characters to be recognized as shift codes.
You cannot continue an alphanumeric literal that contains DBCS characters. The length of a DBCS literal is
likewise limited by the available space in Area B on a single source line. The maximum length of a DBCS
literal is thus 28 double-byte characters.
An alphanumeric literal that contains DBCS characters is processed byte by byte, that is, with semantics
appropriate for single-byte characters, except when it is converted explicitly or implicitly to national data
representation, as for example in an assignment to or comparison with a national data item.
related tasks
“Using figurative constants” on page 26
148 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
related references
“APOST/QUOTE” on page 298
“DBCS” on page 311
“NSYMBOL” on page 335
DBCS literals (Enterprise COBOL for z/OS Language Reference)
The Kanji class test is done by checking characters for the range X'41' through X'7E' in the first byte
and X'41' through X'FE' in the second byte, plus the space character X'4040'.
The DBCS class test tests for valid graphic characters for the code page.
The DBCS class test is done by checking characters for the range X'41' through X'FE' in both the first
and second byte of each character, plus the space character X'4040'.
related tasks
“Coding conditional expressions” on page 95
related references
Class condition (Enterprise COBOL for z/OS Language Reference)
related tasks
“Joining data items (STRING)” on page 103
“Splitting data items (UNSTRING)” on page 105
“Referring to substrings
of data items” on page 109
“Converting to or from national (Unicode) representation” on page 136
Processing data is an essential part of every program. Your program retrieves information, processes it as
you request, and then produces the results.
The source of the information and the target for the results can be one or more of the following items:
• Another program
• Hierarchical or relational database
• Messages from subsystem software
• Direct-access storage device
• Magnetic tape
• Printer
• Terminal
• Card reader or punch
The information as it exists on an external device might be in a physical record or block, a collection of
information that is handled as a unit by the system during input or output operations.
Your COBOL program does not directly handle physical records. It processes logical records. A logical
record can correspond to a complete physical record, part of a physical record, or to parts or all of one or
more physical records. Your COBOL program handles logical records exactly as you have defined them.
In COBOL, a collection of logical records is a file, a sequence of pieces of information that your program
can process.
related concepts
“File organization and input-output devices” on page 151
related tasks
“Choosing file organization and access mode” on page 152
“Allocating files” on page 154
“Checking for input or output errors” on page 155
related tasks
“Allocating files” on page 154
Chapter 9, “Processing QSAM files,” on page 157
Chapter 10, “Processing VSAM files,” on page 179
Chapter 11, “Processing line-sequential files,” on page 205
“Choosing file organization and access mode” on page 152
152 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
• If an application accesses records (whether fixed-length or variable-length) only sequentially and does
not insert records between existing records, a QSAM or VSAM sequential file is the simplest type.
• If you are developing an application for z/OS UNIX file system that sequentially accesses records that
contain only printable characters and certain control characters, line-sequential files work best.
• If an application requires both sequential and random access (whether records are fixed length or
variable length), a VSAM indexed file is the most flexible type.
• If an application inserts and deletes records randomly, a relative file works well.
Consider the following guidelines when choosing access mode:
• If a large percentage of a file is referenced or updated in an application, sequential access is faster than
random or dynamic access.
• If a small percentage of records is processed during each run of an application, use random or dynamic
access.
Table 19. Summary of file organizations, access modes, and record formats of COBOL files
File organization Sequential Random Dynamic Fixed length Variable
access access access length
QSAM (physical sequential) X X X
Line sequential X X1 X
VSAM sequential (ESDS) X X X
VSAM indexed (KSDS) X X X X X
VSAM relative (RRDS) X X X X X
1. The data itself is in variable format but can be read into and written from COBOL fixed-length
records.
related references
“Format for coding input and output” on page 153
“Control characters in line-sequential files” on page 206
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
01 recordname (6)
nn . . . fieldlength & type (7) (8)
nn . . . fieldlength & type
. . .
WORKING-STORAGE SECTION
01 file-status PICTURE 99.
. . .
PROCEDURE DIVISION.
. . .
OPEN iomode filename (9)
. . .
READ filename
related tasks
Chapter 9, “Processing QSAM files,” on page 157
Chapter 10, “Processing VSAM files,” on page 179
Chapter 11, “Processing line-sequential files,” on page 205
Allocating files
For any type of file (sequential, line sequential, indexed, or relative) in your z/OS or z/OS UNIX
applications, you can define the external name with either a ddname or an environment-variable name.
The external name is the name in the assignment-name of the ASSIGN clause.
If the file is in the z/OS UNIX file system, you can use either a DD definition or an environment variable to
define the file by specifying its path name with the PATH keyword.
The environment-variable name must be uppercase. The allowable attributes for its value depend on the
organization of the file being defined.
154 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Because you can define the external name in either of two ways, the COBOL run time goes through the
following steps to find the definition of the file:
1. If the ddname is explicitly allocated, it is used. The definition can be from a DD statement in JCL, an
ALLOCATE command from TSO/E, or a user-initiated dynamic allocation.
2. If the ddname is not explicitly allocated and an environment variable of the same name is set, the
value of the environment variable is used.
The file is dynamically allocated using the attributes specified by the environment variable. At a
minimum, you must specify either the PATH() or DSN() option. All options and attributes must be in
uppercase, except for the path-name suboption of the PATH option, which is case sensitive. You cannot
specify a temporary data-set name in the DSN() option.
File status code 98 results from any of the following cases:
• The contents (including a value of null or all blanks) of the environment variable are not valid.
• The dynamic allocation of the file fails.
• The dynamic deallocation of the file fails.
The COBOL run time checks the contents of the environment variable at each OPEN statement. If
a file with the same external name was dynamically allocated by a previous OPEN statement, and
the contents of the environment variable have changed since that OPEN, the run time dynamically
deallocates the previous allocation and reallocates the file using the options currently set in the
environment variable. If the contents of the environment variable have not changed, the run time uses
the current allocation.
3. If neither a ddname nor an environment variable is defined, the following steps occur:
a) If the allocation is for a QSAM file and the CBLQDA runtime option is in effect, CBLQDA dynamic
allocation processing takes place for those eligible files. This type of "implicit" dynamic allocation
persists for the life of the run unit and cannot be reallocated.
b) Otherwise, the allocation fails.
The COBOL run time deallocates all dynamic allocations at run unit termination, except for implicit
CBLQDA allocations.
related tasks
“Setting and accessing environment variables” on page 460
“Defining and allocating QSAM files” on page 170
“Dynamically creating QSAM files” on page 167
“Allocating VSAM files” on page 198
related tasks
“Handling errors in input
and output operations” on page 233
“Coding ERROR declaratives” on page 236
“Using file status keys” on page 237
related concepts
z/OS DFSMS: Using Data Sets (Access methods)
related tasks
“Defining QSAM files and records in COBOL” on page 157
“Coding input and output
statements for QSAM files” on page 166
“Handling errors in QSAM files” on page 169
“Working with QSAM files” on page 169
“Accessing z/OS UNIX files
using QSAM” on page 176
“Processing QSAM ASCII files on tape” on page 177
FILE-CONTROL.
SELECT COMMUTER-FILE-MST
ASSIGN TO S-COMMUTR
ORGANIZATION IS SEQUENTIAL
ACCESS MODE IS SEQUENTIAL.
The ASSIGN clause name can include an S- before the external name to document that the file is a QSAM
file. Both the ORGANIZATION and ACCESS MODE clauses are optional.
related tasks
“Establishing record formats” on page 158
“Setting block sizes” on page 164
FILE SECTION.
FD COMMUTER-FILE-MST
RECORDING MODE IS F
BLOCK CONTAINS 0 RECORDS
RECORD CONTAINS 80 CHARACTERS.
01 COMMUTER-RECORD-MST.
05 COMMUTER-NUMBER PIC X(16).
05 COMMUTER-DESCRIPTION PIC X(64).
A recording mode of S is not supported for files in the z/OS UNIX file system. The above example is
appropriate for such a file.
related concepts
“Logical records” on page 158
related tasks
“Requesting fixed-length format” on page 158
“Requesting variable-length format” on page 159
“Requesting spanned format” on page 161
“Requesting undefined format” on page 163
“Defining QSAM files and records in COBOL” on page 157
related references
“FILE SECTION entries” on page 12
Logical records
COBOL uses the term logical record in a slightly different way than z/OS QSAM.
For format-V and format-S files, a QSAM logical record includes a 4-byte prefix in front of the user data
portion of the record that is not included in the definition of a COBOL logical record.
For format-F and format-U files, and for byte-stream files in the z/OS UNIX file system, the definitions of
QSAM logical record and COBOL logical record are identical.
In this information, QSAM logical record refers to the QSAM definition, and logical record refers to the
COBOL definition.
related references
“Layout of format-F records” on page 159
“Layout of format-V records” on page 160
“Layout of format-S records” on page 162
“Layout of format-U records” on page 163
158 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
When you use this clause, the file is always fixed format with record length integer even if there are
multiple level-01 record description entries with different lengths associated with the file.
• Omit the RECORD CONTAINS integer clause, but code the same fixed size and no OCCURS DEPENDING
ON clause for all level-01 record description entries associated with the file. This fixed size is the record
length.
In an unblocked format-F file, the logical record is the same as the block.
In a blocked format-F file, the number of logical records in a block (the blocking factor) is constant for
every block in the file except the last block, which might be shorter.
Files in the z/OS UNIX file system are never blocked.
related concepts
“Logical records” on page 158
related tasks
“Requesting variable-length format” on page 159
“Requesting spanned format” on page 161
“Requesting undefined format” on page 163
“Establishing record formats” on page 158
related references
“Layout of format-F records” on page 159
related concepts
“Logical records” on page 158
related tasks
“Requesting fixed-length format” on page 158
z/OS DFSMS: Using Data Sets (Fixed-length record formats)
related references
“Layout of format-V records” on page 160
“Layout of format-S records” on page 162
“Layout of format-U records” on page 163
related tasks
“Requesting fixed-length format” on page 158
“Requesting spanned format” on page 161
“Requesting undefined format” on page 163
“Establishing record formats” on page 158
related references
“FILE SECTION entries” on page 12
“Layout of format-V records” on page 160
Enterprise COBOL for z/OS Migration Guide (Moving from the
VS COBOL II run time)
CC
The first 4 bytes of each block contain control information.
LL Represents 2 bytes designating the length of the block (including the CC field).
160 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
BB Represents 2 bytes reserved for system use.
cc
The first 4 bytes of each logical record contain control information.
ll Represents 2 bytes designating the logical record length (including the cc field).
bb Represents 2 bytes reserved for system use.
The block length is determined as follows:
• Unblocked format-V records: CC + cc + the data portion
• Blocked format-V records: CC + the cc of each record + the data portion of each record
The operating system provides the control bytes when the file is written; the control byte fields do not
appear in the description of the logical record in the DATA DIVISION of your program. COBOL allocates
input and output buffers that are large enough to accommodate the control bytes. These control fields
in the buffer are not available for you to use in your program. When variable-length records are written
on unit record devices, control bytes are neither printed nor punched. They appear however on other
external storage devices, as well as in buffer areas of storage. If you move V-mode records from an input
buffer to a WORKING-STORAGE area, the records will be moved without the control bytes.
Files in the z/OS UNIX file system are never blocked.
related concepts
“Logical records” on page 158
related tasks
“Requesting variable-length format” on page 159
related references
“Layout of format-F records” on page 159
“Layout of format-S records” on page 162
“Layout of format-U records” on page 163
related concepts
“Logical records” on page 158
“Spanned blocked and unblocked files” on page 162
related tasks
“Requesting fixed-length format” on page 158
“Requesting variable-length format” on page 159
“Requesting undefined format” on page 163
“Establishing record formats” on page 158
related references
“FILE SECTION entries” on page 12
“Layout of format-S records” on page 162
related concepts
“Logical records” on page 158
related tasks
“Requesting spanned format” on page 161
Each block is preceded by a 4-byte block descriptor field ('BDF' in the image above). There is only one
block descriptor field at the beginning of each physical block.
Each segment of a record in a block is preceded by a 4-byte segment descriptor field ('SDF' in the image)
even if the segment is the entire record. There is one segment descriptor field for each record segment
in the block. The segment descriptor field also indicates whether the segment is the first, the last, or an
intermediate segment.
You do not describe these fields in the DATA DIVISION, and the fields are not available for you to use in
your COBOL program.
related tasks
“Requesting spanned format” on page 161
related references
“Layout of format-F records” on page 159
162 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
“Layout of format-V records” on page 160
“Layout of format-U records” on page 163
Format-U files and READ INTO: When you specify a READ INTO statement for a format-U file, the
compiler generates a MOVE statement that uses the size of the record that it just read for that file. If the
record just read does not correspond to the level-01 record description, you might not get the result that
you expect. All other rules of the MOVE statement apply.
related tasks
“Requesting fixed-length format” on page 158
“Requesting variable-length format” on page 159
“Requesting spanned format” on page 161
“Establishing record formats” on page 158
related references
“FILE SECTION entries” on page 12
“Layout of format-U records” on page 163
related tasks
“Requesting undefined format” on page 163
related references
“Layout of format-F records” on page 159
“Layout of format-V records” on page 160
“Layout of format-S records” on page 162
164 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
• Code BLOCK CONTAINS 0 in your source program or compile with the BLOCK0 option.
• Not code a BLKSIZE value in the ddname definition.
When you omit the BLKSIZE from the ddname definition, the block size is automatically obtained by the
system from the data-set label.
Taking advantage of LBI: You can improve the performance of tape data sets by using the large block
interface (LBI) for large block sizes. When the LBI is available, the COBOL run time automatically uses this
facility for those tape files for which you use system-determined block size. LBI is also used for those files
for which you explicitly define a block size in JCL or a BLOCK CONTAINS clause. Use of the LBI allows
block sizes to exceed 32760 if the tape device supports it.
The LBI is not used in all cases. An attempt to use a block size greater than 32760 in the following cases
is diagnosed at compile time or results in a failure at OPEN:
• Spanned records
• OPEN I-O
Using a block size that exceeds 32760 might result in your not being able to read the tape on another
system. A tape that you create with a block size greater than 32760 can be read only on a system that has
a tape device that supports block sizes greater than 32760. If you specify a block size that is too large for
the file, the device, or the operating system level, a runtime message is issued.
To limit a system-determined block size to 32760, do not specify BLKSIZE anywhere, and set one of the
following items to 32760:
• The BLKSZLIM keyword on the DD statement for the data set
• BLKSZLIM for the data class by using the BLKSZLIM keyword (must be set by your systems
programmer)
• A block-size limit for the system in the DEVSUPxx member of SYS1.PARMLIB by using the keyword
TAPEBLKSZLIM (must be set by your systems programmer)
The block-size limit is the first nonzero value that the compiler finds by checking these items.
If no BLKSIZE or BLKSZLIM value is available from any source, the system limits BLKSIZE to 32760. You
can then enable block sizes larger than 32760 in one of two ways:
• Specify a BLKSZLIM value greater than 32760 in the DD statement for the file and use BLOCK
CONTAINS 0 in your COBOL source.
• Specify a value greater than 32760 for the BLKSIZE in the DD statement or in the BLOCK CONTAINS
clause in your COBOL source.
BLKSZLIM is device-independent.
Block size and the DCB RECFM subparameter: Under z/OS, you can code the S or T option in the DCB
RECFM subparameter:
• Use the S (standard) option in the DCB RECFM subparameter for a format-F record with only standard
blocks (ones that have no truncated blocks or unfilled tracks in the file, except for the last block of the
file). S is also supported for records on tape. It is ignored if the records are not on DASD or tape.
Using this standard block option might improve input-output performance, especially for direct-access
devices.
• The T (track overflow) option for QSAM files is no longer useful.
related tasks
“Defining QSAM files and records in COBOL” on page 157
z/OS DFSMS: Using Data Sets
related references
“FILE SECTION entries” on page 12
“BLOCK0” on page 302
BLOCK CONTAINS clause (Enterprise COBOL for z/OS Language Reference)
related references
OPEN statement (Enterprise COBOL for z/OS Language Reference)
READ statement (Enterprise COBOL for z/OS Language Reference)
WRITE statement (Enterprise COBOL for z/OS Language Reference)
REWRITE statement (Enterprise COBOL for z/OS Language Reference)
CLOSE statement (Enterprise COBOL for z/OS Language Reference)
File status key (Enterprise COBOL for z/OS Language Reference)
166 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Use the REVERSED option of the OPEN statement to process tape files in reverse order. The file is
positioned at the end, and READ statements read the data records in reverse order, starting with the last
record. The REVERSED option is supported only for files that have fixed-length records.
related tasks
“Dynamically creating QSAM files” on page 167
“Ensuring that file attributes match your program” on page 173
related references
OPEN statement (Enterprise COBOL for z/OS Language Reference)
related tasks
“Opening QSAM files” on page 166
related references
READ statement (Enterprise COBOL for z/OS Language Reference)
WRITE statement (Enterprise COBOL for z/OS Language Reference)
You cannot open as I-O an extended format data set that you allocate in compressed format.
related references
REWRITE statement (Enterprise COBOL for z/OS Language Reference)
Controlling the page size: Use the LINAGE clause of the FD entry to control the size of your printed page:
the number of lines in the top and bottom margins and in the footing area of the page. When you use the
LINAGE clause, COBOL handles the file as if you had also requested the ADV compiler option.
If you use the LINAGE clause in combination with WRITE BEFORE|AFTER ADVANCING nn LINES, be
careful about the values you set. With the ADVANCING nn LINES phrase, COBOL first calculates the
sum of LINAGE-COUNTER plus nn. Subsequent actions depend on the size of nn. The END-OF-PAGE
imperative phrase is performed after the LINAGE-COUNTER is increased. Consequently, the LINAGE-
COUNTER could be pointing to the next logical page instead of to the current footing area when the
END-OF-PAGE phrase is performed.
AT END-OF-PAGE or NOT AT END-OF-PAGE imperative phrases are performed only if the write
operation completes successfully. If the write operation is unsuccessful, control is passed to the end
of the WRITE statement, and all conditional phrases are omitted.
Controlling the vertical positioning of records: Use the WRITE ADVANCING statement to control the
vertical positioning of each record you write on a printed page.
BEFORE ADVANCING prints the record before the page is advanced. AFTER ADVANCING prints the record
after the page is advanced.
Specify the number of lines the page is advanced with an integer (or an identifier with a mnemonic-name)
following ADVANCING. If you omit the ADVANCING phrase from a WRITE statement, the effect is as if you
had coded:
related references
WRITE statement (Enterprise COBOL for z/OS Language Reference)
168 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
You can change the location where the program resumes running (after a condition is handled) by
moving the resume cursor with the Language Environment CEEMRCR callable service or by using
language constructs such as a C longjmp.
• When you use CANCEL for a COBOL subprogram, the run time closes any open nonexternal files that are
defined in that program.
• When a COBOL subprogram with the INITIAL attribute returns control, the run time closes any open
nonexternal files that are defined in that program.
• When a thread of a multithreaded application ends, both external and nonexternal files that you opened
from within that same thread are closed.
File status key data items in the DATA DIVISION are set when these implicit CLOSE operations are
performed, but your EXCEPTION/ERROR declarative is not invoked.
Errors: If you open a QSAM file in a multithreaded application, you must close it from the same thread of
execution from which the file was opened. Attempting to close the file from a different thread results in a
close failure with file-status condition 90.
related references
CLOSE statement (Enterprise COBOL for z/OS Language Reference)
COBOL provides these ways for you to intercept and handle certain QSAM input and output errors:
• End-of-file phrase (AT END)
• EXCEPTION/ERROR declarative
• FILE STATUS clause
• INVALID KEY phrase
If you do not code a FILE STATUS key or a declarative, serious QSAM processing errors will cause a
message to be issued and a Language Environment condition to be signaled, which will cause an abend if
you specify the runtime option ABTERMENC(ABEND).
If you use the FILE STATUS clause or the EXCEPTION/ERROR declarative, code EROPT=ACC in the DCB
of the DD statement for that file. Otherwise, your COBOL program will not be able to continue processing
after some error conditions.
If you use the FILE STATUS clause, be sure to check the key and take appropriate action based on its
value. If you do not check the key, your program might continue, but the results will probably not be what
you expected.
related tasks
“Handling errors in input
and output operations” on page 233
related tasks
“Defining and allocating QSAM files” on page 170
“Retrieving QSAM files” on page 172
related references
“Allocation of buffers for QSAM files” on page 176
170 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 20. QSAM file allocation (continued)
What you want to do DD parameter to use EV keyword to use
Give instructions for the volume in which VOLUME (or let the system VOL
the file will reside and for volume choose an output volume)
mounting.
Allocate the type and amount of space SPACE SPACE for the amount of
the file needs. (Only for direct-access space (primary and secondary
storage devices.) only); TRACKS or CYL for the
type of space
Specify the type and some of the LABEL n/a
contents of the label associated with the
file.
Indicate whether you want to catalog, DISP NEW, OLD, SHR, MOD plus
pass, or keep the file after the job step is KEEP, DELETE, CATALOG, or
completed. UNCATALOG
Complete any data control block DCB subparameters n/a
information that you want to add.
Some of the information about the QSAM file must always be coded in the FILE-CONTROL paragraph, the
FD entry, and other COBOL clauses. Other information must be coded in the DD statement or environment
variable for output files. For input files, the system can obtain information from the file label (for standard
label files). If DCB information is provided in the DD statement for input files, it overrides information on
the data-set label. For example, the amount of space allocated for a new direct-access device file can be
set in the DD statement by the SPACE parameter.
You cannot express certain characteristics of QSAM files in the COBOL language, but you can code them in
the DD statement for the file by using the DCB parameter. Use the subparameters of the DCB parameter to
provide information that the system needs for completing the data set definition, including the following
items:
• Block size (BLKSIZE=), if BLOCK CONTAINS 0 RECORDS or BLOCK0 option was specified at compile
time (recommended)
• Options to be executed if an error occurs in reading or writing a record
• TRACK OVERFLOW or standard blocks
• Mode of operation for a card reader or punch
DCB attributes coded for a DD DUMMY do not override those coded in the FD entry of your COBOL program.
“Example: setting and accessing environment variables” on page 462
related tasks
“Setting block sizes” on page 164
“Defining QSAM files and records in COBOL” on page 157
“Allocating files” on page 154
related references
“BLOCK0” on page 302
“Parameters for creating QSAM files” on page 172
MVS Program Management: User's Guide and Reference
related tasks
“Defining and allocating QSAM files” on page 170
related references
“Parameters for retrieving QSAM files” on page 173
172 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Parameters for retrieving QSAM files
The following DD statement parameters are used to retrieve previously created files.
related tasks
“Retrieving QSAM files” on page 172
If you have not made a file available with a DD statement or a TSO ALLOCATE command, and your COBOL
program specifies that the file be created, Enterprise COBOL dynamically allocates the file. When the file
is opened, the file attributes that are coded in your program are used. You do not have to worry about file
attribute conflicts.
Remember that information in the JCL or environment variable overrides information in the data-set label.
related tasks
“Processing existing files” on page 174
“Processing new files” on page 175
“Opening QSAM files” on page 166
related references
“FILE SECTION entries” on page 12
The easiest way to define variable-length (format-V) records in a program is to use the RECORD IS
VARYING FROM integer-1 TO integer-2 clause in the FD entry and set an appropriate value for integer-2.
Express the integer sizes in bytes regardless of the underlying USAGE of the data items in the record. For
example, assume that you determine that the length attribute of the data set is 104 bytes (LRECL=104).
Remembering that the maximum record length is determined from the RECORD IS VARYING clause and
not from the level-01 record descriptions, you could define a format-V file in your program with this code:
FILE SECTION.
FD COMMUTER-FILE-MST
RECORDING MODE IS V
RECORD IS VARYING FROM 4 TO 100 CHARACTERS.
01 COMMUTER-RECORD-A PIC X(4).
01 COMMUTER-RECORD-B PIC X(75).
Assume that the existing file in the previous example was format-U instead of format-V. If the 104 bytes
are all user data, you could define the file in your program with this code:
FILE SECTION.
FD COMMUTER-FILE-MST
RECORDING MODE IS U
RECORD IS VARYING FROM 4 TO 104 CHARACTERS.
01 COMMUTER-RECORD-A PIC X(4).
01 COMMUTER-RECORD-B PIC X(75).
To define fixed-length records in your program, either code the RECORD CONTAINS integer clause, or
omit this clause and code all level-01 record descriptions to be the same fixed size. In either case, use a
value that equals the value of the length attribute of the data set. If you intend to use the same program
to process different files at run time, and those files have differing fixed lengths, avoid record-length
conflicts by coding RECORD CONTAINS 0.
If the existing file is an ASCII data set (DCB=(OPTCD=Q)), you must use the CODE-SET clause in the FD
entry for the file.
related tasks
“Processing new files” on page 175
“Requesting fixed-length format” on page 158
“Requesting variable-length format” on page 159
“Requesting undefined format” on page 163
“Opening QSAM files” on page 166
related references
“FILE SECTION entries” on page 12
174 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Processing new files
If your COBOL program writes records to a new file that will be made available before the program runs,
ensure that the file attributes in the DD statement, the environment variable, or the allocation do not
conflict with the attributes in the program.
Usually you need to code only a minimum of parameters when predefining files. But if you need to
explicitly set a length attribute for the data set (for example, you are using an ISPF allocation panel, or
your DD statement is for a batch job in which the program uses RECORD CONTAINS 0), follow these
guidelines:
• For format-V and format-S files, set a length attribute that is 4 bytes larger than that defined in the
program.
• For format-F and format-U files, set a length attribute that is the same as that defined in the program.
• If you open the file as OUTPUT and write it to a printer, the compiler might add 1 byte to the record
length to account for the carriage-control character, depending on the ADV compiler option and the
language used in your program. In such a case, take the added byte into account when coding the
LRECL value.
For example, if your program contains the following code for a file that has variable-length records, the
LRECL value in the DD statement or allocation should be 54.
FILE SECTION.
FD COMMUTER-FILE-MST
RECORDING MODE IS V
RECORD CONTAINS 10 TO 50 CHARACTERS.
01 COMMUTER-RECORD-A PIC X(10).
01 COMMUTER-RECORD-B PIC X(50).
related tasks
“Processing existing files” on page 174
“Requesting fixed-length format” on page 158
“Requesting variable-length format” on page 159
“Requesting undefined format” on page 163
“Opening QSAM files” on page 166
“Dynamically creating QSAM files” on page 167
related references
“FILE SECTION entries” on page 12
related tasks
z/OS DFSMS: Using Data Sets
related concepts
“Storage and its addressability” on page 39
related tasks
“Using striped extended-format QSAM data sets” on page 175
176 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
For example, suppose that a file definition has level-01 record descriptions of 3, 5, and 10 bytes long,
and you write the following three records: 'abc', 'defgh', and 'ijklmnopqr', in that order. The first READ of
this file returns 'abcdefghij', the second READ returns 'klmnopqr ', and the third READ results in the AT
END condition.
For compatibility with releases of IBM COBOL before COBOL for OS/390 & VM Version 2 Release 2, you
can also specify FILEDATA=TEXT when using a DD allocation for z/OS UNIX files, but this use is not
recommended. To process text files in the z/OS UNIX file system, use LINE SEQUENTIAL organization. If
you use QSAM to process text files in the z/OS UNIX file system, you cannot use environment variables to
define the files.
related tasks
“Allocating files” on page 154
“Defining and allocating QSAM files” on page 170
z/OS DFSMS: Using Data Sets (Using HFS data sets)
ALPHABET-NAME IS STANDARD-1
CODE-SET IS ALPHABET-NAME
Defining the record formats: Process QSAM ASCII tape files with any of these record formats:
• Fixed length (format F)
• Undefined (format U)
• Variable length (format V)
If you use variable-length records, you cannot explicitly code format D; instead, code RECORDING MODE
V. The format information is internally converted to D mode. D-mode records have a 4-byte record
descriptor for each record.
Defining the ddname: Under z/OS, processing ASCII files requires special JCL coding. Code these
subparameters of the DCB parameter in the DD statement:
BUFOFF=[L|n]
L
A 4-byte block prefix that contains the block length (including the block prefix)
n
The length of the block prefix:
• For input, from 0 through 99
• For output, either 0 or 4
Use this value if you coded BLOCK CONTAINS 0.
n
The size of the block, including the length of the block prefix
LABEL=[AL|AUL|NL]
AL
American National Standard (ANS) labels
AUL
ANS and user labels
NL
No labels
OPTCD=Q
Q
This value is required for ASCII files and is the default if the file is created using Enterprise COBOL.
related references
z/OS DFSMS: Using Data Sets (Character data conversion)
178 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Chapter 10. Processing VSAM files
Virtual storage access method (VSAM) is an access method for files on direct-access storage devices.
With VSAM you can load files, retrieve records from files, update files, and add, replace, and delete
records in files.
VSAM processing has these advantages over QSAM:
• Protection of data against unauthorized access
• Compatibility across systems
• Independence of devices (no need to be concerned with block size and other control information)
• Simpler JCL (information needed by the system is provided in integrated catalogs)
• Ability to use indexed file organization or relative file organization
The following table shows how VSAM terms differ from COBOL terms and other terms that you might be
familiar with.
The term file in this VSAM documentation refers to either a COBOL file or a VSAM data set.
If you have complex requirements or frequently use VSAM, se the VSAM publications for your operating
system.
related concepts
“VSAM files” on page 180
related tasks
“Defining VSAM file organization and records” on page 181
“Coding input and output
statements for VSAM files” on page 186
“Handling errors in VSAM files” on page 194
“Protecting VSAM files with a password” on page 194
“Working with VSAM data sets under z/OS and z/OS UNIX” on page 195
“Improving VSAM performance” on page 201
VSAM files
The physical organization of VSAM data sets differs considerably from the organizations used by other
access methods.
VSAM data sets are held in control intervals (CI) and control areas (CA). The size of the CI and CA is
normally determined by the access method; and the way in which they are used is not visible to you.
You can use three types of file organization with VSAM:
VSAM sequential file organization
(Also referred to as VSAM ESDS (entry-sequenced data set) organization.) In VSAM sequential file
organization, the records are stored in the order in which they were entered.
VSAM entry-sequenced data sets are equivalent to QSAM sequential files. The order of the records is
fixed.
VSAM indexed file organization
(Also referred to as VSAM KSDS (key-sequenced data set) organization.) In a VSAM indexed file
(KSDS), the records are ordered according to the collating sequence of an embedded prime key field,
which you define. The prime key consists of one or more consecutive characters in the records. The
prime key uniquely identifies the record and determines the sequence in which it is accessed with
respect to other records. A prime key for a record might be, for example, an employee number or an
invoice number.
VSAM relative file organization
(Also referred to as VSAM fixed-length or variable-length RRDS (relative-record data set) organization.)
A VSAM relative-record data set (RRDS) contains records ordered by their relative key. The relative key
is the relative record number, which represents the location of the record relative to where the file
begins. The relative record number identifies the fixed- or variable-length record.
In a VSAM fixed-length RRDS, records are placed in a series of fixed-length slots in storage. Each
slot is associated with a relative record number. For example, in a fixed-length RRDS that contains 10
slots, the first slot has a relative record number of 1, and the tenth slot has a relative record number of
10.
In a VSAM variable-length RRDS, the records are ordered according to their relative record number.
Records are stored and retrieved according to the relative record number that you set.
Throughout this information, the term VSAM relative-record data set (or RRDS) is used to mean both
relative-record data sets with fixed-length records and with variable-length records, unless they need
to be differentiated.
The following table compares the characteristics of the different types of VSAM data sets.
180 Enterprise COBOL for z/OS: Enterprise COBOL for z/OS, V6.2 Programming Guide
Table 23. Comparison of VSAM data-set types (continued)
Characteristic Entry-sequenced data Key-sequenced data set Relative-record data set
set (ESDS) (KSDS) (RRDS)
Alternate indexes Can have one or Can have one or more Cannot have alternate
more alternate indexes, alternate indexes indexes
although not supported in
COBOL
Relative byte RBA cannot change. RBA can change. RRN cannot change.
address (RBA) and
relative record
number (RRN) of a
record
Space for adding Uses space at the end of Uses distributed free space For fixed-length RRDS, uses
records the data set for inserting records and empty slots in the data set
changing their lengths in
For variable-length RRDS,
place
uses distributed free space
and changes the lengths of
added records in place
Space from deleting You cannot delete a Space from a deleted Space from a deleted record
records record, but you can reuse or shortened record is can be reused.
its space for a record of automatically reclaimed in a
the same length. control interval.
Spanned records Can have spanned records Can have spanned records Cannot have spanned records
Reuse as work file Can be reused unless it Can be reused unless it Can be reused
has an alternate index, has an alternate index, is
is associated with key associated with key ranges,
ranges, or exceeds 123 or exceeds 123 extents per
extents per volume volume
related tasks
“Specifying sequential organization for VSAM files” on page 182
“Specifying indexed organization
for VSAM files” on page 182
“Specifying relative organization for VSAM files” on page 183
“Defining VSAM files” on page 196