10.07.2015 Views

Enterprise COBOL for z/OS V4.2 Programming Guide

Enterprise COBOL for z/OS V4.2 Programming Guide

Enterprise COBOL for z/OS V4.2 Programming Guide

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong><strong>Programming</strong> <strong>Guide</strong>Version4Release2SC23-8529-01


<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong><strong>Programming</strong> <strong>Guide</strong>Version4Release2SC23-8529-01


Note!Be<strong>for</strong>e using this in<strong>for</strong>mation and the product it supports, be sure to read the general in<strong>for</strong>mation under “Notices” on page835.Second Edition (August 2009)This edition applies to Version 4 Release 2 of IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> (program number 5655-S71) and toall subsequent releases and modifications until otherwise indicated in new editions. Make sure that you are usingthe correct edition <strong>for</strong> the level of the product.You can order publications online at www.ibm.com/shop/publications/order/, or order by phone or fax. IBMSoftware Manufacturing Solutions takes publication orders between 8:30 a.m. and 7:00 p.m. Eastern Standard Time(EST). The phone number is (800)879-2755. The fax number is (800)445-9269.You can also order publications through your IBM representative or the IBM branch office serving your locality.© Copyright International Business Machines Corporation 1991, 2009.US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contractwith IBM Corp.


Arithmetic comparisons (relation conditions) . . 65Examples: fixed-point and floating-pointevaluations . . . . . . . . . . . . . 66Using currency signs . . . . . . . . . . . 67Example: multiple currency signs . . . . . . 68Chapter 4. Handling tables . . . . . . 69Defining a table (OCCURS) . . . . . . . . . 69Nesting tables . . . . . . . . . . . . . 71Example: subscripting . . . . . . . . . . 72Example: indexing . . . . . . . . . . . 72Referring to an item in a table . . . . . . . . 72Subscripting . . . . . . . . . . . . . 73Indexing . . . . . . . . . . . . . . 74Putting values into a table . . . . . . . . . 75Loading a table dynamically. . . . . . . . 75Initializing a table (INITIALIZE) . . . . . . 76Assigning values when you define a table(VALUE) . . . . . . . . . . . . . . 77Example: PERFORM and subscripting . . . . 79Example: PERFORM and indexing. . . . . . 80Creating variable-length tables (DEPENDING ON) 81Loading a variable-length table . . . . . . . 82Assigning values to a variable-length table . . . 83Searching a table . . . . . . . . . . . . 84Doing a serial search (SEARCH) . . . . . . 84Doing a binary search (SEARCH ALL) . . . . 85Processing table items using intrinsic functions . . 86Example: processing tables using intrinsicfunctions . . . . . . . . . . . . . . 87Chapter 5. Selecting and repeatingprogram actions . . . . . . . . . . 89Selecting program actions . . . . . . . . . 89Coding a choice of actions . . . . . . . . 89Coding conditional expressions . . . . . . . 94Repeating program actions . . . . . . . . . 97Choosing inline or out-of-line PERFORM . . . 98Coding a loop . . . . . . . . . . . . 99Looping through a table . . . . . . . . . 100Executing multiple paragraphs or sections. . . 100Chapter 6. Handling strings . . . . . 101Joining data items (STRING) . . . . . . . . 101Example: STRING statement . . . . . . . 102Splitting data items (UNSTRING) . . . . . . 103Example: UNSTRING statement . . . . . . 104Manipulating null-terminated strings . . . . . 106Example: null-terminated strings . . . . . . 107Referring to substrings of data items . . . . . 107Reference modifiers . . . . . . . . . . 109Example: arithmetic expressions as referencemodifiers . . . . . . . . . . . . . . 110Example: intrinsic functions as referencemodifiers . . . . . . . . . . . . . . 110Tallying and replacing data items (INSPECT) . . . 111Examples: INSPECT statement. . . . . . . 111Converting data items (intrinsic functions). . . . 112Converting to uppercase or lowercase(UPPER-CASE, LOWER-CASE) . . . . . . 113Trans<strong>for</strong>ming to reverse order (REVERSE) . . . 113Converting to numbers (NUMVAL,NUMVAL-C) . . . . . . . . . . . . 113Converting from one code page to another . . 115Evaluating data items (intrinsic functions) . . . . 115Evaluating single characters <strong>for</strong> collatingsequence . . . . . . . . . . . . . . 115Finding the largest or smallest data item . . . 116Finding the length of data items . . . . . . 118Finding the date of compilation . . . . . . 119Chapter 7. Processing data in aninternational environment . . . . . . 121<strong>COBOL</strong> statements and national data . . . . . 122Intrinsic functions and national data. . . . . . 124Unicode and the encoding of language characters 125Using national data (Unicode) in <strong>COBOL</strong> . . . . 126Defining national data items . . . . . . . 127Using national literals . . . . . . . . . 127Using national-character figurative constants 128Defining national numeric data items . . . . 129National groups . . . . . . . . . . . 129Using national groups . . . . . . . . . 130Storage of character data . . . . . . . . 133Converting to or from national (Unicode)representation . . . . . . . . . . . . . 134Converting alphanumeric, DBCS, and integer tonational (MOVE) . . . . . . . . . . . 134Converting alphanumeric or DBCS to national(NATIONAL-OF) . . . . . . . . . . . 135Converting national to alphanumeric(DISPLAY-OF) . . . . . . . . . . . . 136Overriding the default code page. . . . . . 136Conversion exceptions . . . . . . . . . 136Example: converting to and from national data 137Processing UTF-8 data . . . . . . . . . . 137Processing Chinese GB 18030 data . . . . . . 138Comparing national (UTF-16) data . . . . . . 139Comparing two class national operands . . . 139Comparing class national and class numericoperands . . . . . . . . . . . . . . 140Comparing national numeric and other numericoperands . . . . . . . . . . . . . . 140Comparing national and other character-stringoperands . . . . . . . . . . . . . . 140Comparing national data andalphanumeric-group operands. . . . . . . 141Coding <strong>for</strong> use of DBCS support . . . . . . . 141Declaring DBCS data . . . . . . . . . . 142Using DBCS literals . . . . . . . . . . 142Testing <strong>for</strong> valid DBCS characters . . . . . 143Processing alphanumeric data items that containDBCS data . . . . . . . . . . . . . 143Chapter 8. Processing files . . . . . 145File organization and input-output devices . . . 145Choosing file organization and access mode . . . 147Format <strong>for</strong> coding input and output . . . . . 148Allocating files . . . . . . . . . . . . . 149Checking <strong>for</strong> input or output errors . . . . . . 150iv<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 9. Processing QSAM files . . 151Defining QSAM files and records in <strong>COBOL</strong> . . . 151Establishing record <strong>for</strong>mats. . . . . . . . 152Setting block sizes . . . . . . . . . . . 159Coding input and output statements <strong>for</strong> QSAMfiles . . . . . . . . . . . . . . . . 161Opening QSAM files . . . . . . . . . . 162Dynamically creating QSAM files. . . . . . 163Adding records to QSAM files. . . . . . . 163Updating QSAM files . . . . . . . . . 164Writing QSAM files to a printer or spooled dataset . . . . . . . . . . . . . . . . 164Closing QSAM files . . . . . . . . . . 165Handling errors in QSAM files . . . . . . . 165Working with QSAM files . . . . . . . . . 166Defining and allocating QSAM files . . . . . 166Retrieving QSAM files . . . . . . . . . 169Ensuring that file attributes match yourprogram . . . . . . . . . . . . . . 170Using striped extended-<strong>for</strong>mat QSAM data sets 172Accessing HFS files using QSAM. . . . . . . 174Labels <strong>for</strong> QSAM files . . . . . . . . . . 174Using trailer and header labels . . . . . . 175Format of standard labels . . . . . . . . 176Processing QSAM ASCII files on tape . . . . . 177Processing ASCII file labels. . . . . . . . . 178Chapter 10. Processing VSAM files 179VSAM files . . . . . . . . . . . . . . 180Defining VSAM file organization and records . . 181Specifying sequential organization <strong>for</strong> VSAMfiles . . . . . . . . . . . . . . . 182Specifying indexed organization <strong>for</strong> VSAM files 182Specifying relative organization <strong>for</strong> VSAM files 184Specifying access modes <strong>for</strong> VSAM files . . . 185Defining record lengths <strong>for</strong> VSAM files. . . . 185Coding input and output statements <strong>for</strong> VSAMfiles . . . . . . . . . . . . . . . . 187File position indicator . . . . . . . . . 189Opening a file (ESDS, KSDS, or RRDS) . . . . 189Reading records from a VSAM file . . . . . 192Updating records in a VSAM file . . . . . . 193Adding records to a VSAM file . . . . . . 193Replacing records in a VSAM file. . . . . . 194Deleting records from a VSAM file . . . . . 194Closing VSAM files . . . . . . . . . . 194Handling errors in VSAM files . . . . . . . 195Protecting VSAM files with a password . . . . 196Example: password protection <strong>for</strong> a VSAMindexed file . . . . . . . . . . . . . 196Working with VSAM data sets under z/<strong>OS</strong> andz/<strong>OS</strong> UNIX . . . . . . . . . . . . . . 197Defining VSAM files . . . . . . . . . . 197Creating alternate indexes . . . . . . . . 198Allocating VSAM files . . . . . . . . . 200Sharing VSAM files through RLS . . . . . . 202Improving VSAM per<strong>for</strong>mance . . . . . . . 203Chapter 11. Processing line-sequentialfiles . . . . . . . . . . . . . . . 207Defining line-sequential files and records in<strong>COBOL</strong> . . . . . . . . . . . . . . . 207Allowable control characters . . . . . . . 208Describing the structure of a line-sequential file 208Defining and allocating line-sequential files . . . 209Coding input-output statements <strong>for</strong> line-sequentialfiles . . . . . . . . . . . . . . . . 209Opening line-sequential files . . . . . . . 210Reading records from line-sequential files . . . 210Adding records to line-sequential files . . . . 211Closing line-sequential files. . . . . . . . 211Handling errors in line-sequential files . . . . . 212Chapter 12. Sorting and merging files 213Sort and merge process . . . . . . . . . . 214Describing the sort or merge file . . . . . . . 214Describing the input to sorting or merging . . . 215Example: describing sort and input files <strong>for</strong>SORT . . . . . . . . . . . . . . . 215Coding the input procedure . . . . . . . . 216Describing the output from sorting or merging . . 217Coding the output procedure . . . . . . . . 218Example: coding the output procedure whenusing DFSORT . . . . . . . . . . . . 218Restrictions on input and output procedures . . . 219Defining sort and merge data sets . . . . . . 219Sorting variable-length records . . . . . . . 220Requesting the sort or merge . . . . . . . . 220Setting sort or merge criteria . . . . . . . 221Example: sorting with input and outputprocedures . . . . . . . . . . . . . 222Choosing alternate collating sequences . . . . 223Sorting on windowed date fields . . . . . . 223Preserving the original sequence of records withequal keys . . . . . . . . . . . . . 224Determining whether the sort or merge wassuccessful . . . . . . . . . . . . . . 224Stopping a sort or merge operation prematurely 225Improving sort per<strong>for</strong>mance with FASTSRT . . . 225FASTSRT requirements <strong>for</strong> JCL . . . . . . 226FASTSRT requirements <strong>for</strong> sort input andoutput files . . . . . . . . . . . . . 226Checking <strong>for</strong> sort errors with NOFASTSRT . . . 227Controlling sort behavior . . . . . . . . . 228Changing DFSORT defaults with controlstatements . . . . . . . . . . . . . 229Allocating storage <strong>for</strong> sort or merge operations 230Allocating space <strong>for</strong> sort files . . . . . . . 231Using checkpoint/restart with DFSORT . . . . 231Sorting under CICS . . . . . . . . . . . 231CICS SORT application restrictions . . . . . 232Chapter 13. Handling errors . . . . . 233Requesting dumps . . . . . . . . . . . 233Handling errors in joining and splitting strings . . 234Handling errors in arithmetic operations . . . . 234Example: checking <strong>for</strong> division by zero . . . . 235Handling errors in input and output operations 235Using the end-of-file condition (AT END) . . . 238Coding ERROR declaratives . . . . . . . 238Contentsv


Using file status keys. . . . . . . . . . 239Example: file status key . . . . . . . . . 240Using VSAM status codes (VSAM files only) 241Example: checking VSAM status codes . . . . 241Coding INVALID KEY phrases . . . . . . 243Example: FILE STATUS and INVALID KEY . . 243Handling errors when calling programs . . . . 244Writing routines <strong>for</strong> handling errors . . . . . . 244Part 2. Compiling and debuggingyour program . . . . . . . . . . 247Chapter 14. Compiling under z/<strong>OS</strong> 249Compiling with JCL . . . . . . . . . . . 249Using a cataloged procedure . . . . . . . 250Writing JCL to compile programs. . . . . . 259Compiling under TSO . . . . . . . . . . 261Example: ALLOCATE and CALL <strong>for</strong> compilingunder TSO . . . . . . . . . . . . . 262Example: CLIST <strong>for</strong> compiling under TSO . . . 262Starting the compiler from an assembler program 263Defining compiler input and output . . . . . . 264Data sets used by the compiler under z/<strong>OS</strong> . . 265Defining the source code data set (SYSIN) . . . 267Defining a compiler-option data set (SYSOPTF) 267Specifying source libraries (SYSLIB) . . . . . 268Defining the output data set (SYSPRINT) . . . 269Directing compiler messages to your terminal(SYSTERM) . . . . . . . . . . . . . 269Creating object code (SYSLIN or SYSPUNCH) 269Defining an associated-data file (SYSADATA) 270Defining the Java-source output file (SYSJAVA) 270Defining the debug data set (SYSDEBUG) . . . 270Defining the library-processing output file(SYSMDECK) . . . . . . . . . . . . 271Specifying compiler options under z/<strong>OS</strong> . . . . 271Specifying compiler options with the PROCESS(CBL) statement . . . . . . . . . . . 272Example: specifying compiler options using JCL 273Example: specifying compiler options underTSO . . . . . . . . . . . . . . . 273Compiler options and compiler output underz/<strong>OS</strong> . . . . . . . . . . . . . . . 273Compiling multiple programs (batch compilation) 274Example: batch compilation . . . . . . . 275Specifying compiler options in a batchcompilation . . . . . . . . . . . . . 276Example: precedence of options in a batchcompilation . . . . . . . . . . . . . 277Example: LANGUAGE option in a batchcompilation . . . . . . . . . . . . . 278Correcting errors in your source program . . . . 279Generating a list of compiler messages . . . . 279Messages and listings <strong>for</strong> compiler-detectederrors . . . . . . . . . . . . . . . 280Format of compiler diagnostic messages . . . 280Severity codes <strong>for</strong> compiler diagnostic messages 281Chapter 15. Compiling under z/<strong>OS</strong>UNIX . . . . . . . . . . . . . . . 283vi<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>||||Setting environment variables under z/<strong>OS</strong> UNIX 283Specifying compiler options under z/<strong>OS</strong> UNIX . . 284Compiling and linking with the cob2 command 285Creating a DLL under z/<strong>OS</strong> UNIX . . . . . 286Example: using cob2 to compile and link underz/<strong>OS</strong> UNIX . . . . . . . . . . . . . 287cob2 syntax and options . . . . . . . . . 287cob2 input and output files . . . . . . . . 289Compiling using scripts . . . . . . . . . . 290Chapter 16. Compiling, linking, andrunning OO applications . . . . . . 291Compiling, linking, and running OO applicationsunder z/<strong>OS</strong> UNIX. . . . . . . . . . . . 291Compiling OO applications under z/<strong>OS</strong> UNIX 291Preparing OO applications under z/<strong>OS</strong> UNIX 292Example: compiling and linking a <strong>COBOL</strong> classdefinition under z/<strong>OS</strong> UNIX . . . . . . . 293Running OO applications under z/<strong>OS</strong> UNIX 293Compiling, linking, and running OO applicationsin JCL or TSO/E . . . . . . . . . . . . 295Compiling OO applications in JCL or TSO/E 296Preparing and running OO applications in JCLor TSO/E. . . . . . . . . . . . . . 296Example: compiling, linking, and running anOO application using JCL . . . . . . . . 298Using Java SDKs <strong>for</strong> z/<strong>OS</strong> . . . . . . . . . 299Object-oriented syntax, and Java 5 or Java 6SDKs . . . . . . . . . . . . . . . 300Chapter 17. Compiler options . . . . 301Option settings <strong>for</strong> Standard <strong>COBOL</strong> 85con<strong>for</strong>mance. . . . . . . . . . . . . . 303Conflicting compiler options . . . . . . . . 304ADATA . . . . . . . . . . . . . . . 305ADV . . . . . . . . . . . . . . . . 305ARITH . . . . . . . . . . . . . . . 306AWO . . . . . . . . . . . . . . . . 307BLOCK0 . . . . . . . . . . . . . . . 307BUFSIZE . . . . . . . . . . . . . . . 309CICS . . . . . . . . . . . . . . . . 309CODEPAGE . . . . . . . . . . . . . . 310COMPILE . . . . . . . . . . . . . . 313CURRENCY. . . . . . . . . . . . . . 313DATA . . . . . . . . . . . . . . . . 314DATEPROC . . . . . . . . . . . . . . 315DBCS . . . . . . . . . . . . . . . . 317DECK . . . . . . . . . . . . . . . . 317DIAGTRUNC . . . . . . . . . . . . . 318DLL . . . . . . . . . . . . . . . . 318DUMP . . . . . . . . . . . . . . . 319DYNAM . . . . . . . . . . . . . . . 320EXIT . . . . . . . . . . . . . . . . 321EXPORTALL . . . . . . . . . . . . . 321FASTSRT . . . . . . . . . . . . . . . 322FLAG . . . . . . . . . . . . . . . . 322FLAGSTD . . . . . . . . . . . . . . 323INTDATE . . . . . . . . . . . . . . 325LANGUAGE . . . . . . . . . . . . . 326LIB. . . . . . . . . . . . . . . . . 327


LINECOUNT . . . . . . . . . . . . . 327LIST . . . . . . . . . . . . . . . . 328MAP . . . . . . . . . . . . . . . . 328MDECK . . . . . . . . . . . . . . . 329NAME . . . . . . . . . . . . . . . 331NSYMBOL . . . . . . . . . . . . . . 331NUMBER . . . . . . . . . . . . . . 332NUMPROC . . . . . . . . . . . . . . 333OBJECT . . . . . . . . . . . . . . . 334OFFSET . . . . . . . . . . . . . . . 335OPTFILE . . . . . . . . . . . . . . . 335OPTIMIZE . . . . . . . . . . . . . . 336OUTDD . . . . . . . . . . . . . . . 337PGMNAME . . . . . . . . . . . . . . 338PGMNAME(COMPAT) . . . . . . . . . 339PGMNAME(LONGUPPER). . . . . . . . 339PGMNAME(LONGMIXED) . . . . . . . 340Usage notes . . . . . . . . . . . . . 340QUOTE/AP<strong>OS</strong>T . . . . . . . . . . . . 340RENT . . . . . . . . . . . . . . . . 341RMODE . . . . . . . . . . . . . . . 342SEQUENCE . . . . . . . . . . . . . . 343SIZE . . . . . . . . . . . . . . . . 344SOURCE . . . . . . . . . . . . . . . 344SPACE . . . . . . . . . . . . . . . 345SQL . . . . . . . . . . . . . . . . 345SQLCCSID . . . . . . . . . . . . . . 347SSRANGE . . . . . . . . . . . . . . 347TERMINAL . . . . . . . . . . . . . . 348TEST . . . . . . . . . . . . . . . . 349THREAD. . . . . . . . . . . . . . . 352TRUNC . . . . . . . . . . . . . . . 353TRUNC example 1 . . . . . . . . . . 355TRUNC example 2 . . . . . . . . . . 355VBREF . . . . . . . . . . . . . . . 356WORD . . . . . . . . . . . . . . . 356XMLPARSE . . . . . . . . . . . . . . 357XREF . . . . . . . . . . . . . . . . 358YEARWINDOW . . . . . . . . . . . . 360ZWB . . . . . . . . . . . . . . . . 360Chapter 18. Compiler-directingstatements . . . . . . . . . . . . 363Chapter 19. Debugging . . . . . . . 367Debugging with source language . . . . . . . 367Tracing program logic . . . . . . . . . 368Finding and handling input-output errors . . . 369Validating data . . . . . . . . . . . . 369Finding uninitialized data . . . . . . . . 370Generating in<strong>for</strong>mation about procedures . . . 370Debugging using compiler options . . . . . . 372Finding coding errors . . . . . . . . . 372Finding line sequence problems . . . . . . 373Checking <strong>for</strong> valid ranges . . . . . . . . 373Selecting the level of error to be diagnosed . . 374Finding program entity definitions andreferences . . . . . . . . . . . . . 376Listing data items . . . . . . . . . . . 376Using the debugger . . . . . . . . . . . 377Getting listings . . . . . . . . . . . . . 377Example: short listing . . . . . . . . . 379Example: SOURCE and NUMBER output . . . 381Example: MAP output . . . . . . . . . 382Reading LIST output . . . . . . . . . . 387Example: XREF output: data-namecross-references. . . . . . . . . . . . 398Example: OFFSET compiler output . . . . . 402Example: VBREF compiler output . . . . . 403Part 3. Targeting <strong>COBOL</strong> programs<strong>for</strong> certain environments . . . . . 405Chapter 20. Developing <strong>COBOL</strong>programs <strong>for</strong> CICS . . . . . . . . . 407Coding <strong>COBOL</strong> programs to run under CICS . . 407Getting the system date under CICS. . . . . 409Calling to or from <strong>COBOL</strong> programs . . . . 409Determining the success of ECI calls. . . . . 411Compiling with the CICS option . . . . . . . 411Separating CICS suboptions . . . . . . . 413Integrated CICS translator . . . . . . . . 413Using the separate CICS translator . . . . . . 414CICS reserved-word table . . . . . . . . . 415Handling errors by using CICS HANDLE . . . . 416Example: handling errors by using CICSHANDLE . . . . . . . . . . . . . 417Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2environment . . . . . . . . . . . . 419DB2 coprocessor . . . . . . . . . . . . 419Coding SQL statements . . . . . . . . . . 420Using SQL INCLUDE with the DB2 coprocessor 420Using character data in SQL statements . . . 421Using national decimal data in SQL statements 422Using national group items in SQL statements 422Using binary items in SQL statements . . . . 423Determining the success of SQL statements . . 423Compiling with the SQL option . . . . . . . 423Separating DB2 suboptions . . . . . . . . 424<strong>COBOL</strong> and DB2 CCSID determination. . . . . 425Code-page determination <strong>for</strong> string hostvariables in SQL statements . . . . . . . 426<strong>Programming</strong> with the SQLCCSID orN<strong>OS</strong>QLCCSID option . . . . . . . . . 426Differences in how the DB2 precompiler andcoprocessor behave . . . . . . . . . . . 427Period at the end of EXEC SQL INCLUDEstatements . . . . . . . . . . . . . 427EXEC SQL INCLUDE and nested COPYREPLACING . . . . . . . . . . . . 427EXEC SQL and REPLACE or COPYREPLACING . . . . . . . . . . . . 428Source code after an END-EXEC statement . . 428Multiple definitions of host variables . . . . 428EXEC SQL statement continuation lines . . . 428Bit-data host variables . . . . . . . . . 428SQL-INIT-FLAG . . . . . . . . . . . 429Contentsvii


Choosing the DYNAM or NODYNAM compileroption . . . . . . . . . . . . . . . . 429Chapter 22. Developing <strong>COBOL</strong>programs <strong>for</strong> IMS. . . . . . . . . . 431Compiling and linking <strong>COBOL</strong> programs <strong>for</strong>running under IMS . . . . . . . . . . . 431Using object-oriented <strong>COBOL</strong> and Java under IMS 432Calling a <strong>COBOL</strong> method from a Javaapplication under IMS . . . . . . . . . 432Building a mixed <strong>COBOL</strong>-Java application thatstarts with <strong>COBOL</strong> . . . . . . . . . . 433Writing mixed-language IMS applications . . . 434Chapter 23. Running <strong>COBOL</strong>programs under z/<strong>OS</strong> UNIX . . . . . 437Running in z/<strong>OS</strong> UNIX environments . . . . . 437Setting and accessing environment variables . . . 438Setting environment variables that affectexecution . . . . . . . . . . . . . . 439Runtime environment variables . . . . . . 439Example: setting and accessing environmentvariables . . . . . . . . . . . . . . 440Calling UNIX/P<strong>OS</strong>IX APIs . . . . . . . . . 440Accessing main program parameters . . . . . 442Example: accessing main program parameters 443Part 4. Structuring complexapplications . . . . . . . . . . . 445Chapter 24. Using subprograms . . . 447Main programs, subprograms, and calls . . . . 447Ending and reentering main programs orsubprograms . . . . . . . . . . . . . 448Transferring control to another program . . . . 449Making static calls. . . . . . . . . . . 450Making dynamic calls . . . . . . . . . 451AMODE switching . . . . . . . . . . 453Per<strong>for</strong>mance considerations of static anddynamic calls . . . . . . . . . . . . 455Making both static and dynamic calls . . . . 455Examples: static and dynamic CALL statements 456Calling nested <strong>COBOL</strong> programs . . . . . . 458Making recursive calls . . . . . . . . . . 461Calling to and from object-oriented programs . . 461Using procedure and function pointers . . . . . 462Deciding which type of pointer to use . . . . 463Calling alternate entry points . . . . . . . 463Making programs reentrant . . . . . . . . 464Chapter 25. Sharing data . . . . . . 465Passing data. . . . . . . . . . . . . . 465Describing arguments in the calling program 467Describing parameters in the called program 468Testing <strong>for</strong> OMITTED arguments . . . . . . 468Coding the LINKAGE SECTION . . . . . . . 469Coding the PROCEDURE DIVISION <strong>for</strong> passingarguments . . . . . . . . . . . . . . 469Grouping data to be passed . . . . . . . 470|Handling null-terminated strings . . . . . . 470Using pointers to process a chained list . . . 471Passing return-code in<strong>for</strong>mation . . . . . . . 474Understanding the RETURN-CODE specialregister . . . . . . . . . . . . . . 474Using PROCEDURE DIVISION RETURNING . ... . . . . . . . . . . . . . . . . 474Specifying CALL . . . RETURNING . . . . . 475Sharing data by using the EXTERNAL clause. . . 475Sharing files between programs (external files) . . 475Example: using external files . . . . . . . 476Chapter 26. Creating a DLL or a DLLapplication . . . . . . . . . . . . 481Dynamic link libraries (DLLs) . . . . . . . . 481Compiling programs to create DLLs . . . . . . 482Linking DLLs . . . . . . . . . . . . . 483Example: sample JCL <strong>for</strong> a procedural DLLapplication . . . . . . . . . . . . . . 484Prelinking certain DLLs . . . . . . . . . . 485Using CALL identifier with DLLs . . . . . . 485Search order <strong>for</strong> DLLs in the HFS . . . . . 486Using DLL linkage and dynamic calls together . . 486Using procedure or function pointers with DLLs 488Calling DLLs from non-DLLs . . . . . . . 488Example: calling DLLs from non-DLLs . . . . 489Using <strong>COBOL</strong> DLLs with C/C++ programs . . . 490Using DLLs in OO <strong>COBOL</strong> applications . . . . 491Chapter 27. Preparing <strong>COBOL</strong>programs <strong>for</strong> multithreading . . . . . 493Multithreading . . . . . . . . . . . . . 494Choosing THREAD to support multithreading . . 495Transferring control to multithreaded programs 495Ending multithreaded programs . . . . . . . 496Processing files with multithreading . . . . . . 496File-definition (FD) storage . . . . . . . . 497Serializing file access with multithreading . . . 497Example: usage patterns of file input andoutput with multithreading. . . . . . . . 498Handling <strong>COBOL</strong> limitations with multithreading 499Part 5. Using XML and <strong>COBOL</strong>together . . . . . . . . . . . . . 501Chapter 28. Processing XML input 503XML parser in <strong>COBOL</strong> . . . . . . . . . . 504Accessing XML documents . . . . . . . . . 506Parsing XML documents . . . . . . . . . 506Writing procedures to process XML . . . . . 508XML events . . . . . . . . . . . . . 510Trans<strong>for</strong>ming XML text to <strong>COBOL</strong> data items 514Parsing XML documents with validation . . . 515Parsing XML documents one segment at a time 518The encoding of XML documents. . . . . . . 520XML input document encoding . . . . . . 521Parsing XML documents encoded in UTF-8 . . 525Handling XML PARSE exceptions . . . . . . 526How the XML parser handles errors. . . . . 528viii<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


||Handling encoding conflicts . . . . . . . 529Terminating XML parsing . . . . . . . . . 530XML PARSE examples . . . . . . . . . . 531Example: parsing a simple document . . . . 531Example: program <strong>for</strong> processing XML . . . . 532Example: parsing an XML document that usesnamespaces . . . . . . . . . . . . . 535Example: parsing an XML document onesegment at a time . . . . . . . . . . . 537Example: parsing XML documents withvalidation . . . . . . . . . . . . . 539Chapter 29. Producing XML output 543Generating XML output . . . . . . . . . . 543Controlling the encoding of generated XML output 547Handling XML GENERATE exceptions . . . . . 548Example: generating XML . . . . . . . . . 549Program XGFX . . . . . . . . . . . . 549Program Pretty . . . . . . . . . . . . 550Output from program XGFX . . . . . . . 553Enhancing XML output . . . . . . . . . . 553Example: enhancing XML output . . . . . . 554Example: converting hyphens in element orattribute names to underscores . . . . . . 557Part 6. Developing object-orientedprograms . . . . . . . . . . . . 559Chapter 30. Writing object-orientedprograms . . . . . . . . . . . . . 561Example: accounts. . . . . . . . . . . . 562Subclasses . . . . . . . . . . . . . 563Defining a class . . . . . . . . . . . . 564CLASS-ID paragraph <strong>for</strong> defining a class . . . 566REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class 566WORKING-STORAGE SECTION <strong>for</strong> definingclass instance data. . . . . . . . . . . 568Example: defining a class . . . . . . . . 569Defining a class instance method . . . . . . . 569METHOD-ID paragraph <strong>for</strong> defining a classinstance method . . . . . . . . . . . 570INPUT-OUTPUT SECTION <strong>for</strong> defining a classinstance method . . . . . . . . . . . 571DATA DIVISION <strong>for</strong> defining a class instancemethod . . . . . . . . . . . . . . 571PROCEDURE DIVISION <strong>for</strong> defining a classinstance method . . . . . . . . . . . 572Overriding an instance method . . . . . . 573Overloading an instance method . . . . . . 574Coding attribute (get and set) methods . . . . 575Example: defining a method . . . . . . . 576Defining a client . . . . . . . . . . . . 578REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a client 579DATA DIVISION <strong>for</strong> defining a client . . . . 580Comparing and setting object references . . . 581Invoking methods (INVOKE) . . . . . . . 582Creating and initializing instances of classes . . 586Freeing instances of classes . . . . . . . . 588Example: defining a client . . . . . . . . 589Defining a subclass . . . . . . . . . . . 589CLASS-ID paragraph <strong>for</strong> defining a subclass 590REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a subclass 591WORKING-STORAGE SECTION <strong>for</strong> definingsubclass instance data . . . . . . . . . 592Defining a subclass instance method . . . . 592Example: defining a subclass (with methods) 592Defining a factory section . . . . . . . . . 594WORKING-STORAGE SECTION <strong>for</strong> definingfactory data . . . . . . . . . . . . . 594Defining a factory method . . . . . . . . 595Example: defining a factory (with methods) . . 597Wrapping procedure-oriented <strong>COBOL</strong> programs 603Structuring OO applications . . . . . . . . 603Examples: <strong>COBOL</strong> applications that run usingthe java command. . . . . . . . . . . 604Chapter 31. Communicating with Javamethods . . . . . . . . . . . . . 607Accessing JNI services . . . . . . . . . . 607Handling Java exceptions . . . . . . . . 608Managing local and global references . . . . 610Java access controls . . . . . . . . . . 611Sharing data with Java . . . . . . . . . . 612Coding interoperable data types in <strong>COBOL</strong> andJava . . . . . . . . . . . . . . . 612Declaring arrays and strings <strong>for</strong> Java . . . . 613Manipulating Java arrays . . . . . . . . 614Manipulating Java strings . . . . . . . . 616Example: J2EE client written in <strong>COBOL</strong> . . . . 619<strong>COBOL</strong> client (ConverterClient.cbl) . . . . . 619Java client (ConverterClient.java) . . . . . . 621Part 7. Specialized processing . . 623Chapter 32. Interrupts andcheckpoint/restart . . . . . . . . . 625Setting checkpoints . . . . . . . . . . . 625Designing checkpoints . . . . . . . . . 626Testing <strong>for</strong> a successful checkpoint . . . . . 627DD statements <strong>for</strong> defining checkpoint data sets 627Messages generated during checkpoint . . . . 628Restarting programs . . . . . . . . . . . 628Requesting automatic restart . . . . . . . 629Requesting deferred restart . . . . . . . . 629Formats <strong>for</strong> requesting deferred restart . . . . 630Resubmitting jobs <strong>for</strong> restart . . . . . . . 631Example: restarting a job at a specificcheckpoint step. . . . . . . . . . . . 631Example: requesting a step restart . . . . . 631Example: resubmitting a job <strong>for</strong> a step restart 632Example: resubmitting a job <strong>for</strong> a checkpointrestart . . . . . . . . . . . . . . . 632Chapter 33. Processing two-digit-yeardates . . . . . . . . . . . . . . . 635Millennium language extensions (MLE) . . . . 636Principles and objectives of these extensions . . 636Resolving date-related logic problems . . . . . 637Contentsix


Using a century window . . . . . . . . 638Using internal bridging . . . . . . . . . 639Moving to full field expansion. . . . . . . 641Using year-first, year-only, and year-last date fields 643Compatible dates . . . . . . . . . . . 643Example: comparing year-first date fields . . . 644Using other date <strong>for</strong>mats . . . . . . . . 644Example: isolating the year . . . . . . . . 645Manipulating literals as dates . . . . . . . . 645Assumed century window . . . . . . . . 646Treatment of nondates . . . . . . . . . 647Setting triggers and limits . . . . . . . . . 648Example: using limits . . . . . . . . . 649Using sign conditions . . . . . . . . . 650Sorting and merging by date . . . . . . . . 650Example: sorting by date and time . . . . . 651Per<strong>for</strong>ming arithmetic on date fields. . . . . . 651Allowing <strong>for</strong> overflow from windowed datefields . . . . . . . . . . . . . . . 652Specifying the order of evaluation . . . . . 653Controlling date processing explicitly . . . . . 653Using DATEVAL . . . . . . . . . . . 654Using UNDATE . . . . . . . . . . . 654Example: DATEVAL . . . . . . . . . . 655Example: UNDATE . . . . . . . . . . 655Analyzing and avoiding date-related diagnosticmessages . . . . . . . . . . . . . . . 656Avoiding problems in processing dates . . . . . 657Avoiding problems with packed-decimal fields 657Moving from expanded to windowed date fields 658Part 8. Improving per<strong>for</strong>mance andproductivity . . . . . . . . . . . 659Chapter 34. Tuning your program. . . 661Using an optimal programming style . . . . . 662Using structured programming . . . . . . 662Factoring expressions. . . . . . . . . . 662Using symbolic constants . . . . . . . . 663Grouping constant computations . . . . . . 663Grouping duplicate computations . . . . . 663Choosing efficient data types . . . . . . . . 664Choosing efficient computational data items . . 664Using consistent data types. . . . . . . . 665Making arithmetic expressions efficient . . . . 665Making exponentiations efficient . . . . . . 665Handling tables efficiently . . . . . . . . . 665Optimization of table references . . . . . . 667Optimizing your code . . . . . . . . . . 669Optimization . . . . . . . . . . . . 669Choosing compiler features to enhanceper<strong>for</strong>mance. . . . . . . . . . . . . . 671Per<strong>for</strong>mance-related compiler options . . . . 672Evaluating per<strong>for</strong>mance . . . . . . . . . 675Running efficiently with CICS, IMS, or VSAM . . 676Chapter 35. Simplifying coding . . . . 679Eliminating repetitive coding . . . . . . . . 679Example: using the COPY statement. . . . . 680Using Language Environment callable services . . 681Sample list of Language Environment callableservices . . . . . . . . . . . . . . 682Calling Language Environment services . . . 683Example: Language Environment callableservices . . . . . . . . . . . . . . 684Part 9. Appendixes . . . . . . . . 685Appendix A. Intermediate results andarithmetic precision . . . . . . . . 687Terminology used <strong>for</strong> intermediate results . . . . 688Example: calculation of intermediate results . . . 689Fixed-point data and intermediate results . . . . 689Addition, subtraction, multiplication, anddivision . . . . . . . . . . . . . . 689Exponentiation . . . . . . . . . . . . 690Example: exponentiation in fixed-pointarithmetic . . . . . . . . . . . . . 691Truncated intermediate results. . . . . . . 692Binary data and intermediate results . . . . 692Intrinsic functions evaluated in fixed-pointarithmetic . . . . . . . . . . . . . . 692Integer functions . . . . . . . . . . . 692Mixed functions . . . . . . . . . . . 693Floating-point data and intermediate results . . . 694Exponentiations evaluated in floating-pointarithmetic . . . . . . . . . . . . . 695Intrinsic functions evaluated in floating-pointarithmetic . . . . . . . . . . . . . 695Arithmetic expressions in nonarithmetic statements 695Appendix B. Complex OCCURSDEPENDING ON . . . . . . . . . . 697Example: complex ODO . . . . . . . . . . 697How length is calculated . . . . . . . . 698Setting values of ODO objects . . . . . . . 698Effects of change in ODO object value . . . . . 698Preventing index errors when changing ODOobject value . . . . . . . . . . . . . 699Preventing overlay when adding elements to avariable table . . . . . . . . . . . . 699Appendix C. Converting double-bytecharacter set (DBCS) data . . . . . . 703DBCS notation . . . . . . . . . . . . . 703Alphanumeric to DBCS data conversion(IGZCA2D) . . . . . . . . . . . . . . 703IGZCA2D syntax . . . . . . . . . . . 704IGZCA2D return codes . . . . . . . . . 704Example: IGZCA2D . . . . . . . . . . 705DBCS to alphanumeric data conversion (IGZCD2A) 706IGZCD2A syntax . . . . . . . . . . . 706IGZCD2A return codes . . . . . . . . . 707Example: IGZCD2A . . . . . . . . . . 707Appendix D. XML reference material 709XML PARSE exceptions with XMLPARSE(XMLSS)in effect . . . . . . . . . . . . . . . 709x<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||||XML PARSE exceptions withXMLPARSE(COMPAT) in effect . . . . . . . 711XML PARSE exceptions that allow continuation 711XML PARSE exceptions that do not allowcontinuation . . . . . . . . . . . . . 715XML GENERATE exceptions . . . . . . . . 718Appendix E. EXIT compiler option . . 719Using the user-exit work area . . . . . . . . 721Calling from exit modules . . . . . . . . . 721Processing of INEXIT. . . . . . . . . . . 722INEXIT parameters . . . . . . . . . . 722Processing of LIBEXIT . . . . . . . . . . 723Processing of LIBEXIT with nested COPYstatements . . . . . . . . . . . . . 724LIBEXIT parameters . . . . . . . . . . 725Processing of PRTEXIT . . . . . . . . . . 726PRTEXIT parameters . . . . . . . . . . 726Processing of ADEXIT . . . . . . . . . . 727ADEXIT parameters . . . . . . . . . . 728Processing of MSGEXIT . . . . . . . . . . 729MSGEXIT parameters . . . . . . . . . 729Customizing compiler-message severities . . . 730Error handling <strong>for</strong> exit modules . . . . . . . 733Using the EXIT compiler option with CICS andSQL statements. . . . . . . . . . . . . 734Example: MSGEXIT user exit . . . . . . . . 735Appendix F. JNI.cpy . . . . . . . . 741Appendix G. <strong>COBOL</strong> SYSADATA filecontents . . . . . . . . . . . . . 747Existing compiler options that affect theSYSADATA file. . . . . . . . . . . . . 747SYSADATA record types . . . . . . . . . 748Example: SYSADATA . . . . . . . . . . 749SYSADATA record descriptions . . . . . . . 750Common header section . . . . . . . . . . 751Job identification record: X’0000’ . . . . . . . 752ADATA identification record: X’0001’ . . . . . 753Compilation unit start|end record: X’0002’ . . . 753Options record: X’0010’ . . . . . . . . . . 754External symbol record: X’0020’ . . . . . . . 763Parse tree record: X’0024’ . . . . . . . . . 764Token record: X’0030’. . . . . . . . . . . 779Source error record: X’0032’ . . . . . . . . 792Source record: X’0038’ . . . . . . . . . . 793COPY REPLACING record: X’0039’ . . . . . . 794Symbol record: X’0042’ . . . . . . . . . . 794Symbol cross-reference record: X’0044’ . . . . . 807Nested program record: X’0046’ . . . . . . . 808Library record: X’0060’ . . . . . . . . . . 809Statistics record: X’0090’ . . . . . . . . . . 809EVENTS record: X’0120’ . . . . . . . . . . 810Appendix H. Using sample programs 815IGYTCARA: batch application . . . . . . . . 815Input data <strong>for</strong> IGYTCARA . . . . . . . . 816Report produced by IGYTCARA . . . . . . 817Preparing to run IGYTCARA . . . . . . . 818IGYTCARB: interactive program . . . . . . . 819Preparing to run IGYTCARB . . . . . . . 820IGYTSALE: nested program application . . . . 822Input data <strong>for</strong> IGYTSALE . . . . . . . . 823Reports produced by IGYTSALE . . . . . . 825Preparing to run IGYTSALE . . . . . . . 828Language elements and concepts that areillustrated . . . . . . . . . . . . . . 829Notices . . . . . . . . . . . . . . 835Trademarks . . . . . . . . . . . . . . 837Glossary . . . . . . . . . . . . . 839List of resources . . . . . . . . . . 873<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> . . . . . . . . 873Related publications . . . . . . . . . . . 873Index . . . . . . . . . . . . . . . 875Contentsxi


xii<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Tables1. FILE-CONTROL entries . . . . . . . . 82. FILE SECTION entries . . . . . . . . 143. Assignment to data items in a program 294. Effect of RMODE and RENT compileroptions on the RMODE attribute . . . . . 425. Ranges in value of COMP-5 data items 516. Internal representation of numeric items 537. NUMCLS(PRIM) and valid signs . . . . . 578. NUMCLS(ALT) and valid signs . . . . . 579. Order of evaluation of arithmetic operators 5910. Numeric intrinsic functions . . . . . . . 6011. Compatibility of math intrinsic functions andcallable services . . . . . . . . . . . 6112. INTDATE(LILIAN) and compatibility of dateintrinsic functions and callable services. . . 6213. INTDATE(ANSI) and compatibility of dateintrinsic functions and callable services. . . 6214. Hexadecimal values of the euro sign . . . . 6715. <strong>COBOL</strong> statements and national data 12216. Intrinsic functions and national characterdata. . . . . . . . . . . . . . . 12417. National group items that are processedwith group semantics . . . . . . . . 13218. Encoding and size of alphanumeric, DBCS,and national data . . . . . . . . . . 13319. Summary of file organizations, accessmodes, and record <strong>for</strong>mats of <strong>COBOL</strong> files . 14720. QSAM file allocation. . . . . . . . . 16721. Maximum record length of QSAM files 17122. Handling of QSAM user labels . . . . . 17623. Identifiers <strong>for</strong> standard tape labels . . . . 17624. Comparison of VSAM, <strong>COBOL</strong>, andnon-VSAM terminology. . . . . . . . 17925. Comparison of VSAM data-set types 18126. VSAM file organization, access mode, andrecord <strong>for</strong>mat . . . . . . . . . . . 18227. Definition of VSAM fixed-length records 18628. Definition of VSAM variable-length records 18629. I/O statements <strong>for</strong> VSAM sequential files 18830. I/O statements <strong>for</strong> VSAM relative andindexed files . . . . . . . . . . . 18831. Statements to load records into a VSAM file 19132. Statements to update records in a VSAMfile . . . . . . . . . . . . . . . 19333. Methods <strong>for</strong> improving VSAM per<strong>for</strong>mance 20334. Methods <strong>for</strong> checking <strong>for</strong> sort errors withNOFASTSRT . . . . . . . . . . . 22835. Methods <strong>for</strong> controlling sort behavior 22836. Compiler data sets . . . . . . . . . 26537. Block size of fixed-length compiler data sets 26738. Block size of variable-length compiler datasets . . . . . . . . . . . . . . . 26739. Types of compiler output under z/<strong>OS</strong> 27340. Severity codes <strong>for</strong> compiler diagnosticmessages . . . . . . . . . . . . . 28141. Input files to the cob2 command . . . . . 289||||||42. Output files from the cob2 command 28943. Commands <strong>for</strong> compiling and linking aclass definition . . . . . . . . . . . 29244. java command options <strong>for</strong> customizing theJVM . . . . . . . . . . . . . . 29445. Compiler options . . . . . . . . . . 30146. Mutually exclusive compiler options 30447. EBCDIC multibyte coded character setidentifiers . . . . . . . . . . . . 31248. Values of the LANGUAGE compiler option 32649. Severity levels of compiler messages 37450. Using compiler options to get listings 37751. Terms used in MAP output . . . . . . 38452. Symbols used in LIST and MAP output 38553. Signature in<strong>for</strong>mation bytes <strong>for</strong> compileroptions . . . . . . . . . . . . . 39054. Signature in<strong>for</strong>mation bytes <strong>for</strong> the DATADIVISION . . . . . . . . . . . . 39155. Signature in<strong>for</strong>mation bytes <strong>for</strong> theENVIRONMENT DIVISION . . . . . . 39256. Signature in<strong>for</strong>mation bytes <strong>for</strong>PROCEDURE DIVISION verbs . . . . . 39257. Signature in<strong>for</strong>mation bytes <strong>for</strong> morePROCEDURE DIVISION items . . . . . 39458. Calls between <strong>COBOL</strong> and assembler underCICS . . . . . . . . . . . . . . 41059. Compiler options required <strong>for</strong> the integratedCICS translator . . . . . . . . . . . 41260. Compiler options required <strong>for</strong> the separateCICS translator . . . . . . . . . . . 41561. TRUNC compiler options recommended <strong>for</strong>the separate CICS translator . . . . . . 41562. Compiler options required with the DB2coprocessor . . . . . . . . . . . . 42463. Samples with P<strong>OS</strong>IX function calls . . . . 44164. Effects of termination statements. . . . . 44865. Methods <strong>for</strong> passing data in the CALLstatement . . . . . . . . . . . . . 46666. Compiler options <strong>for</strong> DLL applications 48267. Binder options <strong>for</strong> DLL applications 48368. Special registers used by the XML parser 50869. Result of processing-procedure changes toXML-CODE with XMLPARSE(XMLSS) in effect . . 51170. Result of processing-procedure changes toXML-CODE with XMLPARSE(COMPAT) in effect . . 51171. Coded character sets <strong>for</strong> XML documents 52172. Hexadecimal values of white-spacecharacters. . . . . . . . . . . . . 52273. Aliases <strong>for</strong> XML encoding declarations 52474. Hexadecimal values of special characters <strong>for</strong>various EBCDIC CCSIDs . . . . . . . 52475. XML events and special registers . . . . 53176. XML events and special registers . . . . 53677. Encoding of generated XML if theENCODING phrase is omitted . . . . . 54778. Structure of class definitions . . . . . . 564© Copyright IBM Corp. 1991, 2009 xiii


|||79. Structure of instance method definitions 57080. Structure of <strong>COBOL</strong> clients . . . . . . 57881. Con<strong>for</strong>mance of arguments in a <strong>COBOL</strong>client . . . . . . . . . . . . . . 58382. Con<strong>for</strong>mance of the returned data item in a<strong>COBOL</strong> client . . . . . . . . . . . 58583. Structure of factory definitions . . . . . 59484. Structure of factory method definitions 59585. JNI services <strong>for</strong> local and global references 61186. Interoperable data types in <strong>COBOL</strong> and Java 61287. Interoperable arrays and strings in <strong>COBOL</strong>and Java . . . . . . . . . . . . . 61388. Noninteroperable array types in <strong>COBOL</strong>and Java . . . . . . . . . . . . . 61489. JNI array services . . . . . . . . . . 61490. Services that convert between jstringreferences and national data . . . . . . 61791. Services that convert between jstringreferences and alphanumeric data . . . . 61792. Advantages and disadvantages of Year 2000solutions . . . . . . . . . . . . . 63893. Per<strong>for</strong>mance-related compiler options 67294. Per<strong>for</strong>mance-tuning worksheet . . . . . 67595. Language Environment callable services 68296. IGZCA2D return codes . . . . . . . . 70597. IGZCD2A return codes . . . . . . . . 70798. Reason codes <strong>for</strong> XML PARSE exceptionsthat are unique to <strong>Enterprise</strong> <strong>COBOL</strong> . . . 70999. XML PARSE exceptions that allowcontinuation (<strong>for</strong> XMLPARSE(COMPAT)) . . . . 711100. XML PARSE exceptions that do not allowcontinuation (<strong>for</strong> XMLPARSE(COMPAT)) . . . . 715101. XML GENERATE exceptions . . . . . . 718102. Layout of the user-exit work area . . . . 721103. INEXIT processing . . . . . . . . . 722104. INEXIT parameters . . . . . . . . . 722105. LIBEXIT processing . . . . . . . . . 723106. LIBEXIT processing with nonnested COPYstatements . . . . . . . . . . . . 724107. LIBEXIT processing with nested COPYstatements . . . . . . . . . . . . 724|||108. LIBEXIT parameters . . . . . . . . . 725109. PRTEXIT processing . . . . . . . . . 726110. PRTEXIT parameters . . . . . . . . . 726111. ADEXIT processing . . . . . . . . . 727112. ADEXIT parameters . . . . . . . . . 728113. MSGEXIT processing . . . . . . . . 729114. MSGEXIT parameters . . . . . . . . 729115. FIPS (FLAGSTD) message categories . . . . 732116. Actions possible in exit modules <strong>for</strong> CICSand SQL statements . . . . . . . . . 734117. SYSADATA record types . . . . . . . 748118. SYSADATA common header section 751119. SYSADATA job identification record 752120. ADATA identification record . . . . . . 753121. SYSADATA compilation unit start|endrecord . . . . . . . . . . . . . . 754122. SYSADATA options record. . . . . . . 754123. SYSADATA external symbol record 764124. SYSADATA parse tree record . . . . . . 764125. SYSADATA token record . . . . . . . 779126. SYSADATA source error record . . . . . 793127. SYSADATA source record . . . . . . . 793128. SYSADATA COPY REPLACING record 794129. SYSADATA symbol record . . . . . . . 794130. SYSADATA symbol cross-reference record 807131. SYSADATA nested program record . . . . 808132. SYSADATA library record . . . . . . . 809133. SYSADATA statistics record . . . . . . 809134. SYSADATA EVENTS TIMESTAMP recordlayout . . . . . . . . . . . . . . 810135. SYSADATA EVENTS PROCESSOR recordlayout . . . . . . . . . . . . . . 810136. SYSADATA EVENTS FILE END recordlayout . . . . . . . . . . . . . . 811137. SYSADATA EVENTS PROGRAM recordlayout . . . . . . . . . . . . . . 811138. SYSADATA EVENTS FILE ID record layout 811139. SYSADATA EVENTS ERROR record layout 812xiv<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


PrefaceAbout this in<strong>for</strong>mationWelcome to IBM ® <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> ® , IBM’s latest host <strong>COBOL</strong>compiler!This version of IBM <strong>COBOL</strong> adds new <strong>COBOL</strong> function to help integrate <strong>COBOL</strong>business processes and Web-oriented business processes by:vvSimplifying the componentization of <strong>COBOL</strong> programs and enablinginteroperability with Java componentsPromoting the exchange and use of data in standardized <strong>for</strong>mats, includingXML and UnicodeHow this document will help youThis document will help you write and compile <strong>Enterprise</strong> <strong>COBOL</strong> programs. Itwill also help you define object-oriented classes and methods, invoke methods, andrefer to objects in your programs.This document assumes experience in developing application programs and someknowledge of <strong>COBOL</strong>. It focuses on using <strong>Enterprise</strong> <strong>COBOL</strong> to meet yourprogramming objectives and not on the definition of the <strong>COBOL</strong> language. Forcomplete in<strong>for</strong>mation about <strong>COBOL</strong> syntax, see the IBM <strong>Enterprise</strong> <strong>COBOL</strong>Language Reference.For in<strong>for</strong>mation about migrating programs to <strong>Enterprise</strong> <strong>COBOL</strong>, see the IBM<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong>.IBM z/<strong>OS</strong> Language Environment ® provides the runtime environment and runtimeservices that are required to run <strong>Enterprise</strong> <strong>COBOL</strong> programs. You can findin<strong>for</strong>mation about link-editing and running programs in the IBM z/<strong>OS</strong> LanguageEnvironment <strong>Programming</strong> <strong>Guide</strong> and IBM z/<strong>OS</strong> Language Environment <strong>Programming</strong>Reference.For a comparison of commonly used <strong>Enterprise</strong> <strong>COBOL</strong> and LanguageEnvironment terms, see “Comparison of commonly used terms” on page xvi.Abbreviated termsCertain terms are used in a shortened <strong>for</strong>m in this in<strong>for</strong>mation. Abbreviations <strong>for</strong>the product names used most frequently are listed alphabetically in the followingtable.Term usedCICS ®<strong>Enterprise</strong> <strong>COBOL</strong>Language EnvironmentMVSLong <strong>for</strong>mCICS Transaction ServerIBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong>IBM z/<strong>OS</strong> Language EnvironmentMVS/ESA© Copyright IBM Corp. 1991, 2009 xv


Term usedz/<strong>OS</strong> UNIX ®Long <strong>for</strong>mz/<strong>OS</strong> UNIX System ServicesIn addition to these abbreviated terms, the term ″Standard <strong>COBOL</strong> 85″ is used torefer to the combination of the following standards:v ISO 1989:1985, <strong>Programming</strong> languages - <strong>COBOL</strong>vvvvvISO/IEC 1989/AMD1:1992, <strong>Programming</strong> languages - <strong>COBOL</strong>: Intrinsic functionmoduleISO/IEC 1989/AMD2:1994, <strong>Programming</strong> languages - Correction andclarification amendment <strong>for</strong> <strong>COBOL</strong>ANSI INCITS 23-1985, <strong>Programming</strong> Languages - <strong>COBOL</strong>ANSI INCITS 23a-1989, <strong>Programming</strong> Languages - Intrinsic Function Module <strong>for</strong><strong>COBOL</strong>ANSI INCITS 23b-1993, <strong>Programming</strong> Language - Correction Amendment <strong>for</strong><strong>COBOL</strong>The ISO standards are identical to the American National standards.Other terms, if not commonly understood, are shown in italics the first time thatthey appear, and are listed in the glossary.Comparison of commonly used termsTo better understand the terms used throughout the IBM z/<strong>OS</strong> LanguageEnvironment and IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> in<strong>for</strong>mation, and to understandwhich terms are meant to be equivalent, see the following table.Language Environment termAggregateArrayArray elementEnclaveExternal dataLocal dataPass parameters directly, by valuePass parameters indirectly, byreferencePass parameters indirectly, by valueRoutineScalar<strong>Enterprise</strong> <strong>COBOL</strong> equivalentGroup itemA table created using the OCCURS clauseTable elementRun unitWORKING-STORAGE data defined using the EXTERNALclauseAny non-EXTERNAL data itemBY VALUEBY REFERENCEBY CONTENTProgramElementary itemHow to read syntax diagramsUse the following description to read the syntax diagrams in this in<strong>for</strong>mation.v Read the syntax diagrams from left to right, from top to bottom, following thepath of the line.The >>--- symbol indicates the beginning of a syntax diagram.xvi<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vThe ---> symbol indicates that the syntax diagram is continued on the next line.The >--- symbol indicates that the syntax diagram is continued from theprevious line.The --->< symbol indicates the end of a syntax diagram.Diagrams of syntactical units other than complete statements start with the >---symbol and end with the ---> symbol.Required items appear on the horizontal line (the main path):►► required_item ►◄vOptional items appear below the main path:►►required_itemoptional_item►◄vIf you can choose from two or more items, they appear vertically, in a stack. Ifyou must choose one of the items, one item of the stack appears on the mainpath:►► required_item required_choice1required_choice2►◄If choosing one of the items is optional, the entire stack appears below the mainpath:►►required_itemoptional_choice1optional_choice2►◄If one of the items is the default, it appears above the main path and theremaining choices are shown below:►►required_itemdefault_choiceoptional_choiceoptional_choice►◄vAn arrow returning to the left, above the main line, indicates an item that can berepeated:Prefacexvii


►► required_item ▼ repeatable_item ►◄If the repeat arrow contains a comma, you must separate repeated items with acomma:►► required_item ▼ ,repeatable_item►◄vvKeywords appear in uppercase (<strong>for</strong> example, FROM). They must be spelled exactlyas shown. Variables appear in lowercase italics (<strong>for</strong> example, column-name). Theyrepresent user-supplied names or values.If punctuation marks, parentheses, arithmetic operators, or other such symbolsare shown, you must enter them as part of the syntax.How examples are shownThis in<strong>for</strong>mation shows numerous examples of sample <strong>COBOL</strong> statements,program fragments, and small programs to illustrate the coding techniques beingdescribed. The examples of program code are written in lowercase, uppercase, ormixed case to demonstrate that you can write your programs in any of these ways.To more clearly separate some examples from the explanatory text, they arepresented in a monospace font.<strong>COBOL</strong> keywords and compiler options that appear in text are generally shown inSMALL UPPERCASE. Other terms such as program variable names are sometimesshown in an italic font <strong>for</strong> clarity.Accessing softcopy documentation and support in<strong>for</strong>mationIBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> provides PDF and BookManager ® versions of thelibrary on the product site at www.ibm.com/software/awdtools/cobol/zos/library/.You can check that Web site <strong>for</strong> the latest editions. In the BookManager version ofa document, the content of some tables and syntax diagrams might be alignedimproperly due to variations in the display technology.Support in<strong>for</strong>mation is also available on the product site at www.ibm.com/software/awdtools/cobol/zos/support/.xviii<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Summary of changesThis section lists the major changes that have been made to <strong>Enterprise</strong> <strong>COBOL</strong> inVersion 4. The changes that are described in this in<strong>for</strong>mation have an associatedcross-reference <strong>for</strong> your convenience. The latest technical changes are marked by avertical bar (|) in the left margin in the PDF and BookManager versions.||||||||||||||||||||||||||||Version 4 Release 2 (August 2009)vvvvvvNew and enhanced XML PARSE capabilities are available when you use the z/<strong>OS</strong>XML System Services parser:– You can parse documents with validation against an XML schema when youuse the VALIDATING phrase of the XML PARSE statement (“Parsing XMLdocuments with validation” on page 515).– The per<strong>for</strong>mance of nonvalidating parsing is improved.– Character processing is enhanced <strong>for</strong> any XML document that contains areference to a character that is not included in the single-byte EBCDIC codepage of the document.For further details, see the <strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration<strong>Guide</strong>.A facility <strong>for</strong> customizing compiler diagnostic messages and FIPS messages bychanging their severity or suppressing them is made possible by a newsuboption, MSGEXIT, oftheEXIT compiler option (“Processing of MSGEXIT” onpage 729).A new compiler option, BLOCK0, activates an implicit BLOCK CONTAINS 0 clause <strong>for</strong>all eligible QSAM files in your program (“BLOCK0” on page 307).The underscore character (_) is now supported in user-defined words such asdata-names and program-names. Underscores are also supported in the literal<strong>for</strong>m of program-names.For further details, see the <strong>Enterprise</strong> <strong>COBOL</strong> Language Reference.If you use the integrated CICS translator, the compiler listing will now show theCICS options that are in effect.<strong>Enterprise</strong> <strong>COBOL</strong> applications that use object-oriented syntax <strong>for</strong> Javainteroperability are now supported with Java 5 and Java 6 in addition to theJava SDK 1.4.2 (“Object-oriented syntax, and Java 5 or Java 6 SDKs” on page300).Version 4 Release 1 (December 2007)vvvThe per<strong>for</strong>mance of operations on Unicode (USAGE NATIONAL) data has beensignificantly improved. The compiler now generates z/Architecture ® hardwareinstructions <strong>for</strong> most Unicode MOVE operations and comparisons.A new compiler option, XMLPARSE, makes it possible to choose between parsingwith the parser that is available with the <strong>COBOL</strong> library (<strong>for</strong> compatibility with<strong>Enterprise</strong> <strong>COBOL</strong> Version 3) or with the z/<strong>OS</strong> XML System Services parser(“XMLPARSE” on page 357).New XML PARSE capabilities are available when you parse a document using thez/<strong>OS</strong> XML System Services parser (Chapter 28, “Processing XML input,” onpage 503):– Namespaces and namespace prefixes are processed using new specialregisters and new XML events.– You can specify the document encoding using the ENCODING phrase of the XMLPARSE statement.Prefacexix


vvvvvv– You can parse documents that are encoded in Unicode UTF-8 (“Parsing XMLdocuments encoded in UTF-8” on page 525).– The RETURNING NATIONAL phrase enables you to receive XML documentfragments in Unicode regardless of the original encoding of an XMLdocument.– You can parse documents that reside in a data set or parse very largedocuments a buffer at a time (“Parsing XML documents one segment at atime” on page 518).The XML GENERATE statement has been enhanced (Chapter 29, “Producing XMLoutput,” on page 543):– You can specify a namespace using the NAMESPACE phrase, and a namespaceprefix to be applied to each element using the NAMESPACE-PREFIX phrase.– You can specify the code page of the generated document using the ENCODINGphrase (“Controlling the encoding of generated XML output” on page 547).– XML documents can now be generated in UTF-8 as well as in UTF-16 orvarious EBCDIC code pages.– The WITH ATTRIBUTES phrase causes eligible elementary items to be expressedas attributes rather than as child elements in the generated XML.– The WITH XML-DECLARATION phrase causes an XML declaration to be generated.A new compiler option, OPTFILE, enables the specifying of <strong>COBOL</strong> compileroptions from within a data set (“OPTFILE” on page 335).Compiler listings now cross-reference copybooks and the data sets from whichcopybooks are obtained (“Example: XREF output: COPY/BASIS cross-references”on page 400).Support <strong>for</strong> new features of DB2 ® <strong>for</strong> z/<strong>OS</strong> V9 is enabled when you use theintegrated DB2 coprocessor (SQL compiler option) (“DB2 coprocessor” on page419):– New SQL data types are supported: XML types, BINARY, VARBINARY,BIGINT, and file reference variables.– New SQL syntax <strong>for</strong> XML manipulation, enhancements to large objectmanipulation, MERGE, and SELECT FROM MERGE is supported.– DB2 processing options STDSQL(YES|NO), NOFOR, and SQL(ALL|DB2) aresupported as suboptions to the SQL compiler option (“Compiling with theSQL option” on page 423).Several usability enhancements to <strong>COBOL</strong>-DB2 applications are available whenyou use the integrated DB2 coprocessor:– The compiler listing is enhanced to show the DB2 options in effect (if you useDB2 <strong>for</strong> z/<strong>OS</strong> V9) and to show the expansion of the SQLCA and SQLDAcontrol blocks.– You can specify an alternate ddname <strong>for</strong> DBRMLIB when you invoke thecompiler from an assembler language program (“Starting the compiler froman assembler program” on page 263).– An explicitly coded LOCAL-STORAGE SECTION or WORKING-STORAGE SECTION is nolonger required.Debugging has been enhanced to support Debug Tool V8. A new suboption ofthe TEST compiler option, EJPD, enables the Debug Tool commands JUMPTO andGOTO <strong>for</strong> production debugging. The TEST compiler option has been simplifiedand has restructured suboptions (“TEST” on page 349).xx<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


How to send your commentsYour feedback is important in helping us to provide accurate, high-qualityin<strong>for</strong>mation. If you have comments about this in<strong>for</strong>mation or any other <strong>Enterprise</strong><strong>COBOL</strong> documentation, contact us in one of these ways:vFill out the Readers’ Comments Form and return it by mail or give it to an IBMrepresentative. If there is no Readers’ Comments Form at the back, address yourcomments to:vvIBM CorporationReader CommentsDTX/E269555 Bailey AvenueSan Jose, CA 95141-1003USAUse the Online Readers’ Comments Form at www.ibm.com/software/awdtools/rcf/.Send your comments to the following e-mail address: comments@us.ibm.com.Be sure to include the name of the document, the publication number, the versionof <strong>Enterprise</strong> <strong>COBOL</strong>, and, if applicable, the specific location (<strong>for</strong> example, thepage number or section heading) of the text that you are commenting on.When you send in<strong>for</strong>mation to IBM, you grant IBM a nonexclusive right to use ordistribute the in<strong>for</strong>mation in any way that IBM believes appropriate withoutincurring any obligation to you.AccessibilityAccessibility features help users who have a disability, such as restricted mobilityor limited vision, to use software products successfully. The accessibility features inz/<strong>OS</strong> provide accessibility <strong>for</strong> <strong>Enterprise</strong> <strong>COBOL</strong>.The major accessibility features in z/<strong>OS</strong> are:v Interfaces that are commonly used by screen readers and screen-magnifiersoftwarev Keyboard-only navigationv Ability to customize display attributes such as color, contrast, and font sizeInterface in<strong>for</strong>mationAssistive technology products work with the user interfaces that are found inz/<strong>OS</strong>. For specific guidance in<strong>for</strong>mation, see the documentation <strong>for</strong> the assistivetechnology product that you use to access z/<strong>OS</strong> interfaces.Keyboard navigationUsers can access z/<strong>OS</strong> user interfaces by using TSO/E or ISPF. For in<strong>for</strong>mationabout accessing TSO/E or ISPF interfaces, see the following publications:v z/<strong>OS</strong> TSO/E Primerv z/<strong>OS</strong> TSO/E User’s <strong>Guide</strong>v z/<strong>OS</strong> ISPF User’s <strong>Guide</strong> Volume IPrefacexxi


These guides describe how to use TSO/E and ISPF, including the use of keyboardshortcuts or function keys (PF keys). Each guide includes the default settings <strong>for</strong>the PF keys and explains how to modify their functions.Accessibility of this in<strong>for</strong>mationThe English-language XHTML <strong>for</strong>mat of this in<strong>for</strong>mation that will be provided inthe IBM System z <strong>Enterprise</strong> Development Tools & Compilers In<strong>for</strong>mation Centerat publib.boulder.ibm.com/infocenter/pdthelp/index.jsp is accessible to visuallyimpaired individuals who use a screen reader.To enable your screen reader to accurately read syntax diagrams, source codeexamples, and text that contains the period or comma PICTURE symbols, you mustset the screen reader to speak all punctuation.|||IBM and accessibilitySee the IBM Human Ability and Accessibility Center at www.ibm.com/able <strong>for</strong>more in<strong>for</strong>mation about the commitment that IBM has to accessibility.xxii<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 1. Coding your programChapter 1. Structuring your program . . . . . 5Identifying a program . . . . . . . . . . . 5Identifying a program as recursive . . . . . . 6Marking a program as callable by containingprograms . . . . . . . . . . . . . . 6Setting a program to an initial state. . . . . . 7Changing the header of a source listing . . . . 7Describing the computing environment . . . . . 7Example: FILE-CONTROL entries . . . . . . 8Specifying the collating sequence . . . . . . 9Example: specifying the collating sequence . . 9Defining symbolic characters . . . . . . . 10Defining a user-defined class . . . . . . . 10Defining files to the operating system . . . . 10Varying the input or output file at run time . 11Optimizing buffer and device space . . . . 12Describing the data . . . . . . . . . . . . 13Using data in input and output operations . . . 13FILE SECTION entries. . . . . . . . . 14Comparison of WORKING-STORAGE andLOCAL-STORAGE . . . . . . . . . . . 16Example: storage sections. . . . . . . . 17Using data from another program . . . . . . 18Sharing data in separately compiled programs 18Sharing data in nested programs . . . . . 18Sharing data in recursive or multithreadedprograms . . . . . . . . . . . . . 19Processing the data . . . . . . . . . . . . 19How logic is divided in the PROCEDUREDIVISION . . . . . . . . . . . . . . 20Imperative statements . . . . . . . . . 21Conditional statements . . . . . . . . 21Compiler-directing statements . . . . . . 22Scope terminators . . . . . . . . . . 22Declaratives . . . . . . . . . . . . . 23Chapter 2. Using data . . . . . . . . . . 25Using variables, structures, literals, and constants . 25Using variables . . . . . . . . . . . . 25Using data items and group items . . . . . . 26Using literals . . . . . . . . . . . . . 27Using constants . . . . . . . . . . . . 28Using figurative constants . . . . . . . . 28Assigning values to data items . . . . . . . . 29Examples: initializing data items . . . . . . 30Initializing a structure (INITIALIZE) . . . . . 32Assigning values to elementary data items(MOVE) . . . . . . . . . . . . . . 34Assigning values to group data items (MOVE) . 35Assigning arithmetic results (MOVE orCOMPUTE) . . . . . . . . . . . . . 36Assigning input from a screen or file (ACCEPT) 37Displaying values on a screen or in a file (DISPLAY) 38Displaying data on the system logical outputdevice . . . . . . . . . . . . . . . 39Using WITH NO ADVANCING . . . . . . 39Using intrinsic functions (built-in functions) . . . 40Using tables (arrays) and pointers . . . . . . . 41Storage and its addressability . . . . . . . . 42Settings <strong>for</strong> RMODE . . . . . . . . . . . 42Storage restrictions <strong>for</strong> passing data . . . . . 43Location of data areas . . . . . . . . . . 43Storage <strong>for</strong> LOCAL-STORAGE data . . . . . 43Storage <strong>for</strong> external data . . . . . . . . . 44Storage <strong>for</strong> QSAM input-output buffers . . . . 44Chapter 3. Working with numbers and arithmetic 45Defining numeric data. . . . . . . . . . . 45Displaying numeric data . . . . . . . . . . 47Controlling how numeric data is stored . . . . . 48Formats <strong>for</strong> numeric data. . . . . . . . . . 49External decimal (DISPLAY and NATIONAL)items . . . . . . . . . . . . . . . 49External floating-point (DISPLAY andNATIONAL) items . . . . . . . . . . . 50Binary (COMP) items . . . . . . . . . . 50Native binary (COMP-5) items . . . . . . . 51Packed-decimal (COMP-3) items . . . . . . 52Internal floating-point (COMP-1 and COMP-2)items . . . . . . . . . . . . . . . 52Examples: numeric data and internalrepresentation . . . . . . . . . . . . 52Data <strong>for</strong>mat conversions . . . . . . . . . . 54Conversions and precision . . . . . . . . 54Conversions that lose precision . . . . . . 54Conversions that preserve precision . . . . 55Conversions that result in rounding . . . . 55Sign representation of zoned and packed-decimaldata . . . . . . . . . . . . . . . . . 55Checking <strong>for</strong> incompatible data (numeric class test) 56Per<strong>for</strong>ming arithmetic . . . . . . . . . . . 57Using COMPUTE and other arithmeticstatements . . . . . . . . . . . . . . 58Using arithmetic expressions . . . . . . . 58Using numeric intrinsic functions . . . . . . 59Using math-oriented callable services. . . . . 60Using date callable services . . . . . . . . 62Examples: numeric intrinsic functions . . . . 62General number handling . . . . . . . 63Date and time . . . . . . . . . . . 63Finance . . . . . . . . . . . . . . 63Mathematics . . . . . . . . . . . . 64Statistics . . . . . . . . . . . . . 64Fixed-point contrasted with floating-point arithmetic 64Floating-point evaluations . . . . . . . . 65Fixed-point evaluations . . . . . . . . . 65Arithmetic comparisons (relation conditions) . . 65Examples: fixed-point and floating-pointevaluations . . . . . . . . . . . . . 66Using currency signs . . . . . . . . . . . 67Example: multiple currency signs . . . . . . 68© Copyright IBM Corp. 1991, 2009 1


Chapter 4. Handling tables. . . . . . . . . 69Defining a table (OCCURS) . . . . . . . . . 69Nesting tables . . . . . . . . . . . . . 71Example: subscripting . . . . . . . . . . 72Example: indexing . . . . . . . . . . . 72Referring to an item in a table . . . . . . . . 72Subscripting . . . . . . . . . . . . . 73Indexing . . . . . . . . . . . . . . 74Putting values into a table . . . . . . . . . 75Loading a table dynamically. . . . . . . . 75Initializing a table (INITIALIZE) . . . . . . 76Assigning values when you define a table(VALUE) . . . . . . . . . . . . . . 77Initializing each table item individually . . . 77Initializing a table at the group level . . . . 78Initializing all occurrences of a given tableelement. . . . . . . . . . . . . . 78Example: PERFORM and subscripting . . . . 79Example: PERFORM and indexing. . . . . . 80Creating variable-length tables (DEPENDING ON) 81Loading a variable-length table . . . . . . . 82Assigning values to a variable-length table . . . 83Searching a table . . . . . . . . . . . . 84Doing a serial search (SEARCH) . . . . . . 84Example: serial search . . . . . . . . . 84Doing a binary search (SEARCH ALL) . . . . 85Example: binary search . . . . . . . . 86Processing table items using intrinsic functions . . 86Example: processing tables using intrinsicfunctions . . . . . . . . . . . . . . 87Chapter 5. Selecting and repeating programactions . . . . . . . . . . . . . . . 89Selecting program actions . . . . . . . . . 89Coding a choice of actions . . . . . . . . 89Using nested IF statements . . . . . . . 90Using the EVALUATE statement . . . . . 91Coding conditional expressions . . . . . . . 94Switches and flags . . . . . . . . . . 95Defining switches and flags . . . . . . . 95Example: switches . . . . . . . . . . 95Example: flags . . . . . . . . . . . 96Resetting switches and flags . . . . . . . 96Example: set switch on . . . . . . . . 96Example: set switch off . . . . . . . . 97Repeating program actions . . . . . . . . . 97Choosing inline or out-of-line PERFORM . . . 98Example: inline PERFORM statement. . . . 98Coding a loop . . . . . . . . . . . . 99Looping through a table . . . . . . . . . 100Executing multiple paragraphs or sections. . . 100Chapter 6. Handling strings . . . . . . . . 101Joining data items (STRING) . . . . . . . . 101Example: STRING statement . . . . . . . 102STRING results. . . . . . . . . . . 103Splitting data items (UNSTRING) . . . . . . 103Example: UNSTRING statement . . . . . . 104UNSTRING results . . . . . . . . . 105Manipulating null-terminated strings . . . . . 106Example: null-terminated strings . . . . . . 107Referring to substrings of data items . . . . . 107Reference modifiers . . . . . . . . . . 109Example: arithmetic expressions as referencemodifiers . . . . . . . . . . . . . . 110Example: intrinsic functions as referencemodifiers . . . . . . . . . . . . . . 110Tallying and replacing data items (INSPECT) . . . 111Examples: INSPECT statement. . . . . . . 111Converting data items (intrinsic functions). . . . 112Converting to uppercase or lowercase(UPPER-CASE, LOWER-CASE) . . . . . . 113Trans<strong>for</strong>ming to reverse order (REVERSE) . . . 113Converting to numbers (NUMVAL,NUMVAL-C) . . . . . . . . . . . . 113Converting from one code page to another . . 115Evaluating data items (intrinsic functions) . . . . 115Evaluating single characters <strong>for</strong> collatingsequence . . . . . . . . . . . . . . 115Finding the largest or smallest data item . . . 116Returning variable-length results withalphanumeric or national functions . . . . 117Finding the length of data items . . . . . . 118Finding the date of compilation . . . . . . 119Chapter 7. Processing data in an internationalenvironment . . . . . . . . . . . . . 121<strong>COBOL</strong> statements and national data . . . . . 122Intrinsic functions and national data. . . . . . 124Unicode and the encoding of language characters 125Using national data (Unicode) in <strong>COBOL</strong> . . . . 126Defining national data items . . . . . . . 127Using national literals . . . . . . . . . 127Using national-character figurative constants 128Defining national numeric data items . . . . 129National groups . . . . . . . . . . . 129Using national groups . . . . . . . . . 130Using national groups as elementary items 131Using national groups as group items . . . 132Storage of character data . . . . . . . . 133Converting to or from national (Unicode)representation . . . . . . . . . . . . . 134Converting alphanumeric, DBCS, and integer tonational (MOVE) . . . . . . . . . . . 134Converting alphanumeric or DBCS to national(NATIONAL-OF) . . . . . . . . . . . 135Converting national to alphanumeric(DISPLAY-OF) . . . . . . . . . . . . 136Overriding the default code page. . . . . . 136Conversion exceptions . . . . . . . . . 136Example: converting to and from national data 137Processing UTF-8 data . . . . . . . . . . 137Processing Chinese GB 18030 data . . . . . . 138Comparing national (UTF-16) data . . . . . . 139Comparing two class national operands . . . 139Comparing class national and class numericoperands . . . . . . . . . . . . . . 140Comparing national numeric and other numericoperands . . . . . . . . . . . . . . 140Comparing national and other character-stringoperands . . . . . . . . . . . . . . 1402 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Comparing national data andalphanumeric-group operands. . . . . . . 141Coding <strong>for</strong> use of DBCS support . . . . . . . 141Declaring DBCS data . . . . . . . . . . 142Using DBCS literals . . . . . . . . . . 142Testing <strong>for</strong> valid DBCS characters . . . . . 143Processing alphanumeric data items that containDBCS data . . . . . . . . . . . . . 143Chapter 8. Processing files . . . . . . . . 145File organization and input-output devices . . . 145Choosing file organization and access mode . . . 147Format <strong>for</strong> coding input and output . . . . . 148Allocating files . . . . . . . . . . . . . 149Checking <strong>for</strong> input or output errors . . . . . . 150Chapter 9. Processing QSAM files . . . . . 151Defining QSAM files and records in <strong>COBOL</strong> . . . 151Establishing record <strong>for</strong>mats. . . . . . . . 152Logical records . . . . . . . . . . . 152Requesting fixed-length <strong>for</strong>mat . . . . . 153Requesting variable-length <strong>for</strong>mat . . . . 154Requesting spanned <strong>for</strong>mat. . . . . . . 156Requesting undefined <strong>for</strong>mat . . . . . . 158Setting block sizes . . . . . . . . . . . 159Coding input and output statements <strong>for</strong> QSAMfiles . . . . . . . . . . . . . . . . 161Opening QSAM files . . . . . . . . . . 162Dynamically creating QSAM files. . . . . . 163Adding records to QSAM files. . . . . . . 163Updating QSAM files . . . . . . . . . 164Writing QSAM files to a printer or spooled dataset . . . . . . . . . . . . . . . . 164Closing QSAM files . . . . . . . . . . 165Handling errors in QSAM files . . . . . . . 165Working with QSAM files . . . . . . . . . 166Defining and allocating QSAM files . . . . . 166Parameters <strong>for</strong> creating QSAM files . . . . 169Retrieving QSAM files . . . . . . . . . 169Parameters <strong>for</strong> retrieving QSAM files . . . 170Ensuring that file attributes match yourprogram . . . . . . . . . . . . . . 170Processing existing files . . . . . . . . 171Processing new files . . . . . . . . . 172Using striped extended-<strong>for</strong>mat QSAM data sets 172Allocation of buffers <strong>for</strong> QSAM files. . . . 173Accessing HFS files using QSAM. . . . . . . 174Labels <strong>for</strong> QSAM files . . . . . . . . . . 174Using trailer and header labels . . . . . . 175Format of standard labels . . . . . . . . 176Standard user labels . . . . . . . . . 177Processing QSAM ASCII files on tape . . . . . 177Processing ASCII file labels. . . . . . . . . 178Chapter 10. Processing VSAM files . . . . . 179VSAM files . . . . . . . . . . . . . . 180Defining VSAM file organization and records . . 181Specifying sequential organization <strong>for</strong> VSAMfiles . . . . . . . . . . . . . . . 182Specifying indexed organization <strong>for</strong> VSAM files 182Using alternate keys . . . . . . . . . 183Using an alternate index. . . . . . . . 183Specifying relative organization <strong>for</strong> VSAM files 184Fixed-length and variable-length RRDS. . . 184Using variable-length RRDS . . . . . . 184Specifying access modes <strong>for</strong> VSAM files . . . 185Example: using dynamic access with VSAMfiles . . . . . . . . . . . . . . 185Defining record lengths <strong>for</strong> VSAM files. . . . 185Defining fixed-length records . . . . . . 186Defining variable-length records . . . . . 186Coding input and output statements <strong>for</strong> VSAMfiles . . . . . . . . . . . . . . . . 187File position indicator . . . . . . . . . 189Opening a file (ESDS, KSDS, or RRDS) . . . . 189Opening an empty file . . . . . . . . 190Statements to load records into a VSAM file 191Opening a loaded file (a file with records) 191Reading records from a VSAM file . . . . . 192Updating records in a VSAM file . . . . . . 193Adding records to a VSAM file . . . . . . 193Replacing records in a VSAM file. . . . . . 194Deleting records from a VSAM file . . . . . 194Closing VSAM files . . . . . . . . . . 194Handling errors in VSAM files . . . . . . . 195Protecting VSAM files with a password . . . . 196Example: password protection <strong>for</strong> a VSAMindexed file . . . . . . . . . . . . . 196Working with VSAM data sets under z/<strong>OS</strong> andz/<strong>OS</strong> UNIX . . . . . . . . . . . . . . 197Defining VSAM files . . . . . . . . . . 197Creating alternate indexes . . . . . . . . 198Example: entries <strong>for</strong> alternate indexes . . . 199Allocating VSAM files . . . . . . . . . 200Sharing VSAM files through RLS . . . . . . 202Preventing update problems with VSAM filesin RLS mode . . . . . . . . . . . 202Restrictions when using RLS . . . . . . 203Handling errors in VSAM files in RLS mode 203Improving VSAM per<strong>for</strong>mance . . . . . . . 203Chapter 11. Processing line-sequential files . . 207Defining line-sequential files and records in<strong>COBOL</strong> . . . . . . . . . . . . . . . 207Allowable control characters . . . . . . . 208Describing the structure of a line-sequential file 208Defining and allocating line-sequential files . . . 209Coding input-output statements <strong>for</strong> line-sequentialfiles . . . . . . . . . . . . . . . . 209Opening line-sequential files . . . . . . . 210Reading records from line-sequential files . . . 210Adding records to line-sequential files . . . . 211Closing line-sequential files. . . . . . . . 211Handling errors in line-sequential files . . . . . 212Chapter 12. Sorting and merging files . . . . 213Sort and merge process . . . . . . . . . . 214Describing the sort or merge file . . . . . . . 214Describing the input to sorting or merging . . . 215Example: describing sort and input files <strong>for</strong>SORT . . . . . . . . . . . . . . . 215Coding the input procedure . . . . . . . . 216Part 1. Coding your program 3


Describing the output from sorting or merging . . 217Coding the output procedure . . . . . . . . 218Example: coding the output procedure whenusing DFSORT . . . . . . . . . . . . 218Restrictions on input and output procedures . . . 219Defining sort and merge data sets . . . . . . 219Sorting variable-length records . . . . . . . 220Requesting the sort or merge . . . . . . . . 220Setting sort or merge criteria . . . . . . . 221Example: sorting with input and outputprocedures . . . . . . . . . . . . . 222Choosing alternate collating sequences . . . . 223Sorting on windowed date fields . . . . . . 223Preserving the original sequence of records withequal keys . . . . . . . . . . . . . 224Determining whether the sort or merge wassuccessful . . . . . . . . . . . . . . 224Stopping a sort or merge operation prematurely 225Improving sort per<strong>for</strong>mance with FASTSRT . . . 225FASTSRT requirements <strong>for</strong> JCL . . . . . . 226FASTSRT requirements <strong>for</strong> sort input andoutput files . . . . . . . . . . . . . 226QSAM requirements . . . . . . . . . 227VSAM requirements . . . . . . . . . 227Checking <strong>for</strong> sort errors with NOFASTSRT . . . 227Controlling sort behavior . . . . . . . . . 228Changing DFSORT defaults with controlstatements . . . . . . . . . . . . . 229Default characteristics of the IGZSRTCD dataset . . . . . . . . . . . . . . . 230Allocating storage <strong>for</strong> sort or merge operations 230Allocating space <strong>for</strong> sort files . . . . . . . 231Using checkpoint/restart with DFSORT . . . . 231Sorting under CICS . . . . . . . . . . . 231CICS SORT application restrictions . . . . . 232Chapter 13. Handling errors . . . . . . . . 233Requesting dumps . . . . . . . . . . . 233Handling errors in joining and splitting strings . . 234Handling errors in arithmetic operations . . . . 234Example: checking <strong>for</strong> division by zero . . . . 235Handling errors in input and output operations 235Using the end-of-file condition (AT END) . . . 238Coding ERROR declaratives . . . . . . . 238Using file status keys. . . . . . . . . . 239Example: file status key . . . . . . . . . 240Using VSAM status codes (VSAM files only) 241Example: checking VSAM status codes . . . . 241Coding INVALID KEY phrases . . . . . . 243Example: FILE STATUS and INVALID KEY . . 243Handling errors when calling programs . . . . 244Writing routines <strong>for</strong> handling errors . . . . . . 2444 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 1. Structuring your program<strong>COBOL</strong> programs consist of four divisions: IDENTIFICATION DIVISION, ENVIRONMENTDIVISION, DATA DIVISION, and PROCEDURE DIVISION. Each division has a specificlogical function.To define a program, only the IDENTIFICATION DIVISION is required.To define a <strong>COBOL</strong> class or method, you need to define some divisions differentlythan you do <strong>for</strong> a program.Identifying a programRELATED TASKS“Identifying a program”“Describing the computing environment” on page 7“Describing the data” on page 13“Processing the data” on page 19“Defining a class” on page 564“Defining a class instance method” on page 569“Structuring OO applications” on page 603Use the IDENTIFICATION DIVISION to name a program and optionally provide otheridentifying in<strong>for</strong>mation.You can use the optional AUTHOR, INSTALLATION, DATE-WRITTEN, and DATE-COMPILEDparagraphs <strong>for</strong> descriptive in<strong>for</strong>mation about a program. The data you enter in theDATE-COMPILED paragraph is replaced with the latest compilation date.IDENTIFICATION DIVISION.Program-ID. Helloprog.Author. A. Programmer.Installation. Computing Laboratories.Date-Written. 07/30/2009.Date-Compiled. 08/30/2009.Use the PROGRAM-ID paragraph to name your program. The program-name that youassign is used in these ways:v Other programs use that name to call your program.vvThe name appears in the header on each page, except the first, of the programlisting that is generated when you compile the program.If you use the NAME compiler option, the name is placed on the NAMElinkage-editor or binder control statement to identify the object module that thecompilation 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 routinesrather than to your intended program:– AFB– AFH– CBC© Copyright IBM Corp. 1991, 2009 5


|||||||– CEE– CEH– CEL– CEQ– CEU– DFH– DSN– EDC– FOR– IBM– IFY– IGY– IGZ– ILBTip: If a program-name is case sensitive, avoid mismatches with the name that thecompiler is looking <strong>for</strong>. Verify that the appropriate setting of the PGMNAMEcompiler option is in effect.RELATED TASKS“Changing the header of a source listing” on page 7“Identifying a program as recursive”“Marking a program as callable by containing programs”“Setting a program to an initial state” on page 7RELATED REFERENCESCompiler limits (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Conventions <strong>for</strong> program-names (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Identifying a program as recursiveCode the RECURSIVE attribute on the PROGRAM-ID clause to specify that a programcan be recursively reentered while a previous invocation is still active.You can code RECURSIVE only on the outermost program of a compilation unit.Neither nested subprograms nor programs that contain nested subprograms can berecursive. You must code RECURSIVE <strong>for</strong> programs that you compile with the THREADoption.RELATED TASKS“Sharing data in recursive or multithreaded programs” on page 19“Making recursive calls” on page 461Marking a program as callable by containing programsUse the COMMON attribute in the PROGRAM-ID paragraph to specify that a program canbe called by the containing program or by any program in the containing program.The COMMON program cannot be called by any program contained in itself.Only contained programs can have the COMMON attribute.6 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED CONCEPTS“Nested programs” on page 458Setting a program to an initial stateUse the INITIAL attribute to specify that whenever a program is called, thatprogram and any nested programs that it contains are to be placed in their initialstate.When a program is in its initial state:v Data items that have VALUE clauses are set to the specified values.v Changed GO TO statements and PERFORM statements are in their initial states.v Non-EXTERNAL files are closed.RELATED TASKS“Ending and reentering main programs or subprograms” on page 448“Making static calls” on page 450“Making dynamic calls” on page 451Changing the header of a source listingThe header on the first page of a source listing contains the identification of thecompiler and the current release level, the date and time of compilation, and thepage number.The following example shows these five elements:PP 5655-S71 IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> 4.2.0 Date 08/30/2009 Time 15:05:19 Page 1The header indicates the compilation plat<strong>for</strong>m. You can customize the header onsucceeding pages of the listing by using the compiler-directing TITLE statement.RELATED REFERENCESTITLE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Describing the computing environmentIn the ENVIRONMENT DIVISION of a program, you describe the aspects of theprogram that depend on the computing environment.Use the CONFIGURATION SECTION to specify the following items:v Computer <strong>for</strong> compiling the program (in the SOURCE-COMPUTER paragraph)v Computer <strong>for</strong> running the program (in the OBJECT-COMPUTER paragraph)v Special items such as the currency sign and symbolic characters (in theSPECIAL-NAMES paragraph)v User-defined classes (in the REP<strong>OS</strong>ITORY paragraph)Use the FILE-CONTROL and I-O-CONTROL paragraphs of the INPUT-OUTPUT SECTION to:v Identify and describe the characteristics of the files in the program.v Associate your files with the external QSAM, VSAM, or HFS (hierarchical filesystem) data sets where they physically reside.Chapter 1. Structuring your program 7


vThe terms file in <strong>COBOL</strong> terminology and data set or HFS file in operating-systemterminology have essentially the same meaning and are used interchangeably inthis in<strong>for</strong>mation.For Customer In<strong>for</strong>mation Control System (CICS) and online In<strong>for</strong>mationManagement System (IMS ) message processing programs (MPP), code only theENVIRONMENT DIVISION header and, optionally, the CONFIGURATION SECTION. CICSdoes not allow <strong>COBOL</strong> definition of files. IMS allows <strong>COBOL</strong> definition of filesonly <strong>for</strong> batch programs.Provide in<strong>for</strong>mation to control efficient transmission of the data records betweenyour program and the external medium.“Example: FILE-CONTROL entries”RELATED TASKS“Specifying the collating sequence” on page 9“Defining symbolic characters” on page 10“Defining a user-defined class” on page 10“Defining files to the operating system” on page 10RELATED REFERENCESSections and paragraphs (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: FILE-CONTROL entriesThe following table shows example FILE-CONTROL entries <strong>for</strong> a QSAM sequentialfile, a VSAM indexed file, and a line-sequential file.Table 1. FILE-CONTROL entriesQSAM file VSAM file Line-sequential fileSELECT PRINTFILE 1ASSIGN TO UPDPRINT 2ORGANIZATION IS SEQUENTIAL 3ACCESS IS SEQUENTIAL. 4 SELECT COMMUTER-FILE 1ASSIGN TO COMMUTER 2ORGANIZATION IS INDEXED 3ACCESS IS RANDOM 4SELECT PRINTFILE 1ASSIGN TO UPDPRINT 2ORGANIZATION IS LINE SEQUENTIAL 3ACCESS IS SEQUENTIAL. 4RECORD KEY IS COMMUTER-KEY 5FILE STATUS IS 5COMMUTER-FILE-STATUSCOMMUTER-VSAM-STATUS.1. The SELECT clause chooses a file in the <strong>COBOL</strong> program to be associated with an external data set.2. The ASSIGN clause associates the program’s name <strong>for</strong> the file with the external name <strong>for</strong> the actual data file. Youcan 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 <strong>for</strong> processing: sequential,random, or dynamic. For QSAM and line-sequential files, the ACCESS MODE clause is optional. These files alwayshave sequential organization.5. For VSAM files, you might have additional statements in the FILE-CONTROL paragraph depending on the type ofVSAM file you use.RELATED TASKSChapter 9, “Processing QSAM files,” on page 151Chapter 10, “Processing VSAM files,” on page 179Chapter 11, “Processing line-sequential files,” on page 207“Describing the computing environment” on page 78 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Specifying the collating sequenceYou can use the PROGRAM COLLATING SEQUENCE clause and the ALPHABET clause of theSPECIAL-NAMES paragraph to establish the collating sequence that is used in severaloperations on alphanumeric items.These clauses specify the collating sequence <strong>for</strong> the following operations onalphanumeric items:vvvvComparisons explicitly specified in relation conditions and condition-nameconditionsHIGH-VALUE and LOW-VALUE settingsSEARCH ALLSORT and MERGE unless overridden by a COLLATING SEQUENCE phrase in the SORTor MERGE statement“Example: specifying the collating sequence”The sequence that you use can be based on one of these alphabets:v EBCDIC: references the collating sequence associated with the EBCDIC charactersetv NATIVE: references the same collating sequence as EBCDICv STANDARD-1: references the collating sequence associated with the ASCIIcharacter set defined by ANSI INCITS X3.4, Coded Character Sets - 7-bit AmericanNational Standard Code <strong>for</strong> In<strong>for</strong>mation Interchange (7-bit ASCII)v STANDARD-2: references the collating sequence associated with the character setdefined by ISO/IEC 646 -- In<strong>for</strong>mation technology -- ISO 7-bit coded character set <strong>for</strong>in<strong>for</strong>mation interchange, International Reference Versionv An alteration of the EBCDIC sequence that you define in the SPECIAL-NAMESparagraphThe PROGRAM COLLATING SEQUENCE clause does not affect comparisons that involvenational or DBCS operands.RELATED TASKS“Choosing alternate collating sequences” on page 223“Comparing national (UTF-16) data” on page 139Example: specifying the collating sequenceThe following example shows the ENVIRONMENT DIVISION coding that you can useto specify a collating sequence in which uppercase and lowercase letters aresimilarly handled in comparisons and in sorting and merging.When you change the EBCDIC sequence in the SPECIAL-NAMES paragraph, theoverall collating sequence is affected, not just the collating sequence of thecharacters that are included in the SPECIAL-NAMES paragraph.IDENTIFICATION DIVISION....ENVIRONMENT DIVISION.CONFIGURATION SECTION.Source-Computer. IBM-390.Object-Computer. IBM-390.Program Collating Sequence Special-Sequence.Special-Names.Alphabet Special-Sequence IsChapter 1. Structuring your program 9


"A" Also "a""B" Also "b""C" Also "c""D" Also "d""E" Also "e""F" Also "f""G" Also "g""H" Also "h""I" Also "i""J" Also "j""K" Also "k""L" Also "l""M" Also "m""N" Also "n""O" Also "o""P" Also "p""Q" Also "q""R" Also "r""S" Also "s""T" Also "t""U" Also "u""V" Also "v""W" Also "w""X" Also "x""Y" Also "y""Z" Also "z".RELATED TASKS“Specifying the collating sequence” on page 9Defining symbolic charactersUse the SYMBOLIC CHARACTERS clause to give symbolic names to any character of thespecified alphabet. Use ordinal position to identify the character, where position 1corresponds to character X’00’.For example, to give a name to the backspace character (X’16’ in the EBCDICalphabet), code:SYMBOLIC CHARACTERS BACKSPACE IS 23Defining a user-defined classUse the CLASS clause to give a name to a set of characters that you list in theclause.For example, name the set of digits by coding the following clause:CLASS DIGIT IS "0" THROUGH "9"You can reference the class-name only in a class condition. (This user-defined classis not the same as an object-oriented class.)Defining files to the operating systemFor all files that you process in your <strong>COBOL</strong> program, you need to define the filesto the operating system with an appropriate system data definition.Depending on the operating system, this system data definition can take any of thefollowing <strong>for</strong>ms:v DD statement <strong>for</strong> MVS JCL.10 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


v ALLOCATE command under TSO.v Environment variable <strong>for</strong> z/<strong>OS</strong> or UNIX. The contents can define either an MVSdata set or a file in the HFS (hierarchical file system).The following examples show the relationship of a FILE-CONTROL entry to thesystem data definition and to the FD entry in the FILE SECTION:v JCL DD statement:vv(1)//OUTFILE DD DSNAME=MY.OUT171,UNIT=SYSDA,SPACE=(TRK,(50,5))/*Environment variable (export command):(1)export OUTFILE=DSN(MY.OUT171),UNIT(SYSDA),SPACE(TRK,(50,5))<strong>COBOL</strong> code:ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT CARPOOLASSIGN TO OUTFILE (1)ORGANIZATION IS SEQUENTIAL....DATA DIVISION.FILE SECTION.FD CARPOOL (2)LABEL RECORD STANDARDBLOCK CONTAINS 0 CHARACTERSRECORD CONTAINS 80 CHARACTERS(1) The assignment-name in the ASSIGN clause points to the ddname OUTFILE inthe DD statement or the environment variable OUTFILE in the exportcommand:v //OUTFILE DD DSNAME=OUT171 ...,orv export OUTFILE= ...(2) When you specify a file file-name in a FILE-CONTROL entry, you mustdescribe the file in an FD entry:SELECT CARPOOL...FD CARPOOLRELATED TASKS“Optimizing buffer and device space” on page 12RELATED REFERENCES“FILE SECTION entries” on page 14File section (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Varying the input or output file at run timeThe file-name that you code in a SELECT clause is used as a constant throughoutyour <strong>COBOL</strong> program, but you can associate the name of the file with a differentactual file at run time.Changing a file-name in a <strong>COBOL</strong> program would require changing the inputstatements and output statements and recompiling the program. Alternatively, youcan change the DSNAME value in the DD statement or the DSN or PATH value in theexport command to use a different file at run time.Chapter 1. Structuring your program 11


Environment variable values that are in effect at the time of the OPEN statement areused <strong>for</strong> associating <strong>COBOL</strong> file-names to the system file-names (including anypath specifications).The name that you use in the assignment-name of the ASSIGN clause must be thesame as the ddname in the DD statement or the environment variable in the exportcommand.The file-name that you use in the SELECT clause (such as SELECT MASTER) must be thesame as in the FD file-name entry.Two files should not use the same ddname or environment variable name in theirSELECT clauses; otherwise, results could be unpredictable. For example, if DISPLAYoutput is directed to SYSOUT, do not use SYSOUT as the ddname or environmentvariable name in the SELECT clause <strong>for</strong> a file.Example: using different input files:This example shows that you use the same <strong>COBOL</strong> program to access differentfiles by coding a DD statement or an export command be<strong>for</strong>e the programs runs.Consider a <strong>COBOL</strong> program that contains the following SELECT clause:SELECT MASTER ASSIGN TO DA-3330-S-MASTERAAssume the three possible input files are MASTER1, MASTER2, and MASTER3. Be<strong>for</strong>erunning the program, code one of the following DD statements in the job step thatcalls <strong>for</strong> program execution, or issue one of the following export commands fromthe 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 there<strong>for</strong>e be a reference to the filecurrently assigned to the ddname or environment-variable name MASTERA.Notice that in this example, you cannot use the PATH(path) <strong>for</strong>m of the exportcommand to reference a line-sequential file in the HFS, because you cannot specifyan organization field (S- or AS-) with a line-sequential file.Optimizing buffer and device spaceUse the APPLY WRITE-ONLY clause to make optimum use of buffer and device spacewhen you create a sequential file with blocked variable-length records.With APPLY WRITE-ONLY specified, a buffer is truncated only when the next recorddoes not fit in the unused portion of the buffer. Without APPLY WRITE-ONLYspecified, a buffer is truncated when it does not have enough space <strong>for</strong> amaximum-size record.The APPLY WRITE-ONLY clause has meaning only <strong>for</strong> sequential files that havevariable-length records and are blocked.12 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The AWO compiler option applies an implicit APPLY WRITE-ONLY clause to all eligiblefiles. The NOAWO compiler option has no effect on files that have the APPLYWRITE-ONLY clause specified. The APPLY WRITE-ONLY clause takes precedence overthe NOAWO compiler option.The APPLY-WRITE ONLY clause can cause input files to use a record area rather thanprocess the data in the buffer. This use might affect the processing of both inputfiles and output files.Describing the dataRELATED REFERENCES“AWO” on page 307Define the characteristics of your data, and group your data definitions into one ormore of the sections in the DATA DIVISION.You can use these sections <strong>for</strong> defining the following types of data:v Data used in input-output operations: FILE SECTIONv Data developed <strong>for</strong> internal processing:– To have storage be statically allocated and exist <strong>for</strong> the life of the run unit:WORKING-STORAGE SECTION– To have storage be allocated each time a program is entered, and deallocatedon return from the program: LOCAL-STORAGE SECTIONv Data from another program: LINKAGE SECTIONThe <strong>Enterprise</strong> <strong>COBOL</strong> compiler limits the maximum size of DATA DIVISIONelements. For details, see the related reference about compiler limits below.RELATED CONCEPTS“Comparison of WORKING-STORAGE and LOCAL-STORAGE” on page 16RELATED TASKS“Using data in input and output operations”“Using data from another program” on page 18RELATED REFERENCESCompiler limits (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using data in input and output operationsDefine the data that you use in input and output operations in the FILE SECTION.Provide the following in<strong>for</strong>mation about the data:v Name the input and output files that the program will use. Use the FD entry togive names to the files that the input-output statements in the PROCEDUREDIVISION can refer to.Data items defined in the FILE SECTION are not available to PROCEDURE DIVISIONstatements until the file has been successfully opened.v In the record description that follows the FD entry, describe the fields of therecords in the file:– You can code a level-01 description of the entire record, and then in theWORKING-STORAGE SECTION code a working copy that describes the fields of theChapter 1. Structuring your program 13


ecord in more detail. Use the READ INTO statement to bring the records intoWORKING-STORAGE. Processing occurs on the copy of data in WORKING-STORAGE.A WRITE FROM statement writes processed data into the record area defined inthe FILE SECTION.– The record-name established is the object of WRITE and REWRITE statements.– For QSAM files only, you can set the record <strong>for</strong>mat in the RECORDING MODEclause. If you omit the RECORDING MODE clause, the compiler determines therecord <strong>for</strong>mat based on the RECORD clause and on the level-01 recorddescriptions.– For QSAM files, you can set a blocking factor <strong>for</strong> the file in the BLOCKCONTAINS clause. If you omit the BLOCK CONTAINS clause, the file defaults tounblocked. However, you can override this with z/<strong>OS</strong> data managementfacilities (including a DD file job-control statement).– For line-sequential files, you can set a blocking factor <strong>for</strong> the file in the BLOCKCONTAINS clause. When you code BLOCK CONTAINS 1 RECORDS, orBLOCKCONTAINS n CHARACTERS, where n is the length of one logical record in bytes,WRITE statements result in the record being transferred immediately to the filerather than being buffered. This technique is useful when you want eachrecord written immediately, such as to an error log.Programs in the same run unit can share, or have access to, common files. Themethod <strong>for</strong> doing this depends on whether the programs are part of a nested(contained) structure or are separately compiled (including programs compiled aspart of a batch sequence).You can use the EXTERNAL clause <strong>for</strong> separately compiled programs. A file that isdefined as EXTERNAL can be referenced by any program in the run unit thatdescribes the file.You can use the GLOBAL clause <strong>for</strong> programs in a nested, or contained, structure. Ifa program contains another program (directly or indirectly), both programs canaccess a common file by referencing a GLOBAL file-name.RELATED CONCEPTS“Nested programs” on page 458RELATED TASKS“Sharing files between programs (external files)” on page 475RELATED REFERENCES“FILE SECTION entries”FILE SECTION entriesThe entries that you can use in the FILE SECTION are summarized in the tablebelow.Table 2. FILE SECTION entriesClause To define NotesFDThe file-name to bereferred to in PROCEDUREDIVISION input-outputstatements (OPEN, CL<strong>OS</strong>E,READ, also START andDELETE <strong>for</strong> VSAM)Must match file-name in the SELECT clause.file-name is associated with a ddnamethrough the assignment-name.14 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 2. FILE SECTION entries (continued)Clause To define NotesBLOCK CONTAINS Size of physical records If the CHARACTERS phrase is specified, sizeindicates the number of bytes in a recordregardless of the USAGE of the data items inthe record.RECORD CONTAINSnRECORD ISVARYINGRECORD CONTAINSn TO mSize of logical records(fixed length)Size of logical records(variable length)Size of logical records(variable length)QSAM: If provided, must matchin<strong>for</strong>mation on JCL or data-set label. Ifspecified as BLOCK CONTAINS 0, ornotprovided, the system determines theoptimal block size <strong>for</strong> you.Line sequential: Can be specified to controlbuffering <strong>for</strong> WRITE statements.VSAM: Syntax-checked, but has no effect onexecution.Integer size indicates the number of bytesin a record regardless of the USAGE of thedata items in the record. If the clause isprovided, it must match in<strong>for</strong>mation on JCLor data-set label. If n is equal to 0, LRECLmust be coded on JCL or data-set label.Integer size or sizes, if specified, indicatethe number of bytes in a record regardlessof the USAGE of the data items in the record.If the clause is provided, it must matchin<strong>for</strong>mation on JCL or data-set label;compiler checks that record descriptionsmatch.The integer sizes indicate the number ofbytes in a record regardless of the USAGE ofthe data items in the record. If the clause isprovided, it must match in<strong>for</strong>mation on JCLor data-set label; compiler checks thatrecord descriptions match.LABEL RECORDS Labels <strong>for</strong> QSAM files VSAM: Handled as commentsSTANDARD Labels exist QSAM: Handled as commentsOMITTED Labels do not exist QSAM: Handled as commentsdata-name Labels defined by the user QSAM: Allowed <strong>for</strong> (optional) tape or diskVALUE OF An item in the labelrecords associated withfileComments onlyDATA RECORDS Names of records Comments onlyassociated with fileLINAGE Depth of logical page QSAM onlyChapter 1. Structuring your program 15


Table 2. FILE SECTION entries (continued)Clause To define NotesCODE-SET ASCII or EBCDIC files QSAM only.When an ASCII file is identified with theCODE-SET clause, the corresponding DDstatement might need to haveDCB=(OPTCD=Q. . .) or DCB=(RECFM=D. . .)coded if the file was not created using VS<strong>COBOL</strong> II, <strong>COBOL</strong> <strong>for</strong> <strong>OS</strong>/390 ® &VM,orIBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong>.RECORDING MODEPhysical recorddescriptionQSAM onlyRELATED CONCEPTS“Labels <strong>for</strong> QSAM files” on page 174RELATED REFERENCESFile section (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Comparison of WORKING-STORAGE and LOCAL-STORAGEHow data items are allocated and initialized varies depending on whether theitems are in the WORKING-STORAGE SECTION or LOCAL-STORAGE SECTION.WORKING-STORAGE <strong>for</strong> programs is allocated at the start of the run unit.Any data items that have VALUE clauses are initialized to the appropriate value atthat time. For the duration of the run unit, WORKING-STORAGE items persist in theirlast-used state. Exceptions are:v A program with INITIAL specified in the PROGRAM-ID paragraphIn this case, WORKING-STORAGE data items are reinitialized each time that theprogram is entered.v A subprogram that is dynamically called and then canceledIn this case, WORKING-STORAGE data items are reinitialized on the first reentry intothe program following the CANCEL.WORKING-STORAGE is deallocated at the termination of the run unit.See the related tasks <strong>for</strong> in<strong>for</strong>mation about WORKING-STORAGE in <strong>COBOL</strong> classdefinitions.A separate copy of LOCAL-STORAGE data is allocated <strong>for</strong> each call of a program orinvocation of a method, and is freed on return from the program or method. If youspecify a VALUE clause <strong>for</strong> a LOCAL-STORAGE item, the item is initialized to that valueon each call or invocation. If a VALUE clause is not specified, the initial value of theitem is undefined.Threading: Each invocation of a program that runs simultaneously on multiplethreads shares access to a single copy of WORKING-STORAGE data. Each invocationhas a separate copy of LOCAL-STORAGE data.“Example: storage sections” on page 1716 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Ending and reentering main programs or subprograms” on page 448Chapter 27, “Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading,” on page 493“WORKING-STORAGE SECTION <strong>for</strong> defining class instance data” on page 568RELATED REFERENCESWorking-storage section (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Local-storage section (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: storage sectionsThe following is an example of a recursive program that uses bothWORKING-STORAGE and LOCAL-STORAGE.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.Local-Storage Section.01 num pic 9(4).PROCEDURE DIVISION.move numb to num.if numb = 0move 1 to factelsesubtract 1 from numbcall 'factorial'multiply num by factend-if.display num '! = ' fact.goback.End Program factorial.The program produces the following output:0000! = 000000010001! = 000000010002! = 000000020003! = 000000060004! = 000000240005! = 00000120The following tables show the changing values of the data items in LOCAL-STORAGEand WORKING-STORAGE in the successive recursive calls of the program, and in theensuing gobacks. During the gobacks, fact progressively accumulates the value of5! (five factorial).Recursive callsValue <strong>for</strong> num inLOCAL-STORAGEValue <strong>for</strong> numb inWORKING-STORAGEValue <strong>for</strong> fact inWORKING-STORAGEMain 5 5 01 4 4 02 3 3 03 2 2 0Chapter 1. Structuring your program 17


Recursive callsValue <strong>for</strong> num inLOCAL-STORAGEValue <strong>for</strong> numb inWORKING-STORAGEValue <strong>for</strong> fact inWORKING-STORAGE4 1 1 05 0 0 0GobacksValue <strong>for</strong> num inLOCAL-STORAGEValue <strong>for</strong> numb inWORKING-STORAGEValue <strong>for</strong> fact inWORKING-STORAGE5 0 0 14 1 0 13 2 0 22 3 0 61 4 0 24Main 5 0 120RELATED CONCEPTS“Comparison of WORKING-STORAGE and LOCAL-STORAGE” on page 16Using data from another programHow you share data depends on the type of program. You share data differently inprograms that are separately compiled than you do <strong>for</strong> programs that are nested or<strong>for</strong> programs that are recursive or multithreaded.RELATED TASKS“Sharing data in separately compiled programs”“Sharing data in nested programs”“Sharing data in recursive or multithreaded programs” on page 19“Passing data” on page 465Sharing data in separately compiled programsMany applications consist of separately compiled programs that call and pass datato one another. Use the LINKAGE SECTION in the called program to describe the datapassed from another program.In the calling program, use a CALL . . . USING or INVOKE . . . USING statementto pass the data.RELATED TASKS“Passing data” on page 465Sharing data in nested programsSome applications consist of nested programs, that is, programs that are containedin other programs. Level-01 data items can include the GLOBAL attribute. Thisattribute allows any nested program that includes the declarations to access thesedata items.18 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


A nested program can also access data items in a sibling program (one at the samenesting level in the same containing program) that is declared with the COMMONattribute.RELATED CONCEPTS“Nested programs” on page 458Sharing data in recursive or multithreaded programsIf your program has the RECURSIVE attribute or is compiled with the THREADcompiler option, data that is defined in the LINKAGE SECTION is not accessible onsubsequent invocations of the program.To address a record in the LINKAGE SECTION, use either of these techniques:v Pass an argument to the program and specify the record in an appropriateposition in the USING phrase in the program.v Use the <strong>for</strong>mat-5 SET statement.If your program has the RECURSIVE attribute or is compiled with the THREADcompiler option, the address of the record is valid <strong>for</strong> a particular instance of theprogram invocation. The address of the record in another execution instance of thesame program must be reestablished <strong>for</strong> that execution instance. Unpredictableresults will occur if you refer to a data item <strong>for</strong> which the address has not beenestablished.RELATED CONCEPTS“Multithreading” on page 494RELATED TASKS“Making recursive calls” on page 461“Processing files with multithreading” on page 496Processing the dataRELATED REFERENCES“THREAD” on page 352SET statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)In the PROCEDURE DIVISION of a program, you code the executable statements thatprocess the data that you defined in the other divisions. The PROCEDURE DIVISIONcontains one or two headers and the logic of your program.The PROCEDURE DIVISION begins with the division header and a procedure-nameheader. The division header <strong>for</strong> a program can simply be: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 <strong>for</strong> a program in either of these ways:PROCEDURE DIVISION USING datanamePROCEDURE DIVISION USING BY REFERENCE datanameBe sure to define dataname in the LINKAGE SECTION of the DATA DIVISION.Chapter 1. Structuring your program 19


To receive a parameter that was passed by value, code the division header <strong>for</strong> aprogram as follows:PROCEDURE DIVISION USING BY VALUE datanameTo return a value as a result, code the division header as follows:PROCEDURE DIVISION RETURNING dataname2You can also combine USING and RETURNING in a PROCEDURE DIVISION header:PROCEDURE DIVISION USING dataname RETURNING dataname2Be sure to define dataname and dataname2 in the LINKAGE SECTION.RELATED CONCEPTS“How logic is divided in the PROCEDURE DIVISION”RELATED TASKS“Eliminating repetitive coding” on page 679RELATED REFERENCESThe procedure division header (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The USING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)How logic is divided in the PROCEDURE DIVISIONThe PROCEDURE DIVISION of a program is divided into sections and paragraphs,which contain sentences, statements, and phrases.SectionLogical subdivision of your processing logic.A section has a section header and is optionally followed by one or moreparagraphs.A section can be the subject of a PERFORM statement. One type of section is<strong>for</strong> declaratives.ParagraphSubdivision of a section, procedure, or program.A paragraph has a name followed by a period and zero or more sentences.A paragraph can be the subject of a statement.SentenceSeries of one or more <strong>COBOL</strong> statements that ends with a period.StatementPer<strong>for</strong>ms a defined step of <strong>COBOL</strong> processing, such as adding twonumbers.A statement is a valid combination of words, and begins with a <strong>COBOL</strong>verb. Statements are imperative (indicating unconditional action),conditional, or compiler-directing. Using explicit scope terminators insteadof periods to show the logical end of a statement is preferred.PhraseA subdivision of a statement.RELATED CONCEPTS“Compiler-directing statements” on page 2220 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Scope terminators” on page 22“Imperative statements”“Conditional statements”“Declaratives” on page 23RELATED REFERENCESPROCEDURE DIVISION structure (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Imperative statementsAn imperative statement (such as ADD, MOVE, INVOKE, orCL<strong>OS</strong>E) indicates anunconditional 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 animperative statement called a delimited scope statement. Only imperative statements(or delimited scope statements) can be nested.RELATED CONCEPTS“Conditional statements”“Scope terminators” on page 22Conditional statementsA conditional statement is either a simple conditional statement (IF, EVALUATE,SEARCH) or a conditional statement made up of an imperative statement thatincludes 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 scopestatement (which is an imperative statement).You can use a delimited scope statement in these ways:v To delimit the range of operation <strong>for</strong> a <strong>COBOL</strong> conditional statement and toexplicitly show the levels of nestingFor example, use an END-IF phrase instead of a period to end the scope of an IFstatement within a nested IF.v To code a conditional statement where the <strong>COBOL</strong> syntax calls <strong>for</strong> an imperativestatementFor example, code a conditional statement as the object of an inline PERFORM:PERFORM UNTIL TRANSACTION-EOFPERFORM 200-EDIT-UPDATE-TRANSACTIONIF NO-ERRORSPERFORM 300-UPDATE-COMMUTER-RECORDELSEPERFORM 400-PRINT-TRANSACTION-ERRORSEND-IFREAD UPDATE-TRANSACTION-FILE INTO WS-TRANSACTION-RECORDAT ENDSET TRANSACTION-EOF TO TRUEEND-READEND-PERFORMAn explicit scope terminator is required <strong>for</strong> the inline PERFORM statement, but it isnot valid <strong>for</strong> the out-of-line PERFORM statement.For additional program control, you can use the NOT phrase with conditionalstatements. For example, you can provide instructions to be per<strong>for</strong>med when aChapter 1. Structuring your program 21


particular exception does not occur, such as NOT ON SIZE ERROR. The NOT phrasecannot be used with the ON OVERFLOW phrase of the CALL statement, but it can beused with the ON EXCEPTION phrase.Do not nest conditional statements. Nested statements must be imperativestatements (or delimited scope statements) and must follow the rules <strong>for</strong>imperative statements.The following statements are examples of conditional statements if they are codedwithout scope terminators:v Arithmetic statement with ON SIZE ERRORv Data-manipulation statements with ON OVERFLOWv CALL statements with ON OVERFLOWv I/O statements with INVALID KEY, AT END, orAT END-OF-PAGEv RETURN with AT ENDRELATED CONCEPTS“Imperative statements” on page 21“Scope terminators”RELATED TASKS“Selecting program actions” on page 89RELATED REFERENCESConditional statements (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Compiler-directing statementsA compiler-directing statement causes the compiler to take specific action about theprogram structure, COPY processing, listing control, or control flow.A compiler-directing statement is not part of the program logic.RELATED REFERENCESChapter 18, “Compiler-directing statements,” on page 363Compiler-directing statements (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Scope terminatorsA scope terminator ends a verb or statement. Scope terminators can be explicit orimplicit.Explicit scope terminators end a verb without ending a sentence. They consist ofEND followed by a hyphen and the name of the verb being terminated, such asEND-IF. An implicit scope terminator is a period (.) that ends the scope of allprevious statements not yet ended.Each of the two periods in the following program fragment ends an IF statement,making the code equivalent to the code after it that instead uses explicit scopeterminators:IF ITEM = "A"DISPLAY "THE VALUE OF ITEM IS " ITEMADD 1 TO TOTALMOVE "C" TO ITEMDISPLAY "THE VALUE OF ITEM IS NOW " ITEM.IF ITEM = "B"ADD 2 TO TOTAL.22 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


IF ITEM = "A"DISPLAY "THE VALUE OF ITEM IS " ITEMADD 1 TO TOTALMOVE "C" TO ITEMDISPLAY "THE VALUE OF ITEM IS NOW " ITEMEND-IFIF ITEM = "B"ADD 2 TO TOTALEND-IFIf you use implicit terminators, the end of statements can be unclear. As a result,you might end statements unintentionally, changing your program’s logic. Explicitscope terminators make a program easier to understand and prevent unintentionalending of statements. For example, in the program fragment below, changing thelocation of the first period in the first implicit scope example changes the meaningof the code:IF ITEM = "A"DISPLAY "VALUE OF ITEM IS " ITEMADD 1 TO TOTAL.MOVE "C" TO ITEMDISPLAY " VALUE OF ITEM IS NOW " ITEMIF ITEM = "B"ADD 2 TO TOTAL.The MOVE statement and the DISPLAY statement after it are per<strong>for</strong>med regardless ofthe value of ITEM, despite what the indentation indicates, because the first periodterminates the IF statement.For improved program clarity and to avoid unintentional ending of statements, useexplicit scope terminators, especially within paragraphs. Use implicit scopeterminators only at the end of a paragraph or the end of a program.Be careful when coding an explicit scope terminator <strong>for</strong> an imperative statementthat is nested within a conditional statement. Ensure that the scope terminator ispaired with the statement <strong>for</strong> which it was intended. In the following example, thescope terminator will be paired with the second READ statement, though theprogrammer intended it to be paired with the first.READ FILE1AT ENDMOVEATOBREAD FILE2END-READTo ensure that the explicit scope terminator is paired with the intended statement,the preceding example can be recoded in this way:READ FILE1AT ENDMOVEATOBREAD FILE2END-READEND-READRELATED CONCEPTS“Conditional statements” on page 21“Imperative statements” on page 21DeclarativesDeclaratives provide one or more special-purpose sections that are executed whenan exception condition occurs.Chapter 1. Structuring your program 23


Start each declarative section with a USE statement that identifies the function ofthe section. In the procedures, specify the actions to be taken when the conditionoccurs.RELATED TASKS“Finding and handling input-output errors” on page 369RELATED REFERENCESDeclaratives (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)24 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 2. Using dataThis in<strong>for</strong>mation is intended to help non-<strong>COBOL</strong> programmers relate terms <strong>for</strong>data used in other programming languages to <strong>COBOL</strong> terms. It introduces <strong>COBOL</strong>fundamentals <strong>for</strong> variables, structures, literals, and constants; assigning anddisplaying values; intrinsic (built-in) functions, and tables (arrays) and pointers.RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Using variables, structures, literals, and constants”“Assigning values to data items” on page 29“Displaying values on a screen or in a file (DISPLAY)” on page 38“Using intrinsic functions (built-in functions)” on page 40“Using tables (arrays) and pointers” on page 41Chapter 7, “Processing data in an international environment,” on page 121Using variables, structures, literals, and constantsMost high-level programming languages share the concept of data beingrepresented as variables, structures (group items), literals, or constants.The data in a <strong>COBOL</strong> program can be alphabetic, alphanumeric, double-bytecharacter set (DBCS), national, or numeric. You can also define index-names anddata items described as USAGE POINTER, USAGE FUNCTION-POINTER, USAGEPROCEDURE-POINTER, orUSAGE OBJECT REFERENCE. You place all data definitions inthe DATA DIVISION of your program.RELATED TASKS“Using variables”“Using data items and group items” on page 26“Using literals” on page 27“Using constants” on page 28“Using figurative constants” on page 28RELATED REFERENCESClasses and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using variablesA variable is a data item whose value can change during a program. The value isrestricted, however, to the data type that you define when you specify a name anda length <strong>for</strong> 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).© Copyright IBM Corp. 1991, 2009 25


...Procedure Division.Move Customer-Name to Original-Customer-Name...You could instead declare the customer names above as national data items byspecifying their PICTURE clauses as Pic N(20) and specifying the USAGE NATIONALclause <strong>for</strong> the items. National data items are represented in Unicode UTF-16, inwhich most characters are represented in 2 bytes of storage.RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED TASKS“Using national data (Unicode) in <strong>COBOL</strong>” on page 126RELATED REFERENCES“NSYMBOL” on page 331“Storage of character data” on page 133PICTURE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using data items and group itemsRelated data items can be parts of a hierarchical data structure. A data item thatdoes not have subordinate data items is called an elementary item. A data item thatis composed of one or more subordinate data items is called a group item.A record can be either an elementary item or a group item. A group item can beeither an alphanumeric group item or a national group item.For example, Customer-Record below is an alphanumeric group item that iscomposed of two subordinate alphanumeric group items (Customer-Name andPart-Order), each of which contains elementary data items. These groups itemsimplicitly have USAGE DISPLAY. You can refer to an entire group item or to parts ofa group item in MOVE statements in the PROCEDURE DIVISION as shown below:Data Division.File Section.FDCustomer-FileRecord 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-NameMove Part-Name to Inventory-Part-Name...You could instead define Customer-Record as a national group item that iscomposed of two subordinate national group items by changing the declarations in26 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


the DATA DIVISION as shown below. National group items behave in the same wayas elementary category national data items in most operations. The GROUP-USAGENATIONAL clause indicates that a group item and any group items subordinate to itare national groups. Subordinate elementary items in a national group must beexplicitly or implicitly described as USAGE NATIONAL.Data Division.File Section.FDCustomer-FileRecord Contains 90 Characters.01 Customer-Record Group-Usage National.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-NameMove Part-Name to Inventory-Part-Name...In the example above, the group items could instead specify the USAGE NATIONALclause at the group level. A USAGE clause at the group level applies to eachelementary data item in a group (and thus serves as a convenient shorthandnotation). However, a group that specifies the USAGE NATIONAL clause is not anational group despite the representation of the elementary items within the group.Groups that specify the USAGE clause are alphanumeric groups and behave in manyoperations, such as moves and compares, like elementary data items of USAGEDISPLAY (except that no editing or conversion of data occurs).RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125“National groups” on page 129RELATED TASKS“Using national data (Unicode) in <strong>COBOL</strong>” on page 126“Using national groups” on page 130RELATED REFERENCES“FILE SECTION entries” on page 14“Storage of character data” on page 133Classes and categories of group items (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)PICTURE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MOVE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)USAGE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using literalsA literal is a character string whose value is given by the characters themselves. Ifyou know the value you want a data item to have, you can use a literalrepresentation of the data value in the PROCEDURE DIVISION.Chapter 2. Using data 27


You do not need to declare a data item <strong>for</strong> the value nor refer to it by using adata-name. For example, you can prepare an error message <strong>for</strong> an output file bymoving an alphanumeric literal:Move "Name is not valid" To Customer-NameYou 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 isa numeric literal:01 Part-number Pic 9(5)....If Part-number = 03519 then display "Part number was found"You can use the opening delimiter N" or N' to designate a national literal if theNSYMBOL(NATIONAL) compiler option is in effect, or to designate a DBCS literal if theNSYMBOL(DBCS) compiler option is in effect.You can use the opening delimiter NX" or NX' to designate national literals inhexadecimal notation (regardless of the setting of the NSYMBOL compiler option).Each group of four hexadecimal digits designates a single national character.RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED TASKS“Using national literals” on page 127“Using DBCS literals” on page 142RELATED REFERENCES“NSYMBOL” on page 331Literals (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using constantsA constant is a data item that has only one value. <strong>COBOL</strong> does not define aconstruct <strong>for</strong> constants. However, you can define a data item with an initial valueby coding a VALUE clause in the data description (instead of coding an INITIALIZEstatement).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 canlikewise use a VALUE clause in defining a national or DBCS constant.RELATED TASKS“Using national data (Unicode) in <strong>COBOL</strong>” on page 126“Coding <strong>for</strong> use of DBCS support” on page 141Using figurative constantsCertain commonly used constants and literals are available as reserved wordscalled figurative constants: ZERO, SPACE, HIGH-VALUE, LOW-VALUE, QUOTE, NULL, and ALLliteral. Because they represent fixed values, figurative constants do not require adata definition.28 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


For example:Move Spaces To Report-HeaderRELATED TASKS“Using national-character figurative constants” on page 128“Coding <strong>for</strong> use of DBCS support” on page 141RELATED REFERENCESFigurative constants (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Assigning values to data itemsAfter you have defined a data item, you can assign a value to it at any time.Assignment takes many <strong>for</strong>ms in <strong>COBOL</strong>, depending on what you want to do.Table 3. Assignment to data items in a programWhat you want to doAssign values to a data item or large data area.Assign the results of arithmetic.Examine or replace characters or groups of characters in a dataitem.Receive values from a file.Receive values from a system input device or a file.Establish a constant.One of these actions:v Place a value associated with a table element in an index.v Set the status of an external switch to ON or OFF.v Move data to a condition-name to make the condition true.v Set a POINTER, PROCEDURE-POINTER, orFUNCTION-POINTER dataitem to an address.v Associate an OBJECT REFERENCE data item with an objectinstance.How to do itUse one of these ways:v INITIALIZE statementv MOVE statementv STRING or UNSTRING statementv VALUE clause (to set data items to the values youwant them to have when the program is ininitial state)Use COMPUTE, ADD, SUBTRACT, MULTIPLY, orDIVIDEstatements.Use the INSPECT statement.Use the READ (or READ INTO) statement.Use the ACCEPT statement.Use the VALUE clause in the definition of the dataitem, and do not use the data item as a receiver.Such an item is in effect a constant even though thecompiler does not en<strong>for</strong>ce read-only constants.Use the SET statement.“Examples: initializing data items” on page 30RELATED TASKS“Initializing a structure (INITIALIZE)” on page 32“Assigning values to elementary data items (MOVE)” on page 34“Assigning values to group data items (MOVE)” on page 35“Assigning input from a screen or file (ACCEPT)” on page 37“Joining data items (STRING)” on page 101Chapter 2. Using data 29


“Splitting data items (UNSTRING)” on page 103“Assigning arithmetic results (MOVE or COMPUTE)” on page 36“Tallying and replacing data items (INSPECT)” on page 111Chapter 7, “Processing data in an international environment,” on page 121Examples: initializing data itemsThe following examples show how you can initialize many kinds of data items,including alphanumeric, national-edited, and numeric-edited data items, by usingINITIALIZE statements.An INITIALIZE statement is functionally equivalent to one or more MOVE statements.The related tasks about initializing show how you can use an INITIALIZE statementon a group item to conveniently initialize all the subordinate data items that are ina given data category.Initializing a data item to blanks or zeros:INITIALIZE identifier-1identifier-1 PICTURE identifier-1 be<strong>for</strong>e identifier-1 after9(5) 12345 00000X(5) AB123 bbbbb 1N(3) 004100420031 2 002000200020 399XX9 12AB3 bbbbb 1XXBX/XX ABbC/DE bbbb/bb 1**99.9CR 1234.5CR **00.0bb 1A(5) ABCDE bbbbb 1+99.99E+99 +12.34E+02 +00.00E+001. The symbol b represents a blank space.2. Hexadecimal representation of the national (UTF-16) characters ’AB1’. The exampleassumes that identifier-1 has Usage National.3. Hexadecimal representation of the national (UTF-16) characters ’ ’ (three blankspaces). Note that if identifier-1 were not defined as Usage National, and ifNSYMBOL(DBCS) were in effect, INITIALIZE would instead store DBCS spaces (’4040’) intoidentifier-1.Initializing an alphanumeric data item:01 ALPHANUMERIC-1 PIC X VALUE "y".01 ALPHANUMERIC-3 PIC X(1) VALUE "A"....INITIALIZE ALPHANUMERIC-1REPLACING ALPHANUMERIC DATA BY ALPHANUMERIC-3ALPHANUMERIC-3 ALPHANUMERIC-1 be<strong>for</strong>e ALPHANUMERIC-1 afterA y AInitializing an alphanumeric right-justified data item:01 ANJUST PIC X(8) VALUE SPACES JUSTIFIED RIGHT.01 ALPHABETIC-1 PIC A(4) VALUE "ABCD"....INITIALIZE ANJUSTREPLACING ALPHANUMERIC DATA BY ALPHABETIC-130 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


ALPHABETIC-1 ANJUST be<strong>for</strong>e ANJUST afterABCD bbbbbbbb 1 bbbbABCD 11. The symbol b represents a blank space.Initializing an alphanumeric-edited data item:01 ALPHANUM-EDIT-1 PIC XXBX/XXX VALUE "ABbC/DEF".01 ALPHANUM-EDIT-3 PIC X/BB VALUE "M/bb"....INITIALIZE ALPHANUM-EDIT-1REPLACING ALPHANUMERIC-EDITED DATA BY ALPHANUM-EDIT-3ALPHANUM-EDIT-3 ALPHANUM-EDIT-1 be<strong>for</strong>e ALPHANUM-EDIT-1 afterM/bb 1 ABbC/DEF 1 M/bb/bbb 11. The symbol b represents a blank space.Initializing a national data item:01 NATIONAL-1 PIC NN USAGE NATIONAL VALUE N"AB".01 NATIONAL-3 PIC NN USAGE NATIONAL VALUE N"CD"....INITIALIZE NATIONAL-1REPLACING NATIONAL DATA BY NATIONAL-3NATIONAL-3 NATIONAL-1 be<strong>for</strong>e NATIONAL-1 after00430044 1 00410042 2 00430044 11. Hexadecimal representation of the national characters ’CD’2. Hexadecimal representation of the national characters ’AB’Initializing a national-edited data item:01 NATL-EDIT-1 PIC 0NN USAGE NATIONAL VALUE N"123".01 NATL-3 PIC NNN USAGE NATIONAL VALUE N"456"....INITIALIZE NATL-EDIT-1REPLACING NATIONAL-EDITED DATA BY NATL-3NATL-3 NATL-EDIT-1 be<strong>for</strong>e NATL-EDIT-1 after003400350036 1 003100320033 2 003000340035 31. Hexadecimal representation of the national characters ’456’2. Hexadecimal representation of the national characters ’123’3. Hexadecimal representation of the national characters ’045’Initializing a numeric (zoned decimal) data item:01 NUMERIC-1 PIC 9(8) VALUE 98765432.01 NUM-INT-CMPT-3 PIC 9(7) COMP VALUE 1234567....INITIALIZE NUMERIC-1REPLACING NUMERIC DATA BY NUM-INT-CMPT-3NUM-INT-CMPT-3 NUMERIC-1 be<strong>for</strong>e NUMERIC-1 after1234567 98765432 01234567Chapter 2. Using data 31


Initializing a numeric (national decimal) data item:01 NAT-DEC-1 PIC 9(3) USAGE NATIONAL VALUE 987.01 NUM-INT-BIN-3 PIC 9(2) BINARY VALUE 12....INITIALIZE NAT-DEC-1REPLACING NUMERIC DATA BY NUM-INT-BIN-3NUM-INT-BIN-3 NAT-DEC-1 be<strong>for</strong>e NAT-DEC-1 after12 003900380037 1 003000310032 21. Hexadecimal representation of the national characters ’987’2. Hexadecimal representation of the national characters ’012’Initializing a numeric-edited (USAGE DISPLAY) data item:01 NUM-EDIT-DISP-1 PIC $ZZ9V VALUE "$127".01 NUM-DISP-3 PIC 999V VALUE 12....INITIALIZE NUM-EDIT-DISP-1REPLACING NUMERIC DATA BY NUM-DISP-3NUM-DISP-3 NUM-EDIT-DISP-1 be<strong>for</strong>e NUM-EDIT-DISP-1 after012 $127 $ 12Initializing a numeric-edited (USAGE NATIONAL) data item:01 NUM-EDIT-NATL-1 PIC $ZZ9V NATIONAL VALUE N"$127".01 NUM-NATL-3 PIC 999V NATIONAL VALUE 12....INITIALIZE NUM-EDIT-NATL-1REPLACING NUMERIC DATA BY NUM-NATL-3NUM-NATL-3 NUM-EDIT-NATL-1 be<strong>for</strong>e NUM-EDIT-NATL-1 after003000310032 1 0024003100320037 2 0024002000310032 31. Hexadecimal representation of the national characters ’012’2. Hexadecimal representation of the national characters ’$127’3. Hexadecimal representation of the national characters ’$ 12’RELATED TASKS“Initializing a structure (INITIALIZE)”“Initializing a table (INITIALIZE)” on page 76“Defining numeric data” on page 45RELATED REFERENCES“NSYMBOL” on page 331Initializing a structure (INITIALIZE)You can reset the values of all subordinate data items in a group item by applyingthe INITIALIZE statement to that group item. However, it is inefficient to initializean entire group unless you really need all the items in the group to be initialized.The following example shows how you can reset fields to spaces and zeros intransaction records that a program produces. The values of the fields are not32 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


identical in each record that is produced. (The transaction record is defined as analphanumeric group item, TRANSACTION-OUT.)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-OUTRecord TRANSACTION-OUT be<strong>for</strong>e TRANSACTION-OUT after1 R001383000240000000000000000 b000000000000000000000000000 12 R001390000480000000000000000 b000000000000000000000000000 13 S001410000120000000000000000 b000000000000000000000000000 14 C001383000000000425000000000 b000000000000000000000000000 15 C002010000000000000100000000 b000000000000000000000000000 11. The symbol b represents a blank space.You can likewise reset the values of all the subordinate data items in a nationalgroup item by applying the INITIALIZE statement to that group item. Thefollowing structure is similar to the preceding structure, but instead uses UnicodeUTF-16 data:01 TRANSACTION-OUT GROUP-USAGE NATIONAL.05 TRANSACTION-CODE PIC N.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-OUTRegardless of the previous contents of the transaction record, after the INITIALIZEstatement above is executed:v TRANSACTION-CODE contains NX"0020" (a national space).vEach of the remaining 27 national character positions of TRANSACTION-OUTcontains NX"0030" (a national-decimal zero).When you use an INITIALIZE statement to initialize an alphanumeric or nationalgroup data item, the data item is processed as a group item, that is, with groupsemantics. The elementary data items within the group are recognized andprocessed, as shown in the examples above. If you do not code the REPLACINGphrase of the INITIALIZE statement:vvSPACE is the implied sending item <strong>for</strong> alphabetic, alphanumeric,alphanumeric-edited, DBCS, category national, and national-edited receivingitems.ZERO is the implied sending item <strong>for</strong> numeric and numeric-edited receivingitems.RELATED CONCEPTS“National groups” on page 129Chapter 2. Using data 33


RELATED TASKS“Initializing a table (INITIALIZE)” on page 76“Using national groups” on page 130RELATED REFERENCESINITIALIZE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Assigning values to elementary data items (MOVE)Use a MOVE statement to assign a value to an elementary data item.The following statement assigns the contents of an elementary data item,Customer-Name, to the elementary data item Orig-Customer-Name:Move Customer-Name to Orig-Customer-NameIf Customer-Name is longer than Orig-Customer-Name, truncation occurs on the right.If Customer-Name is shorter, the extra character positions on the right inOrig-Customer-Name are filled with spaces.For data items that contain numbers, moves can be more complicated than withcharacter data items because there are several ways in which numbers can berepresented. In general, the algebraic values of numbers are moved if possible, asopposed to the digit-by-digit moves that are per<strong>for</strong>med with character data. Forexample, after the MOVE statement below, Item-x contains the value 3.0, representedas 0030:01 Item-x Pic 999v9....Move 3.06 to Item-xYou can move an alphabetic, alphanumeric, alphanumeric-edited, DBCS, integer, ornumeric-edited data item to a category national or national-edited data item; thesending item is converted. You can move a national data item to a categorynational or national-edited data item. If the content of a category national dataitem 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 anational-edited data item only to a category national data item or anothernational-edited data item. Padding or truncation might occur.For complete details about elementary moves, see the related reference belowabout the MOVE statement.The following example shows an alphanumeric data item in the Greek languagethat 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-GreekMove Data-in-Greek to Data-in-UnicodeRELATED CONCEPTS“Unicode and the encoding of language characters” on page 12534 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Assigning values to group data items (MOVE)”“Converting to or from national (Unicode) representation” on page 134RELATED REFERENCES“CODEPAGE” on page 310Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MOVE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Assigning values to group data items (MOVE)Use the MOVE statement to assign values to group data items.You can move a national group item (a data item that is described with theGROUP-USAGE NATIONAL clause) to another national group item. The compilerprocesses the move as though each national group item were an elementary itemof category national, that is, as if each item were described as PIC N(m), where mis the length of that item in national character positions.You can move an alphanumeric group item to an alphanumeric group item or to anational group item. You can also move a national group item to an alphanumericgroup item. The compiler per<strong>for</strong>ms such moves as group moves, that is, withoutconsideration of the individual elementary items in the sending or receiving group,and without conversion of the sending data item. Be sure that the subordinate datadescriptions in the sending and receiving group items are compatible. The movesoccur even if a destructive overlap could occur at run time.You can code the CORRESPONDING phrase in a MOVE statement to move subordinateelementary items from one group item to the identically named correspondingsubordinate 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-NIn the example above, State and Month within Group-N receive the values innational representation of State and Month, respectively, from Group-X. The otherdata items in Group-N are unchanged. (Filler items in a receiving group item areunchanged by a MOVE CORRESPONDING statement.)In a MOVE CORRESPONDING statement, sending and receiving group items are treatedas group items, not as elementary data items; group semantics apply. That is, theelementary data items within each group are recognized, and the results are thesame as if each pair of corresponding data items were referenced in a separateMOVE statement. Data conversions are per<strong>for</strong>med according to the rules <strong>for</strong> the MOVEstatement as specified in the related reference below. For details about which typesof elementary data items correspond, see the related reference about theCORRESPONDING phrase.Chapter 2. Using data 35


RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125“National groups” on page 129RELATED TASKS“Assigning values to elementary data items (MOVE)” on page 34“Using national groups” on page 130“Converting to or from national (Unicode) representation” on page 134RELATED REFERENCESClasses and categories of group items (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MOVE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CORRESPONDING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Assigning arithmetic results (MOVE or COMPUTE)When assigning a number to a data item, consider using the COMPUTE statementinstead of the MOVE statement.MovewtozCompute z=wIn the example above, the two statements in most cases have the same effect. TheMOVE statement however carries out the assignment with truncation. You can usethe DIAGTRUNC compiler option to request that the compiler issue a warning <strong>for</strong>MOVE statements that might truncate numeric receivers.When significant left-order digits would be lost in execution, the COMPUTE statementcan detect the condition and allow you to handle it. If you use the ON SIZE ERRORphrase of the COMPUTE statement, the compiler generates code to detect asize-overflow condition. If the condition occurs, the code in the ON SIZE ERRORphrase is per<strong>for</strong>med, and the content of z remains unchanged. If you do notspecify the ON SIZE ERROR phrase, the assignment is carried out with truncation.There is no ON SIZE ERROR support <strong>for</strong> the MOVE statement.You can also use the COMPUTE statement to assign the result of an arithmeticexpression 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 todata items by using Language Environment callable services. LanguageEnvironment services are available through a standard <strong>COBOL</strong> CALL statement, andthe values they return are passed in the parameters of the CALL statement. Forexample, you can call the Language Environment service CEESIABS to find theabsolute value of a data item by coding the following statement:Call 'CEESIABS' Using Arg, Feedback-code, Result.As a result of this call, data item Result is assigned the absolute value of the valuein data item Arg; data item Feedback-code contains the return code that indicateswhether the service completed successfully. You have to define all the data items inthe DATA DIVISION using the correct descriptions according to the requirements ofthe particular callable service. For the example above, the data items could bedefined as follows:77 Arg Pic s9(9) Binary.77 Feedback-code Pic x(12) Display.77 Result Pic s9(9) Binary.36 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED REFERENCES“DIAGTRUNC” on page 318Intrinsic functions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Language Environment <strong>Programming</strong> Reference (Callable services)Assigning input from a screen or file (ACCEPT)One way to assign a value to a data item is to read the value from a screen or afile.To enter data from the screen, first associate the monitor with a mnemonic-name inthe SPECIAL-NAMES paragraph. Then use ACCEPT to assign the line of input enteredat the screen to a data item. For example:Environment Division.Configuration Section.Special-Names.Console is Names-Input....Accept Customer-Name From Names-InputTo read from a file instead of the screen, make the following change:v Change Console to device, where device is any valid system device (<strong>for</strong> example,SYSIN). For example:SYSIN is Names-Inputdevice can be a ddname that references a hierarchical file system (HFS) path. Ifthis ddname is not defined and your program is running in the z/<strong>OS</strong> UNIXenvironment, stdin is the input source. If this ddname is not defined and yourprogram is not running in the z/<strong>OS</strong> UNIX environment, the ACCEPT statementfails.When you use the ACCEPT statement, you can assign a value to an alphanumeric ornational group item, or to an elementary data item that has USAGE DISPLAY, USAGEDISPLAY-1, orUSAGE NATIONAL.When you assign a value to a USAGE NATIONAL data item, input data from theconsole is converted from the EBCDIC code page specified in the CODEPAGEcompiler option to national (Unicode UTF-16) representation. This is the only casewhere 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 ascreen.To have conversion done when the input data is from any other device, use theNATIONAL-OF intrinsic function.RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED TASKS“Converting alphanumeric or DBCS to national (NATIONAL-OF)” on page 135RELATED REFERENCES“CODEPAGE” on page 310ACCEPT statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SPECIAL-NAMES paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 2. Using data 37


Displaying values on a screen or in a file (DISPLAY)You can display the value of a data item on a screen or write it to a file by usingthe DISPLAY statement.Display "No entry <strong>for</strong> surname '" Customer-Name "' found in the file.".In the example above, if the content of data item Customer-Name is JOHNSON,then the statement displays the following message on the system logical outputdevice:No entry <strong>for</strong> surname 'JOHNSON' found in the file.To write data to a destination other than the system logical output device, use theUPON phrase with a destination other than SYSOUT. For example, the followingstatement writes to the file specified in the SYSPUNCH DD statement:Display "Hello" upon syspunch.You can specify a file in the HFS 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=TEXTThe following statement writes to the job log or console and to the TSO screen ifyou are running under TSO:Display "Hello" upon console.When you display the value of a USAGE NATIONAL data item to the console, it isconverted from Unicode (UTF-16) representation to EBCDIC based on the value ofthe CODEPAGE option. This is the only case where conversion of national data isdone when you use the DISPLAY statement. Conversion is done in this case becausethe output is known to be directed to a screen.To have a national data item be converted when you direct output to a differentdevice, use the DISPLAY-OF intrinsic function, such as in the following example:01 Data-in-Unicode pic N(10) usage national....Display function Display-of(Data-in-Unicode, 00037)RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED TASKS“Displaying data on the system logical output device” on page 39“Using WITH NO ADVANCING” on page 39“Converting national to alphanumeric (DISPLAY-OF)” on page 136“Coding <strong>COBOL</strong> programs to run under CICS” on page 407RELATED REFERENCES“CODEPAGE” on page 310DISPLAY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)38 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Displaying data on the system logical output deviceTo write data to the system logical output device, either omit the UPON clause oruse the UPON clause with destination SYSOUT.Display "Hello" upon sysout.The output is directed to the ddname that you specify in the OUTDD compileroption. You can specify a file in the hierarchical file system with this ddname.If the OUTDD ddname is not allocated and you are not running in the z/<strong>OS</strong> UNIXenvironment, a default DD of SYSOUT=* is allocated. If the OUTDD ddname is notallocated and you are running in the z/<strong>OS</strong> UNIX environment, the _IGZ_SYSOUTenvironment variable is used as follows:Undefined or set to stdoutOutput is routed to stdout (file descriptor 1).Set to stderrOutput 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 conditionis raised.When DISPLAY output is routed to stdout or stderr, the output is not subdividedinto records. The output is written as a single stream of characters without linebreaks.If OUTDD and the Language Environment runtime option MSGFILE specify the sameddname, both DISPLAY output and Language Environment runtime diagnostics arerouted to the Language Environment message file.RELATED TASKS“Setting and accessing environment variables” on page 438RELATED REFERENCES“OUTDD” on page 337DISPLAY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using WITH NO ADVANCINGIf you specify the WITH NO ADVANCING phrase, and output is going to a ddname, theprinter control character + (plus) is placed into the first output position from thenext DISPLAY statement. + is the ANSI-defined printer control character thatsuppresses line spacing be<strong>for</strong>e a record is printed.If you specify the WITH NO ADVANCING phrase and the output is going to stdout orstderr, a newline character is not appended to the end of the stream. A subsequentDISPLAY statement might add additional characters to the end of the stream.If you do not specify WITH NO ADVANCING, and the output is going to a ddname, theprinter control character ’ ’ (space) is placed into the first output position from thenext DISPLAY statement, indicating single-spaced output.Chapter 2. Using data 39


DISPLAY "ABC"DISPLAY "CDEF" WITH NO ADVANCINGDISPLAY "GHIJK" WITH NO ADVANCINGDISPLAY "LMNOPQ"DISPLAY "RSTUVWX"If you code the statements above, the result sent to the output device is:ABCCDEF+GHIJK+LMNOPQRSTUVMXThe output that is printed depends on how the output device interprets printercontrol characters.If you do not specify the WITH NO ADVANCING phrase and the output is going tostdout or stderr, a newline character is appended to the end of the stream.RELATED REFERENCESDISPLAY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using intrinsic functions (built-in functions)Some high-level programming languages have built-in functions that you canreference in your program as if they were variables that have defined attributesand a predetermined value. In <strong>COBOL</strong>, these functions are called intrinsic functions.They provide capabilities <strong>for</strong> manipulating strings and numbers.Because the value of an intrinsic function is derived automatically at the time ofreference, you do not need to define functions in the DATA DIVISION. Define onlythe nonliteral data items that you use as arguments. Figurative constants are notallowed as arguments.A function-identifier is the combination of the <strong>COBOL</strong> reserved word FUNCTIONfollowed by a function name (such as Max), followed by any arguments to be usedin the evaluation of the function (such as x, y, z). For example, the groups ofhighlighted words below are function-identifiers:Unstring Function Upper-case(Name) Delimited By SpaceInto Fname LnameCompute A=1+Function Log10(x)Compute M = Function Max(xyz)A function-identifier represents both the invocation of the function and the datavalue returned by the function. Because it actually represents a data item, you canuse a function-identifier in most places in the PROCEDURE DIVISION where a dataitem that has the attributes of the returned value can be used.The <strong>COBOL</strong> word function is a reserved word, but the function-names are notreserved. You can use them in other contexts, such as <strong>for</strong> the name of a data item.For example, you could use Sqrt to invoke an intrinsic function and to name adata 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.40 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


...Compute Sqrt = 16 ** .5Compute 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 (referencemodifier) in a function-identifier <strong>for</strong> alphanumeric or national functions. Numericintrinsic functions are further classified according to the type of numbers theyreturn.The functions MAX, MIN, DATEVAL, and UNDATE can return either type of valuedepending on the type of arguments you supply.The functions DATEVAL, UNDATE, and YEARWINDOW are provided with the millenniumlanguage extensions to assist with manipulating and converting windowed datefields.Functions can reference other functions as arguments provided that the results ofthe nested functions meet the requirements <strong>for</strong> the arguments of the outer function.For example, Function Sqrt(5) returns a numeric value. Thus, the three argumentsto the MAX function below are all numeric, which is an allowable argument type <strong>for</strong>this function:Compute x = Function Max((Function Sqrt(5)) 2.5 3.5)RELATED TASKS“Processing table items using intrinsic functions” on page 86“Converting data items (intrinsic functions)” on page 112“Evaluating data items (intrinsic functions)” on page 115Using tables (arrays) and pointersIn <strong>COBOL</strong>, arrays are called tables. A table is a set of logically consecutive dataitems that you define in the DATA DIVISION by using the OCCURS clause.Pointers are data items that contain virtual storage addresses. You define themeither explicitly with the USAGE IS POINTER clause in the DATA DIVISION orimplicitly as ADDRESS OF special registers.You can per<strong>for</strong>m the following operations with pointer data items:v Pass them between programs by using the CALL...BYREFERENCE statement.v Move them to other pointers by using the SET statement.v Compare them to other pointers <strong>for</strong> equality by using a relation condition.v Initialize them to contain an invalid address by using VALUE IS NULL.Use pointer data items to:v Accomplish limited base addressing, particularly if you want to pass and receiveaddresses of a record area that is defined with OCCURS DEPENDING ON and isthere<strong>for</strong>e variably located.v Handle a chained list.RELATED TASKS“Defining a table (OCCURS)” on page 69“Using procedure and function pointers” on page 462Chapter 2. Using data 41


Storage and its addressabilityWhen you run <strong>COBOL</strong> programs, the programs and the data that they use residein virtual storage. Storage that you use with <strong>COBOL</strong> can be either below the16-MB line or above the 16-MB line but below the 2-GB bar. Two modes ofaddressing are available to address this storage: 24-bit and 31-bit.You can address storage below (but not above) the 16-MB line with 24-bitaddressing. You can address storage either above or below the 16-MB line with31-bit addressing. Unrestricted storage is addressable by 31-bit addressing andthere<strong>for</strong>e encompasses all the storage available to your program, both above andbelow the 16-MB line.<strong>Enterprise</strong> <strong>COBOL</strong> does not directly exploit the 64-bit virtual addressing capabilityof z/<strong>OS</strong>; however, <strong>COBOL</strong> applications running in 31-bit or 24-bit addressingmode are fully supported on 64-bit z/<strong>OS</strong> systems.Addressing mode (AMODE) is the attribute that tells which hardware addressing modeis supported by your program: 24-bit addressing, 31-bit addressing, or either 24-bitor 31-bit addressing. This attribute is AMODE 24, AMODE 31, orAMODE ANY,respectively. The object program, the load module, and the executing program eachhas an AMODE attribute. All <strong>Enterprise</strong> <strong>COBOL</strong> object programs are AMODE ANY.Residency mode (RMODE) is the attribute of a program load module that identifieswhere in virtual storage the program will reside: below the 16-MB line, or eitherbelow or above. This attribute is RMODE 24 or RMODE ANY.<strong>Enterprise</strong> <strong>COBOL</strong> uses Language Environment services to control the storage usedat run time. Thus <strong>COBOL</strong> compiler options and Language Environment runtimeoptions influence the AMODE and RMODE attributes of your program and data, aloneand in combination:DATARMODERENTHEAPSTACKALL31Settings <strong>for</strong> RMODECompiler option that influences the location of storage <strong>for</strong> WORKING-STORAGEdata, I-O buffers, and parameter lists <strong>for</strong> programs compiled with RENT.Compiler option that influences the residency mode and also influences thelocation of storage <strong>for</strong> WORKING-STORAGE data, I-O buffers, and parameterlists <strong>for</strong> programs compiled with NORENT.Compiler option to generate a reentrant program.Runtime option that controls storage <strong>for</strong> the runtime heap. For example,<strong>COBOL</strong> WORKING-STORAGE is allocated from heap storage.Runtime option that controls storage <strong>for</strong> the runtime stack. For example,<strong>COBOL</strong> LOCAL-STORAGE is allocated from stack storage.Runtime option that specifies whether an application can run entirely inAMODE 31.The RMODE and RENT options determine the RMODE attribute of your program.Table 4. Effect of RMODE and RENT compiler options on the RMODE attributeRMODE compiler option RENT compiler option RMODE attributeRMODE(AUTO) NORENT RMODE 24RMODE(AUTO) RENT RMODE ANY42 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 4. Effect of RMODE and RENT compiler options on the RMODEattribute (continued)RMODE compiler option RENT compiler option RMODE attributeRMODE(24) RENT or NORENT RMODE 24RMODE(ANY) RENT or NORENT RMODE ANYLink-edit considerations: When the object code that <strong>COBOL</strong> generates has anattribute of RMODE 24, you must link-edit it with RMODE 24. When the object codethat <strong>COBOL</strong> generates has an attribute of RMODE ANY, you can link-edit it withRMODE ANY or RMODE 24.Storage restrictions <strong>for</strong> passing dataDo not pass parameters that are allocated in storage above the 16-MB line to AMODE24 subprograms. Force the WORKING-STORAGE data and parameter lists below the line<strong>for</strong> programs that run in 31-bit addressing mode and pass data to programs thatrun in AMODE 24:v Compile reentrant programs (RENT) with DATA(24).v Compile nonreentrant programs (NORENT) with RMODE(24) or RMODE(AUTO).vNonreentrant programs (NORENT) compiled with RMODE(ANY) must be link-editedwith RMODE 24. The data areas <strong>for</strong> NORENT programs are above the 16-MB line orbelow the 16-MB line depending on where the program is loaded, even if theprogram was compiled with DATA(24). The DATA option does not affect programscompiled with NORENT.Location of data areasFor reentrant programs, the DATA compiler option and the HEAP runtime optioncontrol whether storage <strong>for</strong> data areas such as WORKING-STORAGE SECTION and FDrecord areas is obtained from below the 16-MB line or from unrestricted storage.Compile programs with RENT or RMODE(ANY) if they will be run with 31-bitaddressing in virtual storage addresses above the 16-MB line. The DATA option doesnot affect programs compiled with NORENT.When you specify the runtime option HEAP(,,BELOW), the DATA compiler option hasno effect; the storage <strong>for</strong> WORKING-STORAGE SECTION data areas is allocated frombelow the 16-MB line. However, with HEAP(,,ANYWHERE) as the runtime option,storage <strong>for</strong> data areas is allocated from below the 16-MB line if you compiled theprogram with the DATA(24) compiler option, or from unrestricted storage if youcompiled with the DATA(31) compiler option.Storage <strong>for</strong> LOCAL-STORAGE dataThe location of LOCAL-STORAGE data items is controlled by the STACK runtime optionand the AMODE of the program. LOCAL-STORAGE data items are acquired inunrestricted storage when the STACK(,,ANYWHERE) runtime option is in effect andthe program is running in AMODE 31. Otherwise LOCAL-STORAGE is acquired belowthe 16-MB line. The DATA compiler option does not influence the location ofLOCAL-STORAGE data.Chapter 2. Using data 43


Storage <strong>for</strong> external dataIn addition to affecting how storage is obtained <strong>for</strong> dynamic data areas(WORKING-STORAGE, FD record areas, and parameter lists), the DATA compiler optioncan also influence where storage <strong>for</strong> EXTERNAL data is obtained. Storage required <strong>for</strong>EXTERNAL data is obtained from unrestricted storage if the following conditions aremet:vvvThe program is compiled with the DATA(31) and RENT compiler options or theRMODE(ANY) and NORENT compiler options.The HEAP(,,ANYWHERE) runtime option is in effect.The ALL31(ON) runtime option is in effect.In all other cases, the storage <strong>for</strong> EXTERNAL data is obtained from below the 16-MBline. If you specify the ALL31(ON) runtime option, all the programs in the run unitmust be capable of running in 31-bit addressing mode.Storage <strong>for</strong> QSAM input-output buffersThe DATA compiler option can also influence where input-output buffers <strong>for</strong> QSAMfiles are obtained. See the related references below <strong>for</strong> in<strong>for</strong>mation about allocationof buffers <strong>for</strong> QSAM files and the DATA compiler option.RELATED CONCEPTS“AMODE switching” on page 453Language Environment <strong>Programming</strong> <strong>Guide</strong> (AMODE considerations <strong>for</strong> heapstorage)RELATED TASKSChapter 24, “Using subprograms,” on page 447Chapter 25, “Sharing data,” on page 465RELATED REFERENCES“Allocation of buffers <strong>for</strong> QSAM files” on page 173“DATA” on page 314“RENT” on page 341“RMODE” on page 342“Per<strong>for</strong>mance-related compiler options” on page 672Language Environment <strong>Programming</strong> Reference (HEAP, STACK, ALL31)MVS Program Management: User’s <strong>Guide</strong> and Reference44 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 3. Working with numbers and arithmeticIn general, you can view <strong>COBOL</strong> numeric data as a series of decimal digitpositions. However, numeric items can also have special properties such as anarithmetic sign or a currency sign.To define, display, and store numeric data so that you can per<strong>for</strong>m arithmeticoperations efficiently:vvvvvvUse the PICTURE clause and the characters 9, +, -, P, S, and V to define numericdata.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 <strong>for</strong>mats 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 per<strong>for</strong>marithmetic.Use the CURRENCY SIGN clause and appropriate PICTURE characters to designatethe currency you want.Defining numeric dataRELATED TASKS“Defining numeric data”“Displaying numeric data” on page 47“Controlling how numeric data is stored” on page 48“Checking <strong>for</strong> incompatible data (numeric class test)” on page 56“Per<strong>for</strong>ming arithmetic” on page 57“Using currency signs” on page 67Define numeric items by using the PICTURE clause with the character 9 in the datadescription to represent the decimal digits of the number. Do not use an X, whichis <strong>for</strong> alphanumeric data items.For example, Count-y below is a numeric data item, an external decimal item thathas USAGE DISPLAY (a zoned decimal item):05 Count-y Pic 9(4) Value 25.05 Customer-name Pic X(20) Value "Johnson".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 USAGENATIONAL (a national decimal item):05 Count-n Pic 9(4) Value 25 Usage National.You can code up to 18 digits in the PICTURE clause when you compile using thedefault compiler option ARITH(COMPAT) (referred to as compatibility mode). Whenyou compile using ARITH(EXTEND) (referred to as extended mode), you can code upto 31 digits in the PICTURE clause.Other characters of special significance that you can code are:PIndicates leading or trailing zeros© Copyright IBM Corp. 1991, 2009 45


SVIndicates a sign, positive or negativeImplies a decimal pointThe s in the following example means that the value is signed:05 Price Pic s99v99.The field can there<strong>for</strong>e hold a positive or a negative value. The v indicates theposition of an implied decimal point, but does not contribute to the size of theitem because it does not require a storage position. An s usually does notcontribute to the size of a numeric item, because by default s does not require astorage position.However, if you plan to port your program or data to a different machine, youmight want to code the sign <strong>for</strong> a zoned decimal data item as a separate positionin storage. In the following case, the sign takes 1 byte:05 Price Pic s99V99 Sign Is Leading, Separate.This coding ensures that the convention your machine uses <strong>for</strong> storing anonseparate sign will not cause unexpected results on a machine that uses adifferent convention.Separate signs are also preferable <strong>for</strong> zoned decimal data items that will be printedor displayed.Separate signs are required <strong>for</strong> national decimal data items that are signed. Thesign takes 2 bytes of storage, as in the following example:05 Price Pic s99V99 Usage National Sign Is Leading, Separate.You cannot use the PICTURE clause with internal floating-point data (COMP-1 orCOMP-2). However, you can use the VALUE clause to provide an initial value <strong>for</strong> aninternal floating-point literal:05 Compute-result Usage Comp-2 Value 06.23E-24.For in<strong>for</strong>mation about external floating-point data, see the examples referencedbelow and the related concept about <strong>for</strong>mats <strong>for</strong> numeric data.“Examples: numeric data and internal representation” on page 52RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49Appendix A, “Intermediate results and arithmetic precision,” on page 687RELATED TASKS“Displaying numeric data” on page 47“Controlling how numeric data is stored” on page 48“Per<strong>for</strong>ming arithmetic” on page 57“Defining national numeric data items” on page 129RELATED REFERENCES“Sign representation of zoned and packed-decimal data” on page 55“Storage of character data” on page 133“ARITH” on page 306“NUMPROC” on page 333SIGN clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)46 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Displaying numeric dataYou 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 readand understand when you display or print them.For example, in the code below, Edited-price is a numeric-edited item that hasUSAGE DISPLAY. (You can specify the clause USAGE IS DISPLAY <strong>for</strong> numeric-editeditems; however, it is implied. It means that the items are stored in character<strong>for</strong>mat.)05 Price Pic 9(5)v99.05 Edited-price Pic $zz,zz9.99....Move Price To Edited-priceDisplay Edited-priceIf the contents of Price are 0150099 (representing the value 1,500.99), $ 1,500.99 isdisplayed when you run the code. The z in the PICTURE clause of Edited-priceindicates the suppression of leading zeros.You can define numeric-edited data items to hold national (UTF-16) charactersinstead of alphanumeric characters. To do so, declare the numeric-edited items asUSAGE NATIONAL. The effect of the editing symbols is the same <strong>for</strong> numeric-editeditems that have USAGE NATIONAL as it is <strong>for</strong> numeric-edited items that have USAGEDISPLAY, except that the editing is done with national characters. For example, ifEdited-price is declared as USAGE NATIONAL in the code above, the item is editedand displayed using national characters.To display numeric or numeric-edited data items that have USAGE NATIONAL inEBCDIC, direct them to CONSOLE. For example, if Edited-price in the code abovehas USAGE NATIONAL, $ 1,500.99 is displayed when you run the program if the laststatement above is:Display Edited-price Upon ConsoleYou can cause an elementary numeric or numeric-edited item to be filled withspaces when a value of zero is stored into it by coding the BLANK WHEN ZERO clause<strong>for</strong> the item. For example, each of the DISPLAY statements below causes blanks tobe displayed instead of zeros:05 Price Pic 9(5)v99.05 Edited-price-D Pic $99,999.99Blank When Zero.05 Edited-price-N Pic $99,999.99 Usage NationalBlank When Zero....Move 0 to PriceMove Price to Edited-price-DMove Price to Edited-price-NDisplay Edited-price-DDisplay Edited-price-N upon consoleYou cannot use numeric-edited items as sending operands in arithmeticexpressions or in ADD, SUBTRACT, MULTIPLY, DIVIDE, orCOMPUTE statements. (Numericediting takes place when a numeric-edited item is the receiving field <strong>for</strong> one ofthese statements, or when a MOVE statement has a numeric-edited receiving fieldand a numeric-edited or numeric sending field.) You use numeric-edited itemsprimarily <strong>for</strong> displaying or printing numeric data.Chapter 3. Working with numbers and arithmetic 47


You can move numeric-edited items to numeric or numeric-edited items. In thefollowing example, the value of the numeric-edited item (whether it has USAGEDISPLAY or USAGE NATIONAL) is moved to the numeric item:Move Edited-price to PriceDisplay PriceIf these two statements immediately followed the statements in the first exampleabove, then Price would be displayed as 0150099, representing the value 1,500.99.Price would also be displayed as 0150099 if Edited-price had USAGE NATIONAL.You can also move numeric-edited items to alphanumeric, alphanumeric-edited,floating-point, and national data items. For a complete list of the valid receivingitems <strong>for</strong> numeric-edited data, see the related reference about the MOVE statement.“Examples: numeric data and internal representation” on page 52RELATED TASKS“Displaying values on a screen or in a file (DISPLAY)” on page 38“Controlling how numeric data is stored”“Defining numeric data” on page 45“Per<strong>for</strong>ming arithmetic” on page 57“Defining national numeric data items” on page 129“Converting to or from national (Unicode) representation” on page 134RELATED REFERENCESMOVE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)BLANK WHEN ZERO clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Controlling how numeric data is storedYou can control how the computer stores numeric data items by coding the USAGEclause in your data description entries.You might want to control the <strong>for</strong>mat <strong>for</strong> any of several reasons such as these:v Arithmetic per<strong>for</strong>med with computational data types is more efficient than withUSAGE DISPLAY or USAGE NATIONAL data types.v Packed-decimal <strong>for</strong>mat requires less storage per digit than USAGE DISPLAY orUSAGE NATIONAL data types.v Packed-decimal <strong>for</strong>mat converts to and from DISPLAY or NATIONAL <strong>for</strong>mat moreefficiently than binary <strong>for</strong>mat does.v Floating-point <strong>for</strong>mat is well suited <strong>for</strong> arithmetic operands and results withwidely varying scale, while maintaining the maximal number of significantdigits.v You might need to preserve data <strong>for</strong>mats when you move data from onemachine to another.The numeric data you use in your program will have one of the following <strong>for</strong>matsavailable with <strong>COBOL</strong>:v External decimal (USAGE DISPLAY or USAGE NATIONAL)v External floating point (USAGE DISPLAY or USAGE NATIONAL)v Internal decimal (USAGE PACKED-DECIMAL)v Binary (USAGE BINARY)v Native binary (USAGE COMP-5)48 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vInternal floating point (USAGE COMP-1 or USAGE COMP-2)COMP and COMP-4 are synonymous with BINARY, and COMP-3 is synonymous withPACKED-DECIMAL.The compiler converts displayable numbers to the internal representation of theirnumeric values be<strong>for</strong>e using them in arithmetic operations. There<strong>for</strong>e it is oftenmore efficient if you define data items as BINARY or PACKED-DECIMAL than asDISPLAY or NATIONAL. For example:05 Initial-count Pic S9(4) Usage Binary Value 1000.Regardless of which USAGE clause you use to control the internal representation of avalue, you use the same PICTURE clause conventions and decimal value in theVALUE clause (except <strong>for</strong> internal floating-point data, <strong>for</strong> which you cannot use aPICTURE clause).“Examples: numeric data and internal representation” on page 52RELATED CONCEPTS“Formats <strong>for</strong> numeric data”“Data <strong>for</strong>mat conversions” on page 54Appendix A, “Intermediate results and arithmetic precision,” on page 687RELATED TASKS“Defining numeric data” on page 45“Displaying numeric data” on page 47“Per<strong>for</strong>ming arithmetic” on page 57Formats <strong>for</strong> numeric dataRELATED REFERENCES“Conversions and precision” on page 54“Sign representation of zoned and packed-decimal data” on page 55Several <strong>for</strong>mats are available <strong>for</strong> numeric data.External decimal (DISPLAY and NATIONAL) itemsWhen USAGE DISPLAY is in effect <strong>for</strong> a category numeric data item (either becauseyou have coded it, or by default), each position (byte) of storage contains onedecimal digit. The items are stored in displayable <strong>for</strong>m. External decimal items thathave USAGE DISPLAY are referred to as zoned decimal data items.When USAGE NATIONAL is in effect <strong>for</strong> a category numeric data item, 2 bytes ofstorage are required <strong>for</strong> each decimal digit. The items are stored in UTF-16 <strong>for</strong>mat.External decimal items that have USAGE NATIONAL are referred to as national decimaldata items.National decimal data items, if signed, must have the SIGN SEPARATE clause ineffect. All other rules <strong>for</strong> zoned decimal items apply to national decimal items. Youcan use national decimal items anywhere that other category numeric data itemscan be used.External decimal (both zoned decimal and national decimal) data items areprimarily intended <strong>for</strong> receiving and sending numbers between your program andChapter 3. Working with numbers and arithmetic 49


files, terminals, or printers. You can also use external decimal items as operandsand receivers in arithmetic processing. However, if your program per<strong>for</strong>ms a lot ofintensive arithmetic, and efficiency is a high priority, <strong>COBOL</strong>’s computationalnumeric types might be a better choice <strong>for</strong> the data items used in the arithmetic.External floating-point (DISPLAY and NATIONAL) itemsWhen USAGE DISPLAY is in effect <strong>for</strong> a floating-point data item (either because youhave coded it, or by default), each PICTURE character position (except <strong>for</strong> v, animplied decimal point, if used) takes 1 byte of storage. The items are stored indisplayable <strong>for</strong>m. External floating-point items that have USAGE DISPLAY arereferred to as display floating-point data items in this in<strong>for</strong>mation when necessary todistinguish them from external floating-point items that have USAGE NATIONAL.In the following example, Compute-Result is implicitly defined as a displayfloating-point item:05 Compute-Result Pic -9v9(9)E-99.The minus signs (-) do not mean that the mantissa and exponent must necessarilybe negative numbers. Instead, they mean that when the number is displayed, thesign appears as a blank <strong>for</strong> positive numbers or a minus sign <strong>for</strong> negativenumbers. If you instead code a plus sign (+), the sign appears as a plus sign <strong>for</strong>positive numbers or a minus sign <strong>for</strong> negative numbers.When USAGE NATIONAL is in effect <strong>for</strong> a floating-point data item, each PICTUREcharacter position (except <strong>for</strong> v, if used) takes 2 bytes of storage. The items arestored as national characters (UTF-16). External floating-point items that haveUSAGE NATIONAL are referred to as national floating-point data items.The existing rules <strong>for</strong> display floating-point items apply to national floating-pointitems.In the following example, Compute-Result-N is a national floating-point item:05 Compute-Result-N Pic -9v9(9)E-99 Usage National.If Compute-Result-N is displayed, the signs appear as described above <strong>for</strong>Compute-Result, but in national characters. To instead display Compute-Result-N inEBCDIC characters, direct it to the console:Display Compute-Result-N Upon ConsoleYou cannot use the VALUE clause <strong>for</strong> external floating-point items.As with external decimal numbers, external floating-point numbers have to beconverted (by the compiler) to an internal representation of their numeric valuebe<strong>for</strong>e they can be used in arithmetic operations. If you compile with the defaultoption ARITH (COMPAT), external floating-point numbers are converted to long(64-bit) floating-point <strong>for</strong>mat. If you compile with ARITH (EXTEND), they are insteadconverted to extended-precision (128-bit) floating-point <strong>for</strong>mat.Binary (COMP) itemsBINARY, COMP, and COMP-4 are synonyms. Binary-<strong>for</strong>mat numbers occupy 2, 4, or 8bytes of storage. If the PICTURE clause specifies that an item is signed, the leftmostbit is used as the operational sign.50 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


A binary number with a PICTURE description of four or fewer decimal digitsoccupies 2 bytes; five to nine decimal digits, 4 bytes; and 10 to 18 decimal digits, 8bytes. Binary items with nine or more digits require more handling by thecompiler. Testing them <strong>for</strong> the SIZE ERROR condition and rounding is morecumbersome than with other types.You can use binary items, <strong>for</strong> example, <strong>for</strong> indexes, subscripts, switches, andarithmetic operands or results.Use the TRUNC(STD|OPT|BIN) compiler option to indicate how binary data (BINARY,COMP, orCOMP-4) is to be truncated.Native binary (COMP-5) itemsData items that you declare as USAGE COMP-5 are represented in storage as binarydata. However, unlike USAGE COMP items, they can contain values of magnitude upto the capacity of the native binary representation (2, 4, or 8 bytes) rather thanbeing limited to the value implied by the number of 9s inthePICTURE clause.When you move or store numeric data into a COMP-5 item, truncation occurs at thebinary field size rather than at the <strong>COBOL</strong> PICTURE size limit. When you referencea COMP-5 item, the full binary field size is used in the operation.COMP-5 is thus particularly useful <strong>for</strong> binary data items that originate innon-<strong>COBOL</strong> programs where the data might not con<strong>for</strong>m to a <strong>COBOL</strong> PICTUREclause.The table below shows the ranges of possible values <strong>for</strong> COMP-5 data items.Table 5. Ranges in value of COMP-5 data itemsPICTURE Storage representation Numeric valuesS9(1) through S9(4) Binary halfword (2 bytes) -32768 through +32767S9(5) through S9(9) Binary fullword (4 bytes) -2,147,483,648 through +2,147,483,647S9(10) throughS9(18)Binary doubleword (8bytes)-9,223,372,036,854,775,808 through+9,223,372,036,854,775,8079(1) through 9(4) Binary halfword (2 bytes) 0 through 655359(5) through 9(9) Binary fullword (4 bytes) 0 through 4,294,967,2959(10) through 9(18) Binary doubleword (8bytes)0 through 18,446,744,073,709,551,615You can specify scaling (that is, decimal positions or implied integer positions) inthe PICTURE clause of COMP-5 items. If you do so, you must appropriately scale themaximal capacities listed above. For example, a data item you describe as PICTURES99V99 COMP-5 is represented in storage as a binary halfword, and supports a rangeof values from -327.68 through +327.67.Large literals in VALUE clauses: Literals specified in VALUE clauses <strong>for</strong> COMP-5 itemscan, with a few exceptions, contain values of magnitude up to the capacity of thenative binary representation. See <strong>Enterprise</strong> <strong>COBOL</strong> Language Reference <strong>for</strong> theexceptions.Regardless of the setting of the TRUNC compiler option, COMP-5 data items behavelike binary data does in programs compiled with TRUNC(BIN).Chapter 3. Working with numbers and arithmetic 51


Packed-decimal (COMP-3) itemsPACKED-DECIMAL and COMP-3 are synonyms. Packed-decimal items occupy 1 byte ofstorage <strong>for</strong> every two decimal digits you code in the PICTURE description, exceptthat the rightmost byte contains only one digit and the sign. This <strong>for</strong>mat is mostefficient when you code an odd number of digits in the PICTURE description, sothat the leftmost byte is fully used. Packed-decimal items are handled asfixed-point numbers <strong>for</strong> arithmetic purposes.Internal floating-point (COMP-1 and COMP-2) itemsCOMP-1 refers to short floating-point <strong>for</strong>mat and COMP-2 refers to long floating-point<strong>for</strong>mat, which occupy 4 and 8 bytes of storage, respectively. The leftmost bitcontains the sign and the next 7 bits contain the exponent; the remaining 3 or 7bytes contain the mantissa.COMP-1 and COMP-2 data items are stored in zSeries ® hexadecimal <strong>for</strong>mat.RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125Appendix A, “Intermediate results and arithmetic precision,” on page 687RELATED TASKS“Defining numeric data” on page 45“Defining national numeric data items” on page 129RELATED REFERENCES“Storage of character data” on page 133“TRUNC” on page 353Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SIGN clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)VALUE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Examples: numeric data and internal representationThe following table shows the internal representation of numeric items.52 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 6. Internal representation of numeric itemsPICTURE and USAGE andNumeric type optional SIGN clause Value Internal representationExternal decimal PIC S9999 DISPLAY + 1234 F1 F2 F3 C4- 1234 F1 F2 F3 D41234 F1 F2 F3 C4PIC 9999 DISPLAY 1234 F1 F2 F3 F4PIC 9999 NATIONAL 1234 00 31 00 32 00 33 00 34PIC S9999 DISPLAY+ 1234 C1 F2 F3 F4SIGN LEADING- 1234 D1 F2 F3 F4PIC S9999 DISPLAY+ 1234 4E F1 F2 F3 F4SIGN LEADING SEPARATE- 1234 60 F1 F2 F3 F4PIC S9999 DISPLAY+ 1234 F1 F2 F3 F4 4ESIGN TRAILING SEPARATE- 1234 F1 F2 F3 F4 60PIC S9999 NATIONAL+ 1234 00 2B 00 31 00 32 00 33 00 34SIGN LEADING SEPARATE- 1234 00 2D 00 31 00 32 00 33 00 34PIC S9999 NATIONAL+ 1234 00 31 00 32 00 33 00 34 00 2BSIGN TRAILING SEPARATE- 1234 00 31 00 32 00 33 00 34 00 2DBinaryPIC S9999 BINARY+ 1234 04 D2PIC S9999 COMPPIC S9999 COMP-4- 1234 FB 2EPIC S9999 COMP-5 + 12345 1 30 39- 12345 1 CF C7PIC 9999 BINARY1234 04 D2PIC 9999 COMPPIC 9999 COMP-4Internal decimalInternal floatingpointExternal floatingpointPIC 9999 COMP-5 60000 1 EA 60PIC S9999 PACKED-DECIMALPIC S9999 COMP-3PIC 9999PIC 9999PACKED-DECIMALCOMP-3+ 1234 01 23 4C- 1234 01 23 4D1234 01 23 4FCOMP-1 + 1234 43 4D 20 00- 1234 C3 4D 20 00COMP-2 + 1234 43 4D 20 00 00 00 00 00- 1234 C3 4D 20 00 00 00 00 00PIC +9(2).9(2)E+99 DISPLAY + 12.34E+02 4E F1 F2 4B F3 F4 C5 4E F0 F2- 12.34E+02 60 F1 F2 4B F3 F4 C5 4E F0 F2PIC +9(2).9(2)E+99 NATIONAL + 12.34E+02 00 2B 00 31 00 32 00 2E 00 3300 34 00 45 00 2B 00 30 00 32- 12.34E+02 00 2D 00 31 00 32 00 2E 00 3300 34 00 45 00 2B 00 30 00 321. The example demonstrates that COMP-5 data items can contain values of magnitude up to the capacity of thenative binary representation (2, 4, or 8 bytes), rather than being limited to the value implied by the number of 9sin the PICTURE clause.Chapter 3. Working with numbers and arithmetic 53


Data <strong>for</strong>mat conversionsWhen the code in your program involves the interaction of items that havedifferent data <strong>for</strong>mats, the compiler converts those items either temporarily, <strong>for</strong>comparisons and arithmetic operations, or permanently, <strong>for</strong> assignment to thereceiver in a MOVE or COMPUTE statement.A conversion is actually a move of a value from one data item to another. Thecompiler per<strong>for</strong>ms any conversions that are required during the execution ofarithmetic or comparisons by using the same rules that are used <strong>for</strong> MOVE andCOMPUTE statements.When possible, the compiler per<strong>for</strong>ms a move to preserve numeric value instead ofa direct digit-<strong>for</strong>-digit move.Conversion generally requires additional storage and processing time because datais moved to an internal work area and converted be<strong>for</strong>e the operation isper<strong>for</strong>med. The results might also have to be moved back into a work area andconverted again.Conversions between fixed-point data <strong>for</strong>mats (external decimal, packed decimal,or binary) are without loss of precision provided that the target field can containall the digits of the source operand.A loss of precision is possible in conversions between fixed-point data <strong>for</strong>mats andfloating-point data <strong>for</strong>mats (short floating point, long floating point, or externalfloating point). These conversions happen during arithmetic evaluations that havea mixture of both fixed-point and floating-point operands.RELATED REFERENCES“Conversions and precision”“Sign representation of zoned and packed-decimal data” on page 55Conversions and precisionIn some numeric conversions, a loss of precision is possible; other conversionspreserve precision or result in rounding.Because both fixed-point and external floating-point items have decimalcharacteristics, references to fixed-point items in the following examples includeexternal floating-point items unless stated otherwise.When the compiler converts from fixed-point to internal floating-point <strong>for</strong>mat,fixed-point numbers in base 10 are converted to the numbering system usedinternally.When the compiler converts short <strong>for</strong>m to long <strong>for</strong>m <strong>for</strong> comparisons, zeros areused <strong>for</strong> padding the shorter number.Conversions that lose precisionWhen a USAGE COMP-1 data item is moved to a fixed-point data item that has morethan nine digits, the fixed-point data item will receive only nine significant digits,and the remaining digits will be zero.54 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


When a USAGE COMP-2 data item is moved to a fixed-point data item that has morethan 18 digits, the fixed-point data item will receive only 18 significant digits, andthe remaining digits will be zero.Conversions that preserve precisionIf a fixed-point data item that has six or fewer digits is moved to a USAGE COMP-1data item and then returned to the fixed-point data item, the original value isrecovered.If a USAGE COMP-1 data item is moved to a fixed-point data item of nine or moredigits and then returned to the USAGE COMP-1 data item, the original value isrecovered.If a fixed-point data item that has 15 or fewer digits is moved to a USAGE COMP-2data item and then returned to the fixed-point data item, the original value isrecovered.If a USAGE COMP-2 data item is moved to a fixed-point (not external floating-point)data item of 18 or more digits and then returned to the USAGE COMP-2 data item,the original value is recovered.Conversions that result in roundingIf a USAGE COMP-1 data item, a USAGE COMP-2 data item, an external floating-pointdata item, or a floating-point literal is moved to a fixed-point data item, roundingoccurs in the low-order position of the target data item.If a USAGE COMP-2 data item is moved to a USAGE COMP-1 data item, rounding occursin the low-order position of the target data item.If a fixed-point data item is moved to an external floating-point data item and thePICTURE of the fixed-point data item contains more digit positions than the PICTUREof the external floating-point data item, rounding occurs in the low-order positionof the target data item.RELATED CONCEPTSAppendix A, “Intermediate results and arithmetic precision,” on page 687Sign representation of zoned and packed-decimal dataSign representation affects the processing and interaction of zoned decimal andinternal decimal data.Given X'sd', where s is the sign representation and d represents the digit, the validsign representations <strong>for</strong> zoned decimal (USAGE DISPLAY) data without the SIGN ISSEPARATE clause are:Positive:C, A, E, and FNegative:D and BThe <strong>COBOL</strong> NUMPROC compiler option affects sign processing <strong>for</strong> zoned decimal andinternal decimal data. NUMPROC has no effect on binary data, national decimal data,or floating-point data.Chapter 3. Working with numbers and arithmetic 55


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 yourdata 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 toprocess data. The preferred sign is generated only where necessary (<strong>for</strong>example, when unsigned data is moved to signed data). Using theNUMPROC(PFD) option can save processing time, but you must use preferredsigns with your data <strong>for</strong> correct processing.NUMPROC(NOPFD)When the NUMPROC(NOPFD) compiler option is in effect, the compiler acceptsany valid sign configuration. The preferred sign is always generated in thereceiver. NUMPROC(NOPFD) is less efficient than NUMPROC(PFD), but you shoulduse it whenever data that does not use preferred signs might exist.If an unsigned, zoned-decimal sender is moved to an alphanumericreceiver, the sign is unchanged (even with NUMPROC(NOPFD) in effect).NUMPROC(MIG)When NUMPROC(MIG) is in effect, the compiler generates code that is similarto that produced by <strong>OS</strong>/VS <strong>COBOL</strong>. This option can be especially useful ifyou migrate <strong>OS</strong>/VS <strong>COBOL</strong> programs to IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong>.RELATED REFERENCES“NUMPROC” on page 333“ZWB” on page 360Checking <strong>for</strong> incompatible data (numeric class test)The compiler assumes that values you supply <strong>for</strong> a data item are valid <strong>for</strong> thePICTURE and USAGE clauses, and does not check their validity. Ensure that thecontents of a data item con<strong>for</strong>m to the PICTURE and USAGE clauses be<strong>for</strong>e using theitem in additional processing.It can happen that values are passed into your program and assigned to items thathave incompatible data descriptions <strong>for</strong> those values. For example, nonnumericdata might be moved or passed into a field that is defined as numeric, or a signednumber might be passed into a field that is defined as unsigned. In either case, thereceiving fields contain invalid data. When you give an item a value that isincompatible with its data description, references to that item in the PROCEDUREDIVISION are undefined and your results are unpredictable.You can use the numeric class test to per<strong>for</strong>m data validation. For example:Linkage Section.01 Count-x Pic 999....Procedure Division Using Count-x.If Count-x is numeric then display "Data is good"56 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The numeric class test checks the contents of a data item against a set of valuesthat are valid <strong>for</strong> the PICTURE and USAGE of the data item. For example, apacked-decimal item is checked <strong>for</strong> hexadecimal values X’0’ through X’9’ in thedigit positions and <strong>for</strong> a valid sign value in the sign position (whether separate ornonseparate).For zoned decimal and packed-decimal items, the numeric class test is affected bythe NUMPROC compiler option and the NUMCLS option (which is set at installationtime). To determine the NUMCLS setting used at your installation, consult yoursystem programmer.If NUMCLS(PRIM) is in effect at your installation, use the following table to find thevalues that the compiler considers valid <strong>for</strong> the sign.Table 7. NUMCLS(PRIM) and valid signsNUMPROC(NOPFD) NUMPROC(PFD) NUMPROC(MIG)Signed C, D, F C, D, +0 (positive C, D, Fzero)Unsigned F F FSeparate sign +, - +, -, +0 (positivezero)+, -If NUMCLS(ALT) is in effect at your installation, use the following table to find thevalues that the compiler considers valid <strong>for</strong> the sign.Table 8. NUMCLS(ALT) and valid signsNUMPROC(NOPFD) NUMPROC(PFD) NUMPROC(MIG)Signed A to F C, D, +0 (positive AtoFzero)Unsigned F F FSeparate sign +, - +, -, +0 (positivezero)+, -Per<strong>for</strong>ming arithmeticRELATED REFERENCES“NUMPROC” on page 333You can use any of several <strong>COBOL</strong> language features (including COMPUTE,arithmetic expressions, numeric intrinsic functions, and math and date callableservices) to per<strong>for</strong>m arithmetic. Your choice depends on whether a feature meetsyour particular needs.For most common arithmetic evaluations, the COMPUTE statement is appropriate. Ifyou need to use numeric literals, numeric data, or arithmetic operators, you mightwant to use arithmetic expressions. In places where numeric expressions areallowed, you can save time by using numeric intrinsic functions. LanguageEnvironment callable services <strong>for</strong> mathematical functions and <strong>for</strong> date and timeoperations also provide a means of assigning arithmetic results to data items.RELATED TASKS“Using COMPUTE and other arithmetic statements” on page 58Chapter 3. Working with numbers and arithmetic 57


“Using arithmetic expressions”“Using numeric intrinsic functions” on page 59“Using math-oriented callable services” on page 60“Using date callable services” on page 62Using COMPUTE and other arithmetic statementsUse the COMPUTE statement <strong>for</strong> most arithmetic evaluations rather than ADD,SUBTRACT, MULTIPLY, and DIVIDE statements. Often you can code only one COMPUTEstatement instead of several individual arithmetic statements.The COMPUTE statement assigns the result of an arithmetic expression to one ormore data items:Compute z =a+b/c**d-eCompute xyz=a+b/c**d-eSome arithmetic calculations might be more intuitive using arithmetic statementsother than COMPUTE. For example:COMPUTECompute Increment = Increment + 1Compute Balance =Balance - OverdraftCompute IncrementOne =IncrementOne + 1Compute IncrementTwo =IncrementTwo + 1Compute IncrementThree =IncrementThree + 1Equivalent arithmetic statementsAdd 1 to IncrementSubtract Overdraft from BalanceAdd 1 to IncrementOne,IncrementTwo,IncrementThreeYou might also prefer to use the DIVIDE statement (with its REMAINDER phrase) <strong>for</strong>division in which you want to process a remainder. The REM intrinsic function alsoprovides the ability to process a remainder.When you per<strong>for</strong>m arithmetic calculations, you can use national decimal dataitems as operands just as you use zoned decimal data items. You can also usenational floating-point data items as operands just as you use displayfloating-point operands.RELATED CONCEPTS“Fixed-point contrasted with floating-point arithmetic” on page 64Appendix A, “Intermediate results and arithmetic precision,” on page 687RELATED TASKS“Defining numeric data” on page 45Using arithmetic expressionsYou can use arithmetic expressions in many (but not all) places in statementswhere numeric data items are allowed.For example, you can use arithmetic expressions as comparands in relationconditions:If(a+b)>(c-d+5)Then. . .58 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Arithmetic expressions can consist of a single numeric literal, a single numeric dataitem, or a single intrinsic function reference. They can also consist of several ofthese items connected by arithmetic operators.Arithmetic operators are evaluated in the following order of precedence:Table 9. Order of evaluation of arithmetic operatorsOperator Meaning Order of evaluationUnary + or - Algebraic sign First** Exponentiation Second/ or * Division or multiplication ThirdBinary + or - Addition or subtraction LastOperators at the same level of precedence are evaluated from left to right;however, you can use parentheses to change the order of evaluation. Expressionsin parentheses are evaluated be<strong>for</strong>e 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 64Appendix A, “Intermediate results and arithmetic precision,” on page 687Using numeric intrinsic functionsYou can use numeric intrinsic functions only in places where numeric expressionsare allowed. These functions can save you time because you don’t have to code themany common types of calculations that they provide.Numeric intrinsic functions return a signed numeric value, and are treated astemporary numeric data items.Numeric functions are classified into the following categories:IntegerThose that return an integerFloating pointThose that return a long (64-bit) or extended-precision (128-bit)floating-point value (depending on whether you compile using the defaultoption ARITH(COMPAT) or using ARITH(EXTEND))Mixed Those that return an integer, a floating-point value, or a fixed-pointnumber with decimal places, depending on the argumentsYou can use intrinsic functions to per<strong>for</strong>m several different arithmetic operations,as outlined in the following table.Chapter 3. Working with numbers and arithmetic 59


Table 10. Numeric intrinsic functionsNumberhandling Date and time Finance Mathematics StatisticsLENGTHMAXMINNUMVALNUMVAL-CORD-MAXORD-MINCURRENT-DATEDATE-OF-INTEGERDATE-TO-YYYYMMDDDATEVALDAY-OF-INTEGERDAY-TO-YYYYDDDINTEGER-OF-DATEINTEGER-OF-DAYUNDATEWHEN-COMPILEDYEAR-TO-YYYYYEARWINDOWANNUITYPRESENT-VALUEAC<strong>OS</strong>ASINATANC<strong>OS</strong>FACTORIALINTEGERINTEGER-PARTLOGLOG10MODREMSINSQRTSUMTANMEANMEDIANMIDRANGERANDOMRANGESTANDARD-DEVIATIONVARIANCE“Examples: numeric intrinsic functions” on page 62You can reference one function as the argument of another. A nested function isevaluated independently of the outer function (except when the compilerdetermines whether a mixed function should be evaluated using fixed-point orfloating-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, andthe arithmetic expression (c/d)):Compute x = Function Sum(a b (c / d))You can reference all the elements of a table (or array) as function arguments byusing the ALL subscript.You can also use the integer special registers as arguments wherever integerarguments are allowed.Many of the capabilities of numeric intrinsic functions are also provided byLanguage Environment callable services.RELATED CONCEPTS“Fixed-point contrasted with floating-point arithmetic” on page 64Appendix A, “Intermediate results and arithmetic precision,” on page 687RELATED REFERENCES“ARITH” on page 306Using math-oriented callable servicesMost <strong>COBOL</strong> intrinsic functions have corresponding math-oriented callableservices that you can use to produce the same results.When you compile with the default option ARITH(COMPAT), <strong>COBOL</strong> floating-pointintrinsic functions return long (64-bit) results. When you compile with option60 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


ARITH(EXTEND), <strong>COBOL</strong> floating-point intrinsic functions (with the exception ofRANDOM) return extended-precision (128-bit) results.For example (considering the first row of the table below), if you compile usingARITH(COMPAT), CEESDACS returns the same result as AC<strong>OS</strong>. If you compile usingARITH(EXTEND), CEESQACS returns the same result as AC<strong>OS</strong>.Table 11. Compatibility of math intrinsic functions and callable services<strong>COBOL</strong> intrinsicfunctionCorrespondinglong-precision LanguageEnvironment callable serviceCorrespondingextended-precision LanguageEnvironment callable serviceAC<strong>OS</strong> CEESDACS CEESQACS YesASIN CEESDASN CEESQASN YesATAN CEESDATN CEESQATN YesC<strong>OS</strong> CEESDC<strong>OS</strong> CEESQC<strong>OS</strong> YesLOG CEESDLOG CEESQLOG YesLOG10 CEESDLG1 CEESQLG1 YesRANDOM 1 CEERAN0 none NoREM CEESDMOD CEESQMOD YesSIN CEESDSIN CEESQSIN YesSQRT CEESDSQT CEESQSQT YesTAN CEESDTAN CEESQTAN YesResults same <strong>for</strong> intrinsicfunction and callableservice?1. RANDOM returns a long (64-bit) floating-point result even if you pass it a 31-digit argument and compile withARITH(EXTEND).Both the RANDOM intrinsic function and CEERAN0 service generate randomnumbers between zero and one. However, because each uses its own algorithm,RANDOM and CEERAN0 produce different random numbers from the same seed.Even <strong>for</strong> functions that produce the same results, how you use intrinsic functionsand Language Environment callable services differs. The rules <strong>for</strong> the data typesrequired <strong>for</strong> intrinsic function arguments are less restrictive. For numeric intrinsicfunctions, you can use arguments that are of any numeric data type. When youinvoke a Language Environment callable service with a CALL statement, however,you must ensure that the parameters match the numeric data types (generallyCOMP-1 or COMP-2) required by that service.The error handling of intrinsic functions and Language Environment callableservices sometimes differs. If you pass an explicit feedback token when calling theLanguage Environment math services, you must check the feedback code aftereach call and take explicit action to deal with errors. However, if you call with thefeedback token explicitly OMITTED, you do not need to check the token; LanguageEnvironment automatically signals any errors.RELATED CONCEPTS“Fixed-point contrasted with floating-point arithmetic” on page 64Appendix A, “Intermediate results and arithmetic precision,” on page 687RELATED TASKS“Using Language Environment callable services” on page 681Chapter 3. Working with numbers and arithmetic 61


RELATED REFERENCES“ARITH” on page 306Using date callable servicesBoth the <strong>COBOL</strong> date intrinsic functions and the Language Environment datecallable services are based on the Gregorian calendar. However, the starting datescan differ depending on the setting of the INTDATE compiler option.When INTDATE(LILIAN) is in effect, <strong>COBOL</strong> uses October 15, 1582 as day 1.Language Environment always uses October 15, 1582 as day 1. If you useINTDATE(LILIAN), you get equivalent results from <strong>COBOL</strong> intrinsic functions andLanguage Environment date callable services. The following table compares theresults when INTDATE(LILIAN) is in effect.Table 12. INTDATE(LILIAN) and compatibility of date intrinsic functions and callableservicesLanguage Environment callable<strong>COBOL</strong> intrinsic function serviceResultsDATE-OF-INTEGER CEEDATE with picture string YYYYMMDD CompatibleDAY-OF-INTEGER CEEDATE with picture string YYYYDDD CompatibleINTEGER-OF-DATE CEEDAYS CompatibleINTEGER-OF-DATE CEECBLDY IncompatibleWhen the default setting of INTDATE(ANSI) is in effect, <strong>COBOL</strong> uses January 1, 1601as 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 callableservicesLanguage Environment callable<strong>COBOL</strong> intrinsic function serviceResultsINTEGER-OF-DATE CEECBLDY CompatibleDATE-OF-INTEGER CEEDATE with picture string YYYYMMDD IncompatibleDAY-OF-INTEGER CEEDATE with picture string YYYYDDD IncompatibleINTEGER-OF-DATE CEEDAYS IncompatibleRELATED TASKS“Using Language Environment callable services” on page 681RELATED REFERENCES“INTDATE” on page 325Examples: numeric intrinsic functionsThe following examples and accompanying explanations show intrinsic functionsin each of several categories.Where the examples below show zoned decimal data items, national decimal itemscould instead be used. (Signed national decimal items, however, require that theSIGN SEPARATE clause be in effect.)62 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


General number handlingSuppose you want to find the maximum value of two prices (represented below asalphanumeric items with dollar signs), put this value into a numeric field in anoutput record, and determine the length of the output record. You can useNUMVAL-C (a function that returns the numeric value of an alphanumeric or nationalliteral, or an alphanumeric or national data item) and the MAX and LENGTH functionsto do so: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:Move Function Upper-case (Product-Name) to Product-NameDate and timeThe following example shows how to calculate a due date that is 90 days fromtoday. The first eight characters returned by the CURRENT-DATE function representthe date in a four-digit year, two-digit month, and two-digit day <strong>for</strong>mat (YYYYMMDD).The date is converted to its integer value; then 90 is added to this value and theinteger is converted back to the YYYYMMDD <strong>for</strong>mat.01 YYYYMMDD Pic 9(8).01 Integer-Form Pic S9(9)....Move Function Current-Date(1:8) to YYYYMMDDCompute Integer-Form = Function Integer-of-Date(YYYYMMDD)Add 90 to Integer-FormCompute YYYYMMDD = Function Date-of-Integer(Integer-Form)Display 'Due Date: ' YYYYMMDDFinanceBusiness investment decisions frequently require computing the present value ofexpected 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 thefuture is that amount, which, if invested today at a given interest rate, wouldaccumulate to that future amount.For example, assume that a proposed investment of $1,000 produces a paymentstream of $100, $200, and $300 over the next three years, one payment per yearrespectively. The following <strong>COBOL</strong> statements calculate the present value of thosecash inflows at a 10% interest rate:01 Series-Amt1 Pic 9(9)V99 Value 100.01 Series-Amt2 Pic 9(9)V99 Value 200.01 Series-Amt3 Pic 9(9)V99 Value 300.01 Discount-Rate Pic S9(2)V9(6) Value .10.01 Todays-Value Pic 9(9)V99....Chapter 3. Working with numbers and arithmetic 63


Compute Todays-Value =FunctionPresent-Value(Discount-Rate Series-Amt1 Series-Amt2 Series-Amt3)You can use the ANNUITY function in business problems that require you todetermine the amount of an installment payment (annuity) necessary to repay theprincipal and interest of a loan. The series of payments is characterized by anequal amount each period, periods of equal length, and an equal interest rate eachperiod. The following example shows how you can calculate the monthly paymentrequired to repay a $15,000 loan in three years at a 12% annual interest rate (36monthly payments, interest per month = .12/12):01 Loan Pic 9(9)V99.01 Payment Pic 9(9)V99.01 Interest Pic 9(9)V99.01 Number-Periods Pic 99....Compute Loan = 15000Compute Interest = .12Compute Number-Periods = 36Compute Payment =Loan * Function Annuity((Interest / 12) Number-Periods)MathematicsThe following <strong>COBOL</strong> statement demonstrates that you can nest intrinsicfunctions, use arithmetic expressions as arguments, and per<strong>for</strong>m previouslycomplex calculations simply:Compute Z = Function Log(Function Sqrt (2 *X+1))+Function Rem(X 2)Here in the addend the intrinsic function REM (instead of a DIVIDE statement with aREMAINDER clause) returns the remainder of dividing X by 2.StatisticsIntrinsic functions make calculating statistical in<strong>for</strong>mation easier. Assume you areanalyzing various city taxes and want to calculate the mean, median, and range(the difference between the maximum and minimum taxes):01 Tax-S Pic 99v999 value .045.01 Tax-T Pic 99v999 value .02.01 Tax-W Pic 99v999 value .035.01 Tax-B Pic 99v999 value .03.01 Ave-Tax Pic 99v999.01 Median-Tax Pic 99v999.01 Tax-Range Pic 99v999....Compute Ave-Tax = Function Mean (Tax-S Tax-T Tax-W Tax-B)Compute Median-Tax = Function Median (Tax-S Tax-T Tax-W Tax-B)Compute Tax-Range = Function Range (Tax-S Tax-T Tax-W Tax-B)RELATED TASKS“Converting to numbers (NUMVAL, NUMVAL-C)” on page 113Fixed-point contrasted with floating-point arithmeticHow you code arithmetic in a program (whether an arithmetic statement, anintrinsic function, an expression, or some combination of these nested within eachother) determines whether the evaluation is done with floating-point or fixed-pointarithmetic.64 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Many statements in a program could involve arithmetic. For example, each of thefollowing types of <strong>COBOL</strong> statements requires some arithmetic evaluation:v General arithmeticvvcompute report-matrix-col = (emp-count ** .5) + 1add report-matrix-min to report-matrix-max giving report-matrix-totExpressions and functionscompute report-matrix-col = function sqrt(emp-count) + 1compute whole-hours = function integer-part((average-hours) + 1)Arithmetic comparisonsif report-matrix-col < function sqrt(emp-count) + 1if whole-hours not = function integer-part((average-hours) + 1)Floating-point evaluationsIn general, if your arithmetic coding has either of the characteristics listed below, itis evaluated in floating-point arithmetic:v An operand or result field is floating point.An operand is floating point if you code it as a floating-point literal or if youcode it as a data item that is defined as USAGE COMP-1, USAGE COMP-2, or externalfloating point (USAGE DISPLAY or USAGE NATIONAL with a floating-point PICTURE).An operand that is a nested arithmetic expression or a reference to a numericintrinsic function results in floating-point arithmetic when any of the followingconditions 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.v An exponent contains decimal places.An exponent contains decimal places if you use a literal that contains decimalplaces, give the item a PICTURE that contains decimal places, or use an arithmeticexpression or function whose result has decimal places.An arithmetic expression or numeric function yields a result that has decimalplaces if any operand or argument (excluding divisors and exponents) has decimalplaces.Fixed-point evaluationsIn general, if an arithmetic operation contains neither of the characteristics listedabove <strong>for</strong> floating point, the compiler causes it to be evaluated in fixed-pointarithmetic. In other words, arithmetic evaluations are handled as fixed point only ifall the operands are fixed point, the result field is defined to be fixed point, andnone of the exponents represent values with decimal places. Nested arithmeticexpressions and function references must also represent fixed-point values.Arithmetic comparisons (relation conditions)When you compare numeric expressions using a relational operator, the numericexpressions (whether they are data items, arithmetic expressions, functionreferences, or some combination of these) are comparands in the context of theentire evaluation. That is, the attributes of each can influence the evaluation of theother: both expressions are evaluated in fixed point, or both are evaluated inChapter 3. Working with numbers and arithmetic 65


floating point. This is also true of abbreviated comparisons even though onecomparand does not explicitly appear in the comparison. For example:if(a+d)=(b+e)andcThis statement has two comparisons: (a+d)=(b+e), and (a+d)=c.Although (a+d)does not explicitly appear in the second comparison, it is acomparand in that comparison. There<strong>for</strong>e, the attributes of c can influence theevaluation of (a+d).The compiler handles comparisons (and the evaluation of any arithmeticexpressions nested in comparisons) in floating-point arithmetic if either comparandis a floating-point value or resolves to a floating-point value.The compiler handles comparisons (and the evaluation of any arithmeticexpressions nested in comparisons) in fixed-point arithmetic if both comparandsare fixed-point values or resolve to fixed-point values.Implicit comparisons (no relational operator used) are not handled as a unit,however; the two comparands are treated separately as to their evaluation infloating-point or fixed-point arithmetic. In the following example, five arithmeticexpressions are evaluated independently of one another’s attributes, and then arecompared to each other.evaluate (a + d)when (b + e) thru cwhen (f / g) thru (h * i)...end-evaluate“Examples: fixed-point and floating-point evaluations”RELATED REFERENCES“Arithmetic expressions in nonarithmetic statements” on page 695Examples: fixed-point and floating-point evaluationsThe following example shows statements that are evaluated using fixed-pointarithmetic and using floating-point arithmetic.Assume that you define the data items <strong>for</strong> an employee table in the followingmanner:01 employee-table.05 emp-count pic 9(4).05 employee-record occurs 1 to 1000 timesdepending on emp-count.10 hours pic +9(5)e+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).These statements are evaluated using floating-point arithmetic:compute report-matrix-col = (emp-count ** .5) + 1compute report-matrix-col = function sqrt(emp-count) + 1if report-matrix-tot < function sqrt(emp-count) + 1These statements are evaluated using fixed-point arithmetic:66 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Using currency signsadd report-matrix-min to report-matrix-max giving report-matrix-totcompute report-matrix-max =function max(report-matrix-max report-matrix-tot)if whole-hours not = function integer-part((average-hours) + 1)Many programs need to process financial in<strong>for</strong>mation and present that in<strong>for</strong>mationusing the appropriate currency signs. With <strong>COBOL</strong> currency support (and theappropriate code page <strong>for</strong> your printer or display unit), you can use severalcurrency signs in a program.You can use one or more of the following signs:v Symbols such as the dollar sign ($)v Currency signs of more than one character (such as USD or EUR)v Euro sign, established by the Economic and Monetary Union (EMU)To specify the symbols <strong>for</strong> displaying financial in<strong>for</strong>mation, use the CURRENCY SIGNclause (in the SPECIAL-NAMES paragraph in the CONFIGURATION SECTION) with thePICTURE characters that relate to those symbols. In the following example, thePICTURE character $ indicates that the currency sign $US is to be used:Currency Sign is "$US" with Picture Symbol "$"....77 Invoice-Amount Pic $$,$$9.99....Display "Invoice amount is " Invoice-Amount.In this example, if Invoice-Amount contained 1500.00, the display output would be:Invoice amount is$US1,500.00By using more than one CURRENCY SIGN clause in your program, you can allow <strong>for</strong>multiple currency signs to be displayed.You can use a hexadecimal literal to indicate the currency sign value. Using ahexadecimal literal could be useful if the data-entry method <strong>for</strong> the sourceprogram does not allow the entry of the intended characters easily. The followingexample shows the hexadecimal value X'9F' used as the currency sign:Currency Sign X'9F' with Picture Symbol 'U'....01 Deposit-Amount Pic UUUUU9.99.If there is no corresponding character <strong>for</strong> the euro sign on your keyboard, youneed to specify it as a hexadecimal value in the CURRENCY SIGN clause. Thehexadecimal value <strong>for</strong> the euro sign is either X'9F' or X'5A' depending on the codepage in use, as shown in the following table.Table 14. Hexadecimal values of the euro signCode pageCCSID Applicable countriesModifiedfrom Euro sign1140 USA, Canada, Netherlands, Portugal, Australia, 037 X’9F’New Zealand1141 Austria, Germany 273 X’9F’1142 Denmark, Norway 277 X’5A’1143 Finland, Sweden 278 X’5A’Chapter 3. Working with numbers and arithmetic 67


Table 14. Hexadecimal values of the euro sign (continued)Code pageCCSID Applicable countriesModifiedfrom Euro sign1144 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 313CURRENCY SIGN clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: multiple currency signsThe following example shows how you can display values in both euro currency(as EUR) and Swiss francs (as CHF).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-EuroCompute Deposit-in-CHF Rounded= Deposit-in-Euro * EUR-to-CHF-Conv-RateOn Size ErrorPer<strong>for</strong>m Conversion-ErrorNot On Size ErrorMove Deposit-in-CHF to Report-in-FrancDisplay "Deposit in euro = " Report-in-EuroDisplay "Deposit in franc = " Report-in-FrancEnd-ComputeGoback.Conversion-Error.Display "Conversion error from EUR to CHF"Display "Euro value: " Report-in-Euro.The above example produces the following display output:Deposit in euro = EUR 8000.00Deposit in franc = CHF 12311.44The exchange rate used in this example is <strong>for</strong> illustrative purposes only.68 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 4. Handling tablesA table is a collection of data items that have the same description, such as accounttotals or monthly averages; it consists of a table name and subordinate items calledtable elements. A table is the <strong>COBOL</strong> 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 threetimes.Rather than defining repetitious items as separate, consecutive entries in the DATADIVISION, you use the OCCURS clause in the DATA DIVISION entry to define a table.This practice has these advantages:v The code clearly shows the unity of the items (the table elements).v You can use subscripts and indexes to refer to the table elements.v You can easily repeat data items.Tables are important <strong>for</strong> increasing the speed of a program, especially one thatlooks up records.Defining a table (OCCURS)RELATED TASKS“Nesting tables” on page 71“Defining a table (OCCURS)”“Referring to an item in a table” on page 72“Putting values into a table” on page 75“Creating variable-length tables (DEPENDING ON)” on page 81“Searching a table” on page 84“Processing table items using intrinsic functions” on page 86“Handling tables efficiently” on page 665To code a table, give the table a group name and define a subordinate item (thetable element) to be repeated n times.01 table-name.05 element-name OCCURS n TIMES.. . . (subordinate items of the table element)In the example above, table-name is the name of an alphanumeric group item. Thetable element definition (which includes the OCCURS clause) is subordinate to thegroup item that contains the table. The OCCURS clause cannot appear in a level-01description.© Copyright IBM Corp. 1991, 2009 69


If a table is to contain only Unicode (UTF-16) data, and you want the group itemthat contains the table to behave like an elementary category national item in mostoperations, code the GROUP-USAGE NATIONAL clause <strong>for</strong> the group item:01 table-nameN Group-Usage National.05 element-nameN OCCURS m TIMES.10 elementN1 Pic nn.10 elementN2 Pic S99 Sign Is Leading, Separate....Any elementary item that is subordinate to a national group must be explicitly orimplicitly described as USAGE NATIONAL, and any subordinate numeric data itemthat is signed must be implicitly or explicitly described with the SIGN IS SEPARATEclause.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 OCCURSclause.To specify that table elements will be arranged in ascending or descending orderbased on the values in one or more key fields of the table, code the ASCENDING orDESCENDING KEY phrases of the OCCURS clause, or both. Specify the names of thekeys in decreasing order of significance. Keys can be of class alphabetic,alphanumeric, DBCS, national, or numeric. (If it has USAGE NATIONAL, a key can beof 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 doa binary search (SEARCH ALL) of a table.“Example: binary search” on page 86RELATED CONCEPTS“National groups” on page 129RELATED TASKS“Nesting tables” on page 71“Referring to an item in a table” on page 72“Putting values into a table” on page 75“Creating variable-length tables (DEPENDING ON)” on page 81“Using national groups” on page 130“Doing a binary search (SEARCH ALL)” on page 85“Defining numeric data” on page 45RELATED REFERENCESOCCURS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SIGN clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)ASCENDING KEY and DESCENDING KEY phrases(<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)70 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Nesting tablesTo create a two-dimensional table, define a one-dimensional table in eachoccurrence of another one-dimensional table.For example, in SAMPLE-TABLE-TWO above, TABLE-ROW is an element of aone-dimensional table that occurs two times. TABLE-COLUMN is an element of atwo-dimensional table that occurs three times in each occurrence of TABLE-ROW.To create a three-dimensional table, define a one-dimensional table in eachoccurrence of another one-dimensional table, which is itself contained in eachoccurrence of another one-dimensional table. For example:In SAMPLE-TABLE-THREE, TABLE-DEPTH is an element of a one-dimensional table thatoccurs two times. TABLE-ROW is an element of a two-dimensional table that occurstwo times within each occurrence of TABLE-DEPTH. TABLE-COLUMN is an element of athree-dimensional table that occurs three times within each occurrence ofTABLE-ROW.In a two-dimensional table, the two subscripts correspond to the row and columnnumbers. In a three-dimensional table, the three subscripts correspond to thedepth, row, and column numbers.“Example: subscripting” on page 72“Example: indexing” on page 72RELATED TASKS“Defining a table (OCCURS)” on page 69“Referring to an item in a table” on page 72“Putting values into a table” on page 75“Creating variable-length tables (DEPENDING ON)” on page 81“Searching a table” on page 84“Processing table items using intrinsic functions” on page 86“Handling tables efficiently” on page 665RELATED REFERENCESOCCURS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 4. Handling tables 71


Example: subscriptingThe following example shows valid references to SAMPLE-TABLE-THREE that useliteral subscripts. The spaces are required in the second example.TABLE-COLUMN (2, 2, 1)TABLE-COLUMN (2 2 1)In either table reference, the first value (2) refers to the second occurrence withinTABLE-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 referenceis valid if SUB1 and SUB2 are data-names that contain positive integer values withinthe range of the table.TABLE-COLUMN (SUB1 SUB2)RELATED TASKS“Subscripting” on page 73Example: indexingThe following example shows how displacements to elements that are referencedwith indexes are calculated.Consider the following three-dimensional table, SAMPLE-TABLE-FOUR:01 SAMPLE-TABLE-FOUR05 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).Suppose you code the following relative indexing reference to SAMPLE-TABLE-FOUR:TABLE-COLUMN (INX-A + 1, INX-B + 2, INX-C - 1)This reference causes the following computation of the displacement to theTABLE-COLUMN element:(contents of INX-A) + (256 * 1)+ (contents of INX-B) + (64 * 2)+ (contents of INX-C) - (8 * 1)This calculation is based on the following element lengths:v Each occurrence of TABLE-DEPTH is 256 bytes in length (4 *8*8).v Each occurrence of TABLE-ROW is 64 bytes in length (8 * 8).v Each occurrence of TABLE-COLUMN is 8 bytes in length.RELATED TASKS“Indexing” on page 74Referring to an item in a tableA table element has a collective name, but the individual items within it do nothave unique data-names.To refer to an item, you have a choice of three techniques:72 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vSubscriptingvvUse 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) thatis added to the address of the table to locate an item (as a displacement from thebeginning of the table). This technique is called indexing, or subscripting usingindex-names.Use both subscripts and indexes together.RELATED TASKS“Subscripting”“Indexing” on page 74The lowest possible subscript value is 1, which references the first occurrence of atable element. In a one-dimensional table, the subscript corresponds to the rownumber.You can use a literal or a data-name as a subscript. If a data item that has a literalsubscript 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 thedata-name as an elementary numeric integer. The most efficient <strong>for</strong>mat isCOMPUTATIONAL (COMP) with a PICTURE size that is smaller than five digits. Youcannot use a subscript with a data-name that is used as a subscript. The codegenerated <strong>for</strong> the application resolves the location of a variable subscript at runtime.You can increment or decrement a literal or variable subscript by a specifiedinteger amount. For example:TABLE-COLUMN (SUB1 - 1, SUB2 + 3)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. Forexample: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 elementnumber 1, beginning at character position 3, <strong>for</strong> a length of 2 characters.“Example: subscripting” on page 72RELATED TASKS“Indexing” on page 74Chapter 4. Handling tables 73


Indexing“Putting values into a table” on page 75“Searching a table” on page 84“Handling tables efficiently” on page 665You create an index by using the INDEXED BY phrase of the OCCURS clause toidentify an index-name.For example, INX-A in the following code is an index-name:05 TABLE-ITEM PIC X(8)OCCURS 10 INDEXED BY INX-A.The compiler calculates the value contained in the index as the occurrence number(subscript) minus 1, multiplied by the length of the table element. There<strong>for</strong>e, <strong>for</strong>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 tabledescriptions have the same number of table elements, and the table elements are ofthe same length.You can use the USAGE IS INDEX clause to create an index data item, and can usean index data item with any table. For example, INX-B in the following code is anindex data item:77 INX-B USAGE IS INDEX....SET INX-A TO 10SET INX-B TO INX-A.PERFORM VARYING INX-A FROM 1 BY 1 UNTIL INX-A > INX-BDISPLAY TABLE-ITEM (INX-A)...END-PERFORM.The index-name INX-A is used to traverse table TABLE-ITEM above. The index dataitem INX-B is used to hold the index of the last element of the table. The advantageof this type of coding is that calculation of offsets of table elements is minimized,and no conversion is necessary <strong>for</strong> the UNTIL condition.You can use the SET statement to assign to an index data item the value that youstored in an index-name, as in the statement SET INX-B TO INX-A above. Forexample, when you load records into a variable-length table, you can store theindex value of the last record into a data item defined as USAGE IS INDEX. Thenyou can test <strong>for</strong> the end of the table by comparing the current index value with theindex value of the last record. This technique is useful when you look through orprocess a table.You can increment or decrement an index-name by an elementary integer dataitem or a nonzero integer literal, <strong>for</strong> example:SET INX-A DOWN BY 3The integer represents a number of occurrences. It is converted to an index valuebe<strong>for</strong>e being added to or subtracted from the index.74 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Initialize the index-name by using a SET, PERFORM VARYING, orSEARCH ALLstatement. You can then use the index-name in SEARCH or relational conditionstatements. To change the value, use a PERFORM, SEARCH, orSET statement.Because you are comparing a physical displacement, you can directly use indexdata items only in SEARCH and SET statements or in comparisons with indexes orother index data items. You cannot use index data items as subscripts or indexes.“Example: indexing” on page 72RELATED TASKS“Subscripting” on page 73“Putting values into a table”“Searching a table” on page 84“Processing table items using intrinsic functions” on page 86“Handling tables efficiently” on page 665Putting values into a tableRELATED REFERENCESINDEXED BY phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)INDEX phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SET statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)You can put values into a table by loading the table dynamically, initializing thetable with the INITIALIZE statement, or assigning values with the VALUE clausewhen you define the table.RELATED TASKS“Loading a table dynamically”“Loading a variable-length table” on page 82“Initializing a table (INITIALIZE)” on page 76“Assigning values when you define a table (VALUE)” on page 77“Assigning values to a variable-length table” on page 83Loading a table dynamicallyIf the initial values of a table are different with each execution of your program,you can define the table without initial values. You can instead read the changedvalues into the table dynamically be<strong>for</strong>e the program refers to the table.To load a table, use the PERFORM statement and either subscripting or indexing.When reading data to load your table, test to make sure that the data does notexceed the space allocated <strong>for</strong> the table. Use a named value (rather than a literal)<strong>for</strong> the maximum item count. Then, if you make the table bigger, you need tochange only one value instead of all references to a literal.“Example: PERFORM and subscripting” on page 79“Example: PERFORM and indexing” on page 80RELATED REFERENCESPERFORM with VARYING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 4. Handling tables 75


Initializing a table (INITIALIZE)You can load a table by coding one or more INITIALIZE statements.For example, to move the value 3 into each of the elementary numeric data itemsin a table called TABLE-ONE, shown below, you can code the following statement:INITIALIZE TABLE-ONE REPLACING NUMERIC DATA BY 3.To move the character ’X’ into each of the elementary alphanumeric data items inTABLE-ONE, you can code the following statement:INITIALIZE TABLE-ONE REPLACING ALPHANUMERIC DATA BY "X".When you use the INITIALIZE statement to initialize a table, the table is processedas a group item (that is, with group semantics); elementary data items within thegroup are recognized and processed. For example, suppose that TABLE-ONE is analphanumeric 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.10 Unit-price Pic 99V Value 50.10 Discount Pic 99V Value 25.10 Sales-Price Pic 999 Value 375....Initialize TABLE-ONE Replacing Numeric Data By 3Alphanumeric Data By "X"The table below shows the content that each of the twenty 12-byte elementsTrans-out(n) has be<strong>for</strong>e execution and after execution of the INITIALIZE statementshown above:Trans-out(n) be<strong>for</strong>eTrans-out(n) afterR13105025375 XXb030303003 11. The symbol b represents a blank space.You can similarly use an INITIALIZE statement to load a table that is defined as anational group. For example, if TABLE-ONE shown above specified the GROUP-USAGENATIONAL clause, and Trans-code and Part-number had N instead of X in theirPICTURE clauses, the following statement would have the same effect as theINITIALIZE statement above, except that the data in TABLE-ONE would instead beencoded in UTF-16:Initialize TABLE-ONE Replacing Numeric Data By 3National Data By N"X"The REPLACING NUMERIC phrase initializes floating-point data items also.You can use the REPLACING phrase of the INITIALIZE statement similarly toinitialize all of the elementary ALPHABETIC, DBCS, ALPHANUMERIC-EDITED,NATIONAL-EDITED, and NUMERIC-EDITED data items in a table.The INITIALIZE statement cannot assign values to a variable-length table (that is, atable that was defined using the OCCURS DEPENDING ON clause).76 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Examples: initializing data items” on page 30RELATED TASKS“Initializing a structure (INITIALIZE)” on page 32“Assigning values when you define a table (VALUE)”“Assigning values to a variable-length table” on page 83“Looping through a table” on page 100“Using data items and group items” on page 26“Using national groups” on page 130RELATED REFERENCESINITIALIZE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Assigning values when you define a table (VALUE)If a table is to contain stable values (such as days and months), you can set thespecific values when you define the table.Set static values in tables in one of these ways:v Initialize each table item individually.v Initialize an entire table at the group level.v Initialize all occurrences of a given table element to the same value.RELATED TASKS“Initializing each table item individually”“Initializing a table at the group level” on page 78“Initializing all occurrences of a given table element” on page 78“Initializing a structure (INITIALIZE)” on page 32Initializing each table item individuallyIf a table is small, you can set the value of each item individually by using a VALUEclause.Use the following technique, which is shown in the example code below:1. Declare a record (such as Error-Flag-Table below) that contains the items thatare to be in the table.2. Set the initial value of each item in a VALUE clause.3. Code a REDEFINES entry to make the record into a table.************************************************************** ERROR FLAG TABLE **************************************************************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 TimesIndexed By Flag-Index Pic X.Chapter 4. Handling tables 77


In the example above, the VALUE clause at the 01 level initializes each of the tableitems to the same value. Each table item could instead be described with its ownVALUE clause to initialize that item to a distinct value.To initialize larger tables, use MOVE, PERFORM, orINITIALIZE statements.RELATED TASKS“Initializing a structure (INITIALIZE)” on page 32“Assigning values to a variable-length table” on page 83RELATED REFERENCESREDEFINES clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)OCCURS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Initializing a table at the group levelCode an alphanumeric or national group data item and assign to it, through theVALUE clause, the contents of the whole table. Then, in a subordinate data item, usean OCCURS clause to define the individual table items.In the following example, the alphanumeric group data item TABLE-ONE uses aVALUE clause that initializes each of the four elements of TABLE-TWO:01 TABLE-ONE VALUE "1234".05 TABLE-TWO OCCURS 4 TIMES PIC X.In the following example, the national group data item Table-OneN uses a VALUEclause that initializes each of the three elements of the subordinate data itemTable-TwoN (each of which is implicitly USAGE NATIONAL). Note that you caninitialize a national group data item with a VALUE clause that uses an alphanumericliteral, as shown below, or a national literal.01 Table-OneN Group-Usage National Value "AB12CD34EF56".05 Table-TwoN Occurs 3 Times Indexed By MyI.10 ElementOneN Pic nn.10 ElementTwoN Pic 99.After Table-OneN is initialized, ElementOneN(1) contains NX"00410042" (the UTF-16representation of ’AB’), the national decimal item ElementTwoN(1) containsNX"00310032" (the UTF-16 representation of ’12’), and so <strong>for</strong>th.RELATED REFERENCESOCCURS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)GROUP-USAGE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Initializing all occurrences of a given table elementYou can use the VALUE clause in the data description of a table element to initializeall instances of that element to the specified value.01 T2.05 T-OBJ PIC 9 VALUE 3.05 T OCCURS 5 TIMESDEPENDING 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 beinitialized to AA, all the Y elements (1 through 5) to be initialized to 19, and all theZ elements (1 through 5) to be initialized to BB. T-OBJ is then set to 3.78 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Assigning values to a variable-length table” on page 83RELATED REFERENCESOCCURS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: PERFORM and subscriptingThis example traverses an error-flag table using subscripting until an error codethat has been set is found. If an error code is found, the corresponding errormessage is moved to a print report field.************************************************************** ERROR FLAG TABLE **************************************************************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 TimesIndexed By Flag-Index Pic X.77 Error-on Pic X Value "E".************************************************************** ERROR MESSAGE TABLE **************************************************************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 TimesIndexed By Message-Index Pic X(25)....PROCEDURE DIVISION....Per<strong>for</strong>mVarying Sub From 1 By 1Until No-ErrorsIf Error-Flag (Sub) = Error-OnMove Space To Error-Flag (Sub)Move Error-Message (Sub) To Print-MessagePer<strong>for</strong>m 260-Print-ReportEnd-IfEnd-Per<strong>for</strong>m...Chapter 4. Handling tables 79


Example: PERFORM and indexingThis example traverses an error-flag table using indexing until an error code thathas been set is found. If an error code is found, the corresponding error message ismoved to a print report field.************************************************************** ERROR FLAG TABLE **************************************************************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 TimesIndexed By Flag-Index Pic X.77 Error-on Pic X Value "E".************************************************************** ERROR MESSAGE TABLE **************************************************************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 TimesIndexed By Message-Index Pic X(25)....PROCEDURE DIVISION....Set Flag-Index To 1Per<strong>for</strong>m Until No-ErrorsSearch Error-FlagWhen Error-Flag (Flag-Index) = Error-OnMove Space To Error-Flag (Flag-Index)Set Message-Index To Flag-IndexMove Error-Message (Message-Index) ToPrint-MessagePer<strong>for</strong>m 260-Print-ReportEnd-SearchEnd-Per<strong>for</strong>m...80 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Creating variable-length tables (DEPENDING ON)If you do not know be<strong>for</strong>e run time how many times a table element occurs, definea variable-length table. To do so, use the OCCURS DEPENDING ON (ODO) clause.X OCCURS 1 TO 10 TIMES DEPENDING ON YIn the example above, X is called the ODO subject, and Y is called the ODO object.Two factors affect the successful manipulation of variable-length records:v Correct calculation of record lengthsThe length of the variable portions of a group item is the product of the objectof the DEPENDING ON phrase and the length of the subject of the OCCURS clause.v Con<strong>for</strong>mance of the data in the object of the OCCURS DEPENDING ON clause to itsPICTURE clauseIf the content of the ODO object does not match its PICTURE clause, the programcould terminate abnormally. You must ensure that the ODO object correctlyspecifies the current number of occurrences of table elements.The following example shows a group item (REC-1) that contains both the subjectand object of the OCCURS DEPENDING ON clause. The way the length of the groupitem 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 TIMESDEPENDING ON FIELD-1PIC X(05).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 ofREC-1 is determined immediately be<strong>for</strong>e the move, using the current value inFIELD-1. If the content of FIELD-1 con<strong>for</strong>ms to its PICTURE clause (that is, if FIELD-1contains a zoned decimal item), the move can proceed based on the actual lengthof REC-1. Otherwise, the result is unpredictable. You must ensure that the ODOobject has the correct value be<strong>for</strong>e you initiate the move.When you do a move to REC-1 (the receiving item in this case), the length of REC-1is determined using the maximum number of occurrences. In this example, fiveoccurrences of FIELD-2, plus FIELD-1, yields a length of 26 bytes. In this case, youdo not need to set the ODO object (FIELD-1) be<strong>for</strong>e referencing REC-1 as a receivingitem. However, the sending field’s ODO object (not shown) must be set to a validnumeric value between 1 and 5 <strong>for</strong> the ODO object of the receiving field to bevalidly set by the move.However, if you do a move to REC-1 (again the receiving item) where REC-1 isfollowed by a variably located group (a type of complex ODO), the actual length ofREC-1 is calculated immediately be<strong>for</strong>e the move, using the current value of theODO object (FIELD-1). In the following example, REC-1 and REC-2 are in the samerecord, but REC-2 is not subordinate to REC-1 and is there<strong>for</strong>e variably located:01 MAIN-AREA03 REC-1.05 FIELD-1 PIC 9.05 FIELD-3 PIC 9.05 FIELD-2 OCCURS 1 TO 5 TIMESDEPENDING ON FIELD-1 PIC X(05).Chapter 4. Handling tables 81


03 REC-2.05 FIELD-4 OCCURS 1 TO 5 TIMESDEPENDING ON FIELD-3PIC 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 be<strong>for</strong>e using the groupitem as a receiving field.The following example shows how to define a variable-length table when the ODOobject (LOCATION-TABLE-LENGTH below) is outside the group:DATA DIVISION.FILE SECTION.FDLOCATION-FILERECORDING MODE FBLOCK 0 RECORDSRECORD 80 CHARACTERSLABEL 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.******************************************************************** LOCATION TABLE ****** FILE CONTAINS LOCATION CODES. ********************************************************************01 LOCATION-TABLE.05 LOCATION-CODE OCCURS 1 TO 100 TIMESDEPENDING ON LOCATION-TABLE-LENGTHPIC X(80).RELATED CONCEPTSAppendix B, “Complex OCCURS DEPENDING ON,” on page 697RELATED TASKS“Assigning values to a variable-length table” on page 83“Loading a variable-length table”“Preventing overlay when adding elements to a variable table” on page 699“Finding the length of data items” on page 118<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong>RELATED REFERENCESOCCURS DEPENDING ON clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Loading a variable-length tableYou can use a do-until structure (a TEST AFTER loop) to control the loading of avariable-length table. For example, after the following code runs,LOCATION-TABLE-LENGTH contains the subscript of the last item in the table.DATA DIVISION.FILE SECTION.FD LOCATION-FILERECORDING MODE FBLOCK 0 RECORDSRECORD 80 CHARACTERSLABEL RECORD STANDARD.82 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


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.******************************************************************** LOCATION TABLE ****** FILE CONTAINS LOCATION CODES. ********************************************************************01 LOCATION-TABLE.05 LOCATION-CODE OCCURS 1 TO 100 TIMESDEPENDING ON LOCATION-TABLE-LENGTH PIC X(80)....PROCEDURE DIVISION....Per<strong>for</strong>m Test AfterVarying Location-Table-Length From 1 By 1Until Location-EOFOr Location-Table-Length = Location-Table-MaxMove Location-Record ToLocation-Code (Location-Table-Length)Read Location-FileAt End Set Location-EOF To TrueEnd-ReadEnd-Per<strong>for</strong>mAssigning values to a variable-length tableYou can code a VALUE clause <strong>for</strong> an alphanumeric or national group item that has asubordinate data item that contains the OCCURS clause with the DEPENDING ONphrase. Each subordinate structure that contains the DEPENDING ON phrase isinitialized using the maximum number of occurrences.If you define the entire table by using the DEPENDING ON phrase, all the elementsare initialized using the maximum defined value of the ODO (OCCURS DEPENDINGON) object.If the ODO object is initialized by a VALUE clause, it is logically initialized after theODO subject has been initialized.01 TABLE-THREE VALUE "3ABCDE".05 X PIC 9.05 Y OCCURS 5 TIMESDEPENDING ON X PIC X.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 subsequentreference to TABLE-THREE (such as in a DISPLAY statement) refers to X and the firstthree elements, Y(1) through Y(3), of the table.RELATED TASKS“Assigning values when you define a table (VALUE)” on page 77RELATED REFERENCESOCCURS DEPENDING ON clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 4. Handling tables 83


Searching a table<strong>COBOL</strong> provides two search techniques <strong>for</strong> tables: serial and binary.To do serial searches, use SEARCH and indexing. For variable-length tables, you canuse PERFORM with subscripting or indexing.To do binary searches, use SEARCH ALL and indexing.A binary search can be considerably more efficient than a serial search. For a serialsearch, the number of comparisons is of the order of n, the number of entries inthe table. For a binary search, the number of comparisons is of the order of onlythe logarithm (base 2) of n. A binary search, however, requires that the table itemsalready be sorted.RELATED TASKS“Doing a serial search (SEARCH)”“Doing a binary search (SEARCH ALL)” on page 85Doing a serial search (SEARCH)Use the SEARCH statement to do a serial (sequential) search beginning at the currentindex setting. To modify the index setting, use the SET statement.The conditions in the WHEN phrase are evaluated in the order in which they appear:v If none of the conditions is satisfied, the index is increased to correspond to thenext table element, and the WHEN conditions are evaluated again.v If one of the WHEN conditions is satisfied, the search ends. The index remainspointing to the table element that satisfied the condition.v If the entire table has been searched and no conditions were met, the AT ENDimperative statement is executed if there is one. If you did not code AT END,control passes to the next statement in the program.You can reference only one level of a table (a table element) with each SEARCHstatement. To search multiple levels of a table, use nested SEARCH statements.Delimit each nested SEARCH statement with END-SEARCH.Per<strong>for</strong>mance: If the found condition comes after some intermediate point in thetable, you can speed up the search by using the SET statement to set the index tobegin the search after that point. Arranging the table so that the data used mostoften is at the beginning of the table also enables more efficient serial searching. Ifthe table is large and is presorted, a binary search is more efficient.“Example: serial search”RELATED REFERENCESSEARCH statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: serial searchThe following example shows how you might find a particular string in theinnermost table of a three-dimensional table.84 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Each dimension of the table has its own index (set to 1, 4, and 1, respectively). Theinnermost table (TABLE-ENTRY3) has an ascending key.01 TABLE-ONE.05 TABLE-ENTRY1 OCCURS 10 TIMESINDEXED BY TE1-INDEX.10 TABLE-ENTRY2 OCCURS 10 TIMESINDEXED BY TE2-INDEX.15 TABLE-ENTRY3 OCCURS 5 TIMESASCENDING KEY IS KEY1INDEXED BY TE3-INDEX.20 KEY1 PIC X(5).20 KEY2 PIC X(10)....PROCEDURE DIVISION....SET TE1-INDEX TO 1SET TE2-INDEX TO 4SET TE3-INDEX TO 1MOVE "A1234" TO KEY1 (TE1-INDEX, TE2-INDEX, TE3-INDEX + 2)MOVE "AAAAAAAA00" TO KEY2 (TE1-INDEX, TE2-INDEX, TE3-INDEX + 2)...SEARCH TABLE-ENTRY3AT ENDMOVE 4 TO RETURN-CODEWHEN TABLE-ENTRY3(TE1-INDEX, TE2-INDEX, TE3-INDEX)= "A1234AAAAAAAA00"MOVE 0 TO RETURN-CODEEND-SEARCHValues after execution:TE1-INDEX = 1TE2-INDEX = 4TE3-INDEX points to the TABLE-ENTRY3 itemthat equals "A1234AAAAAAAA00"RETURN-CODE = 0Doing a binary search (SEARCH ALL)If you use SEARCH ALL to do a binary search, you do not need to set the indexbe<strong>for</strong>e you begin. The index is always the one that is associated with the firstindex-name in the OCCURS clause. The index varies during execution to maximizethe search efficiency.To use the SEARCH ALL statement to search a table, the table must specify theASCENDING or DESCENDING KEY phrases of the OCCURS clause, or both, and mustalready be ordered on the key or keys that are specified in the ASCENDING andDESCENDING KEY phrases.In the WHEN phrase of the SEARCH ALL statement, you can test any key that is namedin the ASCENDING or DESCENDING KEY phrases <strong>for</strong> the table, but you must test allpreceding keys, if any. The test must be an equal-to condition, and the WHEN phrasemust specify either a key (subscripted by the first index-name associated with thetable) or a condition-name that is associated with the key. The WHEN condition canbe a compound condition that is <strong>for</strong>med from simple conditions that use AND as theonly logical connective.Each key and its object of comparison must be compatible according to the rules<strong>for</strong> comparison of data items. Note though that if a key is compared to a nationalliteral or identifier, the key must be a national data item.Chapter 4. Handling tables 85


“Example: binary search”RELATED TASKS“Defining a table (OCCURS)” on page 69RELATED REFERENCESSEARCH statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)General relation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: binary searchThe following example shows how you can code a binary search of a table.Suppose you define a table that contains 90 elements of 40 bytes each, and threekeys. The primary and secondary keys (KEY-1 and KEY-2) are in ascending order,but the least significant key (KEY-3) is in descending order:01 TABLE-A.05 TABLE-ENTRY OCCURS 90 TIMESASCENDING KEY-1, KEY-2DESCENDING KEY-3INDEXED BY INDX-1.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).You can search this table by using the following statements:SEARCH ALL TABLE-ENTRYAT ENDPERFORM NOENTRYWHEN KEY-1 (INDX-1) = VALUE-1 ANDKEY-2 (INDX-1) = VALUE-2 ANDKEY-3 (INDX-1) = VALUE-3MOVE PART-1 (INDX-1) TO OUTPUT-AREAEND-SEARCHIf an entry is found in which each of the three keys is equal to the value to whichit is compared (VALUE-1, VALUE-2, and VALUE-3, respectively), PART-1 of that entry ismoved to OUTPUT-AREA. If no matching key is found in the entries in TABLE-A, theNOENTRY routine is per<strong>for</strong>med.Processing table items using intrinsic functionsYou can use intrinsic functions to process alphabetic, alphanumeric, national, ornumeric table items. (You can process DBCS data items only with the NATIONAL-OFintrinsic function.) The data descriptions of the table items must be compatiblewith the requirements <strong>for</strong> the function arguments.Use a subscript or index to reference an individual data item as a functionargument. For example, assuming that Table-One isa3x3array of numeric items,you can find the square root of the middle element by using this statement:Compute X = Function Sqrt(Table-One(2,2))You might often need to iteratively process the data in tables. For intrinsicfunctions that accept multiple arguments, you can use the subscript ALL to86 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


eference all the items in the table or in a single dimension of the table. Theiteration is handled automatically, which can make your code shorter and simpler.You can mix scalars and array arguments <strong>for</strong> functions that accept multiplearguments:Compute Table-Median = Function Median(Arg1 Table-One(ALL))“Example: processing tables using intrinsic functions”RELATED TASKS“Using intrinsic functions (built-in functions)” on page 40“Converting data items (intrinsic functions)” on page 112“Evaluating data items (intrinsic functions)” on page 115RELATED REFERENCESIntrinsic functions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: processing tables using intrinsic functionsThese examples show how you can apply an intrinsic function to some or all of theelements in a table by using the ALL subscript.Assuming that Table-Two isa2x3x2array, the following statement adds thevalues in elements Table-Two(1,3,1), Table-Two(1,3,2), Table-Two(2,3,1), andTable-Two(2,3,2):Compute Table-Sum = FUNCTION SUM (Table-Two(ALL, 3, ALL))The following example computes various salary values <strong>for</strong> all the employeeswhose salaries are encoded in Employee-Table:01 Employee-Table.05 Emp-Count Pic s9(4) usage binary.05 Emp-Record Occurs 1 to 500 timesdepending 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))Chapter 4. Handling tables 87


88 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 5. Selecting and repeating program actionsUse <strong>COBOL</strong> control language to choose program actions based on the outcome oflogical tests, to iterate over selected parts of your program and data, and toidentify statements to be per<strong>for</strong>med as a group.These controls include the IF, EVALUATE, and PERFORM statements, and the use ofswitches and flags.Selecting program actionsRELATED TASKS“Selecting program actions”“Repeating program actions” on page 97You can provide <strong>for</strong> different program actions depending on the tested value ofone or more data items.The IF and EVALUATE statements in <strong>COBOL</strong> test one or more data items by meansof a conditional expression.RELATED TASKS“Coding a choice of actions”“Coding conditional expressions” on page 94RELATED REFERENCESIF statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)EVALUATE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Coding a choice of actionsUse IF...ELSE to code a choice between two processing actions. (The wordTHEN is optional.) Use the EVALUATE statement to code a choice among three ormore possible actions.IF condition-pstatement-1ELSEstatement-2END-IFWhen one of two processing choices is no action, code the IF statement with orwithout ELSE. Because the ELSE clause is optional, you can code the IF statement asfollows:IF condition-qstatement-1END-IFSuch coding is suitable <strong>for</strong> simple cases. For complex logic, you probably need touse the ELSE clause. For example, suppose you have nested IF statements in whichthere is an action <strong>for</strong> only one of the processing choices. You could use the ELSEclause and code the null branch of the IF statement with the CONTINUE statement:© Copyright IBM Corp. 1991, 2009 89


IF condition-qstatement-1ELSECONTINUEEND-IFThe EVALUATE statement is an expanded <strong>for</strong>m of the IF statement that allows you toavoid nesting IF statements, a common source of logic errors and debuggingproblems.RELATED TASKS“Using nested IF statements”“Using the EVALUATE statement” on page 91“Coding conditional expressions” on page 94Using nested IF statementsWhen an IF statement contains an IF statement as one of its possible branches, theIF statements are said to be nested. Theoretically, there is no limit to the depth ofnested IF statements.However, use nested IF statements sparingly. The logic can be difficult to follow,although explicit scope terminators and indentation help. When a program has totest a variable <strong>for</strong> more than two values, EVALUATE is probably a better choice.The following pseudocode depicts a nested IF statement:IF condition-pIF condition-qstatement-1ELSEstatement-2END-IFstatement-3ELSEstatement-4END-IFIn the pseudocode above, an IF statement and a sequential structure are nested inone branch of the outer IF. In this structure, the END-IF that closes the nested IF isvery important. Use END-IF instead of a period, because a period would end theouter IF structure also.The following figure shows the logic structure of the pseudocode above.90 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Coding a choice of actions” on page 89RELATED REFERENCESExplicit scope terminators (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using the EVALUATE statementYou can use the EVALUATE statement instead of a series of nested IF statements totest several conditions and specify a different action <strong>for</strong> each. Thus you can use theEVALUATE statement to implement a case structure or decision table.You can also use the EVALUATE statement to cause multiple conditions to lead to thesame processing, as shown in these examples:“Example: EVALUATE using THRU phrase” on page 92“Example: EVALUATE using multiple WHEN phrases” on page 92In an EVALUATE statement, the operands be<strong>for</strong>e the WHEN phrase are referred to asselection subjects, and the operands in the WHEN phrase are called the selection objects.Selection subjects can be identifiers, literals, conditional expressions, or the wordTRUE or FALSE. Selection objects can be identifiers, literals, conditional or arithmeticexpressions, or the word TRUE, FALSE, orANY.You can separate multiple selection subjects with the ALSO phrase. You can separatemultiple selection objects with the ALSO phrase. The number of selection objectswithin each set of selection objects must be equal to the number of selectionsubjects, as shown in this example:“Example: EVALUATE testing several conditions” on page 93Identifiers, literals, or arithmetic expressions that appear within a selection objectmust be valid operands <strong>for</strong> comparison to the corresponding operand in the set ofselection subjects. Conditions or the word TRUE or FALSE that appear in a selectionChapter 5. Selecting and repeating program actions 91


object must correspond to a conditional expression or the word TRUE or FALSE inthe set of selection subjects. (You can use the word ANY as a selection object tocorrespond to any type of selection subject.)The execution of the EVALUATE statement ends when one of the followingconditions occurs:v The statements associated with the selected WHEN phrase are per<strong>for</strong>med.v The statements associated with the WHEN OTHER phrase are per<strong>for</strong>med.v No WHEN conditions are satisfied.WHEN phrases are tested in the order that they appear in the source program.There<strong>for</strong>e, you should order these phrases <strong>for</strong> the best per<strong>for</strong>mance. First code theWHEN phrase that contains selection objects that are most likely to be satisfied, thenthe next most likely, and so on. An exception is the WHEN OTHER phrase, which mustcome last.RELATED TASKS“Coding a choice of actions” on page 89RELATED REFERENCESEVALUATE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)General relation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: EVALUATE using THRU phrase:This example shows how you can code several conditions in a range of values tolead to the same processing action by coding the THRU phrase. Operands in a THRUphrase must be of the same class.In this example, CARPOOL-SIZE is the selection subject; 1, 2, and 3 THRU 6 are theselection objects:EVALUATE CARPOOL-SIZEWHEN 1MOVE "SINGLE" TO PRINT-CARPOOL-STATUSWHEN 2MOVE "COUPLE" TO PRINT-CARPOOL-STATUSWHEN 3 THRU 6MOVE "SMALL GROUP" TO PRINT-CARPOOL STATUSWHEN OTHERMOVE "BIG GROUP" TO PRINT-CARPOOL STATUSEND-EVALUATEThe following nested IF statements represent the same logic:IF CARPOOL-SIZE = 1 THENMOVE "SINGLE" TO PRINT-CARPOOL-STATUSELSEIF CARPOOL-SIZE = 2 THENMOVE "COUPLE" TO PRINT-CARPOOL-STATUSELSEIF CARPOOL-SIZE >= 3 and CARPOOL-SIZE


The following example shows that you can code multiple WHEN phrases if severalconditions should lead to the same action. Doing so gives you more flexibility thanusing only the THRU phrase, because the conditions do not have to evaluate tovalues in a range nor have the same class.EVALUATE MARITAL-CODEWHEN "M"ADD 2 TO PEOPLE-COUNTWHEN "S"WHEN "D"WHEN "W"ADD 1 TO PEOPLE-COUNTEND-EVALUATEThe following nested IF statements represent the same logic:IF MARITAL-CODE = "M" THENADD 2 TO PEOPLE-COUNTELSEIF MARITAL-CODE = "S" ORMARITAL-CODE = "D" ORMARITAL-CODE = "W" THENADD 1 TO PEOPLE-COUNTEND-IFEND-IFExample: EVALUATE testing several conditions:This example shows the use of the ALSO phrase to separate two selection subjects(True ALSO True) and to separate the two corresponding selection objects withineach set of selection objects (<strong>for</strong> example, WhenA+B 12 And Age < 20 Also Sex = "M"Move "Teenage Boy" To DescriptionWhen Age > 12 And Age < 20 Also Sex = "F"Move "Teenage Girl" To DescriptionWhen Age > 19 Also Sex = "M"Move "Adult Man" To DescriptionWhen Age > 19 Also Sex = "F"Chapter 5. Selecting and repeating program actions 93


Move "Adult Woman" To DescriptionWhen OtherMove "Invalid Data" To DescriptionEnd-EvaluateEvaluate True Also TrueWhenA+B50AlsoC=(D+E)/FMove "Case 2" To DescriptionWhen OtherMove "Case Other" To DescriptionEnd-EvaluateStop Run.Coding conditional expressionsUsing the IF and EVALUATE statements, you can code program actions that will beper<strong>for</strong>med depending on the truth value of a conditional expression.The following are some of the conditions that you can specify:v Relation conditions, such as:– Numeric comparisons– Alphanumeric comparisons– DBCS comparisons– National comparisonsv Class conditions; <strong>for</strong> example, to test whether a data item:– IS NUMERIC– IS ALPHABETIC– IS DBCS– IS KANJI– IS NOT KANJIv Condition-name conditions, to test the value of a conditional variable that youdefinev Sign conditions, to test whether a numeric operand IS P<strong>OS</strong>ITIVE, NEGATIVE, orZEROv Switch-status conditions, to test the status of UPSI switches that you name in theSPECIAL-NAMES paragraphv Complex conditions, such as:– Negated conditions; <strong>for</strong> example, NOT (A IS EQUAL TO B)– Combined conditions (conditions combined with logical operators AND or OR)RELATED CONCEPTS“Switches and flags” on page 95RELATED TASKS“Defining switches and flags” on page 95“Resetting switches and flags” on page 96“Checking <strong>for</strong> incompatible data (numeric class test)” on page 56“Comparing national (UTF-16) data” on page 139“Testing <strong>for</strong> valid DBCS characters” on page 143RELATED REFERENCESGeneral relation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)94 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Class condition (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Rules <strong>for</strong> condition-name entries (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Sign condition (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Combined conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Switches and flagsSome program decisions are based on whether the value of a data item is true orfalse, on or off, yes or no. Control these two-way decisions by using level-88 itemswith meaningful names (condition-names) to act as switches.Other program decisions depend on the particular value or range of values of adata item. When you use condition-names to give more than just on or off valuesto a field, the field is generally referred to as a flag.Flags and switches make your code easier to change. If you need to change thevalues <strong>for</strong> a condition, you have to change only the value of that level-88condition-name.For example, suppose a program uses a condition-name to test a field <strong>for</strong> a givensalary range. If the program must be changed to check <strong>for</strong> a different salary range,you need to change only the value of the condition-name in the DATA DIVISION.You do not need to make changes in the PROCEDURE DIVISION.RELATED TASKS“Defining switches and flags”“Resetting switches and flags” on page 96Defining switches and flagsIn the DATA DIVISION, define level-88 items that will act as switches or flags, andgive them meaningful names.To test <strong>for</strong> more than two values with flags, assign more than one condition-nameto a field by using multiple level-88 items.The reader can easily follow your code if you choose meaningful condition-namesand if the values assigned to them have some association with logical values.“Example: switches”“Example: flags” on page 96Example: switchesThe following examples show how you can use level-88 items to test <strong>for</strong> variousbinary-valued (on-off) conditions in your program.For example, to test <strong>for</strong> the end-of-file condition <strong>for</strong> an input file namedTransaction-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 turned onwhen Transaction-EOF-Switch has value ’y’. Referencing Transaction-EOF in thePROCEDURE DIVISION expresses the same condition as testing Transaction-EOF-Chapter 5. Selecting and repeating program actions 95


Switch = "y". For example, the following statement causes a report to be printedonly if Transaction-EOF-Switch has been set to ’y’:If Transaction-EOF ThenPer<strong>for</strong>m Print-Report-Summary-LinesExample: flagsThe following examples show how you can use several level-88 items togetherwith an EVALUATE statement to determine which of several conditions in a programis true.Consider <strong>for</strong> example a program that updates a master file. The updates are readfrom a transaction file. The records in the file contain a field that indicates whichof the three functions is to be per<strong>for</strong>med: add, change, or delete. In the recorddescription of the input file, code a field <strong>for</strong> the function code using level-88 items:01 Transaction-Input Record05 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 <strong>for</strong> testing these condition-names to determinewhich function is to be per<strong>for</strong>med might look like this:Evaluate TrueWhen Add-TransactionPer<strong>for</strong>m Add-Master-Record-ParagraphWhen Change-TransactionPer<strong>for</strong>m Update-Existing-Record-ParagraphWhen Delete-TransactionPer<strong>for</strong>m Delete-Master-Record-ParagraphEnd-EvaluateResetting switches and flagsThroughout your program, you might need to reset switches or flags to theoriginal values they had in their data descriptions. To do so, either use a SETstatement or define a data item to move to the switch or flag.When you use the SET condition-name TO TRUE statement, the switch or flag is set tothe original value that it was assigned in its data description. For a level-88 itemthat has multiple values, SET condition-name TO TRUE assigns the first value (A in theexample below):88 Record-is-Active Value "A" "O" "S"Using the SET statement and meaningful condition-names makes it easier <strong>for</strong>readers to follow your code.“Example: set switch on”“Example: set switch off” on page 97Example: set switch onThe following examples show how you can set a switch on by coding a SETstatement that moves the value TRUE to a level-88 item.For example, the SET statement in the following example has the same effect ascoding the statement Move "y" to Transaction-EOF-Switch:96 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


01 Switches05 Transaction-EOF-Switch Pic X Value space.88 Transaction-EOF Value "y"....Procedure Division.000-Do-Main-Logic.Per<strong>for</strong>m 100-Initialize-ParagraphRead Update-Transaction-FileAt End Set Transaction-EOF to TrueEnd-ReadThe following example shows how to assign a value to a field in an output recordbased 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-RecordWhen "ACTIVE"Set Record-Is-Active to TRUEWhen "SUSPENDED"Set Record-Is-Suspended to TRUEWhen "DELETED"Set Record-Is-Deleted to TRUEEnd-EvaluateExample: set switch offRepeating program actionsThe following example shows how you can set a switch off by coding a MOVEstatement that moves a value to a level-88 item.For example, you can use a data item called SWITCH-OFF to set an on-off switch tooff, as in the following code, which resets a switch to indicate that end-of-file hasnot been reached:01 Switches05 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-SwitchUse a PERFORM statement to repeat the same code (that is, loop) either a specifiednumber of times or based on the outcome of a decision.You can also use a PERFORM statement to execute a paragraph and then implicitlyreturn control to the next executable statement. In effect, this PERFORM statement isa way of coding a closed subroutine that you can enter from many different partsof the program.PERFORM statements can be inline or out-of-line.Chapter 5. Selecting and repeating program actions 97


RELATED TASKS“Choosing inline or out-of-line PERFORM”“Coding a loop” on page 99“Looping through a table” on page 100“Executing multiple paragraphs or sections” on page 100RELATED REFERENCESPERFORM statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Choosing inline or out-of-line PERFORMAn inline PERFORM is an imperative statement that is executed in the normal flow ofa program; an out-of-line PERFORM entails a branch to a named paragraph and animplicit return from that paragraph.To determine whether to code an inline or out-of-line PERFORM statement, answerthe following questions:v Is the PERFORM statement used in several places?Use an out-of-line PERFORM when you want to use the same portion of code inseveral places in your program.v Which placement of the statement will be easier to read?If the code to be per<strong>for</strong>med is short, an inline PERFORM can be easier to read. Butif the code extends over several screens, the logical flow of the program mightbe clearer if you use an out-of-line PERFORM. (Each paragraph in structuredprogramming should per<strong>for</strong>m one logical function, however.)v What are the efficiency tradeoffs?An inline PERFORM avoids the overhead of branching that occurs with anout-of-line PERFORM. But even out-of-line PERFORM coding can improve codeoptimization, so efficiency gains should not be overemphasized.In the 1974 <strong>COBOL</strong> standard, the PERFORM statement is out-of-line and thus requiresa branch to a separate paragraph and an implicit return. If the per<strong>for</strong>medparagraph is in the subsequent sequential flow of your program, it is also executedin that logic flow. To avoid this additional execution, place the paragraph outsidethe normal sequential flow (<strong>for</strong> example, after the GOBACK) or code a branch aroundit.The subject of an inline PERFORM is an imperative statement. There<strong>for</strong>e, you mustcode statements (other than imperative statements) within an inline PERFORM withexplicit scope terminators.“Example: inline PERFORM statement”Example: inline PERFORM statementThis example shows the structure of an inline PERFORM statement that has therequired scope terminators and the required END-PERFORM phrase.Per<strong>for</strong>m 100-Initialize-Paragraph* The following statement is an inline PERFORM:Per<strong>for</strong>m Until Transaction-EOFRead Update-Transaction-File Into WS-Transaction-RecordAt EndSet Transaction-EOF To TrueNot At EndPer<strong>for</strong>m 200-Edit-Update-TransactionIf No-ErrorsPer<strong>for</strong>m 300-Update-Commuter-Record98 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


ElsePer<strong>for</strong>m 400-Print-Transaction-Errors* End-If is a required scope terminatorEnd-IfPer<strong>for</strong>m 410-Re-Initialize-Fields* End-Read is a required scope terminatorEnd-ReadEnd-Per<strong>for</strong>mCoding a loopUse the PERFORM ...TIMES statement to execute a paragraph a specified numberof times.PERFORM 010-PROCESS-ONE-MONTH 12 TIMESINSPECT ...In the example above, when control reaches the PERFORM statement, the code <strong>for</strong> theparagraph 010-PROCESS-ONE-MONTH is executed 12 times be<strong>for</strong>e control is transferredto the INSPECT statement.Use the PERFORM ...UNTIL statement to execute a paragraph until a conditionyou choose is satisfied. You can use either of the following <strong>for</strong>ms:PERFORM ...WITH TEST AFTER ....UNTIL ...PERFORM ...[WITH TEST BEFORE] ...UNTIL ...Use the PERFORM ...WITH TEST AFTER ...UNTIL statement if you want toexecute the paragraph at least once, and test be<strong>for</strong>e any subsequent execution. Thisstatement is equivalent to a do-until structure:In the following example, the implicit WITH TEST BEFORE phrase provides ado-while structure:PERFORM 010-PROCESS-ONE-MONTHUNTIL MONTH GREATER THAN 12INSPECT ...When control reaches the PERFORM statement, the condition MONTH GREATER THAN 12is tested. If the condition is satisfied, control is transferred to the INSPECTstatement. If the condition is not satisfied, 010-PROCESS-ONE-MONTH is executed, andthe 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 TESTBEFORE clause.)Chapter 5. Selecting and repeating program actions 99


Looping through a tableYou can use the PERFORM ...VARYING statement to initialize a table. In this <strong>for</strong>mof the PERFORM statement, a variable is increased or decreased and tested until acondition is satisfied.Thus you use the PERFORM statement to control looping through a table. You canuse either of these <strong>for</strong>ms:PERFORM ...WITH TEST AFTER ....VARYING ...UNTIL ...PERFORM ...[WITH TEST BEFORE] ...VARYING ...UNTIL ...The following section of code shows an example of looping through a table tocheck <strong>for</strong> invalid data:PERFORM TEST AFTER VARYING WS-DATA-IXFROM 1 BY 1 UNTIL WS-DATA-IX = 12IF WS-DATA (WS-DATA-IX) EQUALS SPACESSET SERIOUS-ERROR TO TRUEDISPLAY ELEMENT-NUM-MSG5END-IFEND-PERFORMINSPECT ...When control reaches the PERFORM statement above, WS-DATA-IX is set equal to 1and the PERFORM statement is executed. Then the condition WS-DATA-IX = 12 istested. If the condition is true, control drops through to the INSPECT statement. Ifthe condition is false, WS-DATA-IX is increased by 1, the PERFORM statement isexecuted, and the condition is tested again. This cycle of execution and testingcontinues until WS-DATA-IX is equal to 12.The loop above controls input-checking <strong>for</strong> the 12 fields of item WS-DATA. Emptyfields are not allowed in the application, so the section of code loops and issueserror messages as appropriate.Executing multiple paragraphs or sectionsIn structured programming, you usually execute a single paragraph. However, youcan execute a group of paragraphs, or a single section or group of sections, bycoding the PERFORM ...THRU statement.When you use the PERFORM ...THRU statement, code a paragraph-EXIT statementto clearly indicate the end point of a series of paragraphs.RELATED TASKS“Processing table items using intrinsic functions” on page 86100 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 6. Handling strings<strong>COBOL</strong> provides language constructs <strong>for</strong> per<strong>for</strong>ming many different operations onstring data items.For example, you can:v Join or split data items.v Manipulate null-terminated strings, such as count or move characters.v Refer to substrings by their ordinal position and, if needed, length.v Tally and replace data items, such as count the number of times a specificcharacter occurs in a data item.v Convert data items, such as change to uppercase or lowercase.v Evaluate data items, such as determine the length of a data item.Joining data items (STRING)RELATED TASKS“Joining data items (STRING)”“Splitting data items (UNSTRING)” on page 103“Manipulating null-terminated strings” on page 106“Referring to substrings of data items” on page 107“Tallying and replacing data items (INSPECT)” on page 111“Converting data items (intrinsic functions)” on page 112“Evaluating data items (intrinsic functions)” on page 115Chapter 7, “Processing data in an international environment,” on page 121Use the STRING statement to join all or parts of several data items or literals intoone data item. One STRING statement can take the place of several MOVE statements.The STRING statement transfers data into a receiving data item in the order that youindicate. In the STRING statement you also specify:vvvA delimiter <strong>for</strong> each set of sending fields that, if encountered, causes thosesending fields to stop being transferred (DELIMITED BY phrase)(Optional) Action to be taken if the receiving field is filled be<strong>for</strong>e all of thesending data has been processed (ON OVERFLOW phrase)(Optional) An integer data item that indicates the leftmost character positionwithin the receiving field into which data should be transferred (WITH POINTERphrase)The receiving data item must not be an edited item, or a display or nationalfloating-point item. If the receiving data item has:vvvUSAGE DISPLAY, each identifier in the statement except the POINTER identifiermust have USAGE DISPLAY, and each literal in the statement must bealphanumericUSAGE NATIONAL, each identifier in the statement except the POINTER identifiermust have USAGE NATIONAL, and each literal in the statement must be nationalUSAGE DISPLAY-1, each identifier in the statement except the POINTER identifiermust have USAGE DISPLAY-1, and each literal in the statement must be DBCS© Copyright IBM Corp. 1991, 2009 101


Only that portion of the receiving field into which data is written by the STRINGstatement is changed.“Example: STRING statement”RELATED TASKS“Handling errors in joining and splitting strings” on page 234RELATED REFERENCESSTRING statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: STRING statementThe following example shows the STRING statement selecting and <strong>for</strong>mattingin<strong>for</strong>mation from a record into an output line.The FILE SECTION defines the following record: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 WORKING-STORAGE SECTION defines the following fields:77 RPT-LINE PIC X(120).77 LINE-P<strong>OS</strong> PIC S9(3).77 LINE-NO PIC 9(5) VALUE 1.77 DEC-POINT PIC X VALUE ".".The record RCD-01 contains the following in<strong>for</strong>mation (the symbol b indicates ablank space):J.B.bSMITHbbbbb444bSPRINGbST.,bCHICAGO,bILL.bbbbbbA14275$4,736.85$2,400.0009/22/76$2,336.8510/22/76In the PROCEDURE DIVISION, these settings occur be<strong>for</strong>e the STRING statement:v RPT-LINE is set to SPACES.v LINE-P<strong>OS</strong>, the data item to be used as the POINTER field, is set to 4.Here is the STRING statement:STRINGLINE-NO SPACE CUST-INFO INV-NO SPACE DATE-DUE SPACEDELIMITED BY SIZEBAL-DUEDELIMITED BY DEC-POINTINTO RPT-LINEWITH POINTER LINE-P<strong>OS</strong>.102 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Because the POINTER field LINE-P<strong>OS</strong> has value 4 be<strong>for</strong>e the STRING statement isper<strong>for</strong>med, data is moved into the receiving field RPT-LINE beginning at characterposition 4. Characters in positions 1 through 3 are unchanged.The sending items that specify DELIMITED BY SIZE are moved in their entirety tothe receiving field. Because BAL-DUE is delimited by DEC-POINT, the moving ofBAL-DUE to the receiving field stops when a decimal point (the value of DEC-POINT)is encountered.STRING resultsWhen the STRING statement is per<strong>for</strong>med, items are moved into RPT-LINE as shownin the table below.ItemPositionsLINE-NO 4-8Space 9CUST-INFO 10-59INV-NO 60-65Space 66DATE-DUE 67-74Space 75Portion of BAL-DUE that precedes the decimal point 76 - 81After the STRING statement is per<strong>for</strong>med, the value of LINE-P<strong>OS</strong> is 82, and RPT-LINEhas the values shown below.Splitting data items (UNSTRING)Use the UNSTRING statement to split a sending field into several receiving fields.One UNSTRING statement can take the place of several MOVE statements.In the UNSTRING statement you can specify:v Delimiters that, when one of them is encountered in the sending field, cause thecurrent receiving field to stop receiving and the next, if any, to begin receiving(DELIMITED BY phrase)v A field <strong>for</strong> the delimiter that, when encountered in the sending field, causes thecurrent receiving field to stop receiving (DELIMITER IN phrase)v An integer data item that stores the number of characters placed in the currentreceiving field (COUNT IN phrase)v An integer data item that indicates the leftmost character position within thesending field at which UNSTRING processing should begin (WITH POINTER phrase)v An integer data item that stores a tally of the number of receiving fields that areacted on (TALLYING IN phrase)Chapter 6. Handling strings 103


vAction to be taken if all of the receiving fields are filled be<strong>for</strong>e the end of thesending data item is reached (ON OVERFLOW phrase)The sending data item and the delimiters in the DELIMITED BY phrase must be ofcategory alphabetic, alphanumeric, alphanumeric-edited, DBCS, national, ornational-edited.Receiving data items can be of category alphabetic, alphanumeric, numeric, DBCS,or national. If numeric, a receiving data item must be zoned decimal or nationaldecimal. If a receiving data item has:vvvUSAGE DISPLAY, the sending item and each delimiter item in the statement musthave USAGE DISPLAY, and each literal in the statement must be alphanumericUSAGE NATIONAL, the sending item and each delimiter item in the statement musthave USAGE NATIONAL, and each literal in the statement must be nationalUSAGE DISPLAY-1, the sending item and each delimiter item in the statementmust have USAGE DISPLAY-1, and each literal in the statement must be DBCS“Example: UNSTRING statement”RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED TASKS“Handling errors in joining and splitting strings” on page 234RELATED REFERENCESUNSTRING statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: UNSTRING statementThe following example shows the UNSTRING statement transferring selectedin<strong>for</strong>mation from an input record. Some in<strong>for</strong>mation is organized <strong>for</strong> printing andsome <strong>for</strong> further processing.The FILE SECTION defines the following records:* Record to be acted on by the UNSTRING statement:01 INV-RCD.05 CONTROL-CHARS PIC XX.05 ITEM-INDENT PIC X(20).05 FILLER PIC X.05 INV-CODE PIC X(10).05 FILLER PIC X.05 NO-UNITS PIC 9(6).05 FILLER PIC X.05 PRICE-PER-M PIC 99999.05 FILLER PIC X.05 RTL-AMT PIC 9(6).99.** UNSTRING receiving field <strong>for</strong> printed output:01 DISPLAY-REC.05 INV-NO PIC X(6).05 FILLER PIC X VALUE SPACE.05 ITEM-NAME PIC X(20).05 FILLER PIC X VALUE SPACE.05 DISPLAY-DOLS PIC 9(6).** UNSTRING receiving field <strong>for</strong> further processing:104 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


01 WORK-REC.05 M-UNITS PIC 9(6).05 FIELD-A PIC 9(6).05 WK-PRICE REDEFINES FIELD-A PIC 9999V99.05 INV-CLASS PIC X(3).** UNSTRING statement control fields:77 DBY-1 PIC X.77 CTR-1 PIC S9(3).77 CTR-2 PIC S9(3).77 CTR-3 PIC S9(3).77 CTR-4 PIC S9(3).77 DLTR-1 PIC X.77 DLTR-2 PIC X.77 CHAR-CT PIC S9(3).77 FLDS-FILLED PIC S9(3).In the PROCEDURE DIVISION, these settings occur be<strong>for</strong>e the UNSTRING statement:v A period (.) is placed in DBY-1 <strong>for</strong> use as a delimiter.v CHAR-CT (the POINTER field) is set to 3.v The value zero (0) is placed in FLDS-FILLED (the TALLYING field).v Data is read into record INV-RCD, whose <strong>for</strong>mat is as shown below.Here is the UNSTRING statement:* Move subfields of INV-RCD to the subfields of DISPLAY-REC* and WORK-REC:UNSTRING INV-RCDDELIMITED BY ALL SPACES OR "/" OR DBY-1INTO ITEM-NAME COUNT IN CTR-1INV-NO DELIMITER IN DLTR-1 COUNT IN CTR-2INV-CLASSM-UNITS COUNT IN CTR-3FIELD-ADISPLAY-DOLS DELIMITER IN DLTR-2 COUNT IN CTR-4WITH POINTER CHAR-CTTALLYING IN FLDS-FILLEDON OVERFLOW GO TO UNSTRING-COMPLETE.Because the POINTER field CHAR-CT has value 3 be<strong>for</strong>e the UNSTRING statement isper<strong>for</strong>med, the two character positions of the CONTROL-CHARS field in INV-RCD areignored.UNSTRING resultsWhen the UNSTRING statement is per<strong>for</strong>med, the following steps take place:1. Positions 3 through 18 (FOUR-PENNY-NAILS) ofINV-RCD are placed in ITEM-NAME,left justified in the area, and the four unused character positions are paddedwith spaces. The value 16 is placed in CTR-1.2. Because ALL SPACES is coded as a delimiter, the five contiguous space charactersin 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 characterslash (/) is placed in DLTR-1, and the value 6 is placed in CTR-2.Chapter 6. Handling strings 105


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 <strong>for</strong> delimiters, thespace in position 34 is bypassed.5. Positions 35 through 40 (475120) are placed in M-UNITS. The value 6 is placed inCTR-3. The delimiter is SPACE, but because no field has been defined as areceiving area <strong>for</strong> delimiters, the space in position 41 is bypassed.6. Positions 42 through 46 (00122) are placed in FIELD-A and right justified in thearea. The high-order digit position is filled with a zero (0). The delimiter isSPACE, but because no field was defined as a receiving area <strong>for</strong> delimiters, thespace 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-RCDhave not been examined, the ON OVERFLOW statement is executed. Execution ofthe UNSTRING statement is completed.After the UNSTRING statement is per<strong>for</strong>med, the fields contain the values shownbelow.FieldValueDISPLAY-REC 707890 FOUR-PENNY-NAILS 000379WORK-REC475120000122BBACHAR-CT (the POINTER field) 55FLDS-FILLED (the TALLYING field) 6Manipulating null-terminated stringsYou can construct and manipulate null-terminated strings (<strong>for</strong> example, strings thatare passed to or from aCprogram) by various mechanisms.For example, you can:v Use null-terminated literal constants (Z"...").v Use an INSPECT statement to count the number of characters in a null-terminatedstring:MOVE 0 TO char-countINSPECT source-field TALLYING char-countFOR CHARACTERSBEFORE X"00"v Use an UNSTRING statement to move characters in a null-terminated string to atarget 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-countPIC X....PROCEDURE DIVISION.UNSTRING source-field DELIMITED BY X"00"INTO target-areaCOUNT IN char-countON OVERFLOWDISPLAY "source not null terminated or target too short"END-UNSTRING106 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvUse a SEARCH statement to locate trailing null or space characters. Define thestring being examined as a table of single characters.Check each character in a field in a loop (PERFORM). You can examine eachcharacter in a field by using a reference modifier such as source-field (I:1).“Example: null-terminated strings”RELATED TASKS“Handling null-terminated strings” on page 470RELATED REFERENCESAlphanumeric literals (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: null-terminated stringsThe following example shows several ways in which you can processnull-terminated strings.01 L pic X(20) value z'ab'.01 M pic X(20) value z'cd'.01 N pic X(20).01 N-Length pic 99 value zero.01 Y pic X(13) value 'Hello, World!'....* Display null-terminated string:Inspect N tallying N-length<strong>for</strong> characters be<strong>for</strong>e initial x'00'Display 'N: ' N(1:N-Length) ' Length: ' N-Length...* Move null-terminated string to alphanumeric, strip null:Unstring N delimited by X'00' into X...* Create null-terminated string:String Y delimited by sizeX'00' delimited by sizeinto N....* Concatenate two null-terminated strings to produce another:String L delimited by x'00'M delimited by x'00'X'00' delimited by sizeinto N.Referring to substrings of data itemsRefer to a substring of a data item that has USAGE DISPLAY, DISPLAY-1, orNATIONALby using a reference modifier. You can also refer to a substring of an alphanumericor national character string that is returned by an intrinsic function by using areference modifier.The following example shows how to use a reference modifier to refer to atwenty-character substring of a data item called Customer-Record:Move Customer-Record(1:20) to Orig-Customer-NameYou code a reference modifier in parentheses immediately after the data item. Asthe example shows, a reference modifier can contain two values that are separatedby a colon, in this order:1. Ordinal position (from the left) of the character that you want the substring tostart withChapter 6. Handling strings 107


2. (Optional) Length of the desired substring in character positionsThe reference-modifier position and length <strong>for</strong> an item that has USAGE DISPLAY areexpressed in terms of single-byte characters. The reference-modifier position andlength <strong>for</strong> items that have USAGE DISPLAY-1 or NATIONAL are expressed in terms ofDBCS character positions and national character positions, respectively.If you omit the length in a reference modifier (coding only the ordinal position ofthe first character, followed by a colon), the substring extends to the end of theitem. Omit the length where possible as a simpler and less error-prone codingtechnique.You can refer to substrings of USAGE DISPLAY data items, including alphanumericgroups, alphanumeric-edited data items, numeric-edited data items, displayfloating-point data items, and zoned decimal data items, by using referencemodifiers. When you reference-modify any of these data items, the result is ofcategory alphanumeric. When you reference-modify an alphabetic data item, theresult is of category alphabetic.You can refer to substrings of USAGE NATIONAL data items, including nationalgroups, national-edited data items, numeric-edited data items, nationalfloating-point data items, and national decimal data items, by using referencemodifiers. When you reference-modify any of these data items, the result is ofcategory national. For example, suppose that you define a national decimal dataitem as follows:01 NATL-DEC-ITEM Usage National Pic 999 Value 123.You can use NATL-DEC-ITEM in an arithmetic expression because NATL-DEC-ITEM is ofcategory numeric. But you cannot use NATL-DEC-ITEM(2:1) (the national character2, which in hexadecimal notation is NX"0032") in an arithmetic expression, becauseit is of category national.You can refer to substrings of table entries, including variable-length entries, byusing reference modifiers. To refer to a substring of a table entry, code thesubscript expression be<strong>for</strong>e the reference modifier. For example, assume thatPRODUCT-TABLE is a properly coded table of character strings. To move D to thefourth character in the second string in the table, you can code this statement:MOVE 'D' to PRODUCT-TABLE (2), (4:1)You can code either or both of the two values in a reference modifier as a variableor as an arithmetic expression.“Example: arithmetic expressions as reference modifiers” on page 110Because numeric function identifiers can be used anywhere that arithmeticexpressions can be used, you can code a numeric function identifier in a referencemodifier as the leftmost character position or as the length, or both.“Example: intrinsic functions as reference modifiers” on page 110Each number in the reference modifier must have a value of at least 1. The sum ofthe two numbers must not exceed the total length of the data item by more than 1character position so that you do not reference beyond the end of the substring.108 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


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 following options detect out-of-range reference modifiers, and flag violationswith a runtime message:v SSRANGE compiler optionv CHECK runtime optionRELATED CONCEPTS“Reference modifiers”“Unicode and the encoding of language characters” on page 125RELATED TASKS“Referring to an item in a table” on page 72RELATED REFERENCES“SSRANGE” on page 347Reference modification (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Function definitions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Reference modifiersReference 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 systemand display its value in an expanded <strong>for</strong>mat. You can retrieve the current timewith the ACCEPT statement, which returns the hours, minutes, seconds, andhundredths of seconds in this <strong>for</strong>mat:HHMMSSssHowever, you might prefer to view the current time in this <strong>for</strong>mat:HH:MM:SSWithout reference modifiers, you would have to define data items <strong>for</strong> both <strong>for</strong>mats.You would also have to write code to convert from one <strong>for</strong>mat to the other.With reference modifiers, you do not need to provide names <strong>for</strong> the subfields thatdescribe the TIME elements. The only data definition you need is <strong>for</strong> the time asreturned by the system. For example:01 REFMOD-TIME-ITEM PIC X(8).The following code retrieves and expands the time value:ACCEPT REFMOD-TIME-ITEM FROM TIME.DISPLAY "CURRENT TIME IS: "* Retrieve the portion of the time value that corresponds to* the number of hours:REFMOD-TIME-ITEM (1:2)":"* Retrieve the portion of the time value that corresponds to* the number of minutes:REFMOD-TIME-ITEM (3:2)":"* Retrieve the portion of the time value that corresponds to* the number of seconds:REFMOD-TIME-ITEM (5:2)Chapter 6. Handling strings 109


“Example: arithmetic expressions as reference modifiers”“Example: intrinsic functions as reference modifiers”RELATED TASKS“Assigning input from a screen or file (ACCEPT)” on page 37“Referring to substrings of data items” on page 107“Using national data (Unicode) in <strong>COBOL</strong>” on page 126RELATED REFERENCESReference modification (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: arithmetic expressions as reference modifiersSuppose that a field contains some right-justified characters, and you want tomove those characters to another field where they will be left justified. You can doso by using reference modifiers and an INSPECT statement.Suppose a program has the following data:01 LEFTY PIC X(30).01 RIGHTY PIC X(30) JUSTIFIED RIGHT.01 I PIC 9(9) USAGE BINARY.The program counts the number of leading spaces and, using arithmeticexpressions in a reference modifier, moves the right-justified characters intoanother field, justified to the left:MOVE SPACES TO LEFTYMOVE ZERO TO IINSPECT RIGHTYTALLYING I FOR LEADING SPACE.IF I IS LESS THAN LENGTH OF RIGHTY THENMOVE RIGHTY (I+1:LENGTH OF RIGHTY -I)TOLEFTYEND-IFThe MOVE statement transfers characters from RIGHTY, beginning at the positioncomputed as I+1<strong>for</strong>alength that is computed as LENGTH OF RIGHTY - I, into thefield LEFTY.Example: intrinsic functions as reference modifiersYou can use intrinsic functions in reference modifiers if you do not know theleftmost position or length of a substring at compile time.For example, the following code fragment causes a substring of Customer-Record tobe moved into the data item WS-name. The substring is determined at run time.05 WS-name Pic x(20).05 Left-posn Pic 99.05 I Pic 99....Move Customer-Record(Function Min(Left-posn I):Function Length(WS-name)) to WS-nameIf you want to use a noninteger function in a position that requires an integerfunction, you can use the INTEGER or INTEGER-PART function to convert the result toan integer. For example:Move Customer-Record(Function Integer(Function Sqrt(I)): ) to WS-nameRELATED REFERENCESINTEGER (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)INTEGER-PART (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)110 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Tallying and replacing data items (INSPECT)Use the INSPECT statement to inspect characters or groups of characters in a dataitem and to optionally replace them.Use the INSPECT statement to do the following tasks:v Count the number of times a specific character occurs in a data item (TALLYINGphrase).v Fill a data item or selected portions of a data item with specified characters suchas spaces, asterisks, or zeros (REPLACING phrase).v Convert all occurrences of a specific character or string of characters in a dataitem to replacement characters that you specify (CONVERTING phrase).You can specify one of the following data items as the item to be inspected:v An elementary item described explicitly or implicitly as USAGE DISPLAY, USAGEDISPLAY-1, orUSAGE NATIONALv An alphanumeric group item or national group itemIf the inspected item has:v USAGE DISPLAY, each identifier in the statement (except the TALLYING count field)must have USAGE DISPLAY, and each literal in the statement must bealphanumericv USAGE NATIONAL, each identifier in the statement (except the TALLYING count field)must have USAGE NATIONAL, and each literal in the statement must be nationalv USAGE DISPLAY-1, each identifier in the statement (except the TALLYING countfield) must have USAGE DISPLAY-1, and each literal in the statement must be aDBCS literal“Examples: INSPECT statement”RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED REFERENCESINSPECT statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Examples: INSPECT statementThe following examples show some uses of the INSPECT statement to examine andreplace characters.In the following example, the INSPECT statement examines and replaces charactersin data item DATA-2. The number of times a leading zero (0) occurs in the data itemis accumulated in COUNTR. The first instance of the character A that follows the firstinstance of the character C is replaced by the character 2.77 COUNTR PIC 9 VALUE ZERO.01 DATA-2 PIC X(11)....INSPECT DATA-2TALLYING COUNTR FOR LEADING "0"REPLACING FIRST "A" BY "2" AFTER INITIAL "C"Chapter 6. Handling strings 111


DATA-2 be<strong>for</strong>e COUNTR after DATA-2 after00ACADEMY00 2 00AC2DEMY000000ALABAMA 4 0000ALABAMACHATHAM0000 0 CH2THAM0000In the following example, the INSPECT statement examines and replaces charactersin data item DATA-3. Each character that precedes the first instance of a quotationmark (") is replaced by the character 0.77 COUNTR PIC 9 VALUE ZERO.01 DATA-3 PIC X(8)....INSPECT DATA-3REPLACING CHARACTERS BY ZER<strong>OS</strong> BEFORE INITIAL QUOTEDATA-3 be<strong>for</strong>e COUNTR after DATA-3 after456"ABEL 0 000"ABELANDES"12 0 00000"12"TWAS BR 0 "TWAS BRThe following example shows the use of INSPECT CONVERTING with AFTER andBEFORE phrases to examine and replace characters in data item DATA-4. Allcharacters that follow the first instance of the character / but that precede the firstinstance of the character ? (if any) are translated from lowercase to uppercase.01 DATA-4 PIC X(11)....INSPECT DATA-4CONVERTING"abcdefghijklmnopqrstuvwxyz" TO"ABCDEFGHIJKLMNOPQRSTUVWXYZ"AFTER INITIAL "/"BEFORE INITIAL"?"DATA-4 be<strong>for</strong>ea/five/?sixr/Rexx/RRRrzfour?inspeDATA-4 aftera/FIVE/?sixr/REXX/RRRRzfour?inspeConverting data items (intrinsic functions)You can use intrinsic functions to convert character-string data items to severalother <strong>for</strong>mats, <strong>for</strong> example, to uppercase or lowercase, to reverse order, tonumbers, or to one code page from another.You can use the NATIONAL-OF and DISPLAY-OF intrinsic functions to convert to andfrom national (Unicode) strings.You can also use the INSPECT statement to convert characters.“Examples: INSPECT statement” on page 111112 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Converting to uppercase or lowercase (UPPER-CASE, LOWER-CASE)”“Trans<strong>for</strong>ming to reverse order (REVERSE)”“Converting to numbers (NUMVAL, NUMVAL-C)”“Converting from one code page to another” on page 115Converting to uppercase or lowercase (UPPER-CASE,LOWER-CASE)You can use the UPPER-CASE and LOWER-CASE intrinsic functions to easily change thecase of alphanumeric, alphabetic, or national strings.01 Item-1 Pic x(30) Value "Hello World!".01 Item-2 Pic x(30)....Display Item-1Display Function Upper-case(Item-1)Display Function Lower-case(Item-1)Move Function Upper-case(Item-1) to Item-2Display Item-2The code above displays the following messages on the system logical outputdevice:Hello World!HELLO WORLD!hello world!HELLO WORLD!The DISPLAY statements do not change the actual contents of Item-1, but affect onlyhow the letters are displayed. However, the MOVE statement causes uppercaseletters to replace the contents of Item-2.RELATED TASKS“Assigning input from a screen or file (ACCEPT)” on page 37“Displaying values on a screen or in a file (DISPLAY)” on page 38Trans<strong>for</strong>ming to reverse order (REVERSE)You can reverse the order of the characters in a string by using the REVERSEintrinsic function.Move Function Reverse(Orig-cust-name) To Orig-cust-nameFor example, the statement above reverses the order of the characters inOrig-cust-name. If the starting value is JOHNSONbbb, the value after the statement isper<strong>for</strong>med is bbbN<strong>OS</strong>NHOJ, where b represents a blank space.RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125Converting to numbers (NUMVAL, NUMVAL-C)The NUMVAL and NUMVAL-C functions convert character strings (alphanumeric ornational literals, or class alphanumeric or class national data items) to numbers.Use these functions to convert free-<strong>for</strong>mat character-representation numbers tonumeric <strong>for</strong>m so that you can process them numerically.Chapter 6. Handling strings 113


01 R Pic x(20) Value "- 1234.5678".01 S Pic x(20) Value " $12,345.67CR".01 Total Usage is Comp-1....Compute Total = Function Numval(R) + Function Numval-C(S)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 be<strong>for</strong>e or afterthe character string, and the sign will be processed. The arguments must notexceed 18 digits when you compile with the default option ARITH(COMPAT)(compatibility mode) nor 31 digits when you compile with ARITH(EXTEND) (extendedmode), not including the editing symbols.NUMVAL and NUMVAL-C return long (64-bit) floating-point values in compatibilitymode, and return extended-precision (128-bit) floating-point values in extendedmode. A reference to either of these functions represents a reference to a numericdata item.At most 15 decimal digits can be converted accurately to long-precision floatingpoint (as described in the related reference below about conversions and precision).If the argument to NUMVAL or NUMVAL-C has more than 15 digits, it is recommendedthat you specify the ARITH(EXTEND) compiler option so that an extended-precisionfunction result that can accurately represent the value of the argument is returned.When you use NUMVAL or NUMVAL-C, you do not need to statically declare numericdata in a fixed <strong>for</strong>mat nor input data in a precise manner. For example, supposeyou define numbers to be entered as follows:01 X Pic S999V99 leading sign is separate....Accept X from ConsoleThe user of the application must enter the numbers exactly as defined by thePICTURE clause. For example:+001.23-300.00However, using the NUMVAL function, you could code:01 A Pic x(10).01 B Pic S999V99....Accept A from ConsoleCompute B = Function Numval(A)The input could then be:1.23-300RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49“Data <strong>for</strong>mat conversions” on page 54“Unicode and the encoding of language characters” on page 125RELATED TASKS“Converting to or from national (Unicode) representation” on page 134114 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED REFERENCES“Conversions and precision” on page 54“ARITH” on page 306Converting from one code page to anotherYou can nest the DISPLAY-OF and NATIONAL-OF intrinsic functions to easily convertfrom any code page to any other code page.For example, the following code converts an EBCDIC string to an ASCII string:77 EBCDIC-CCSID PIC 9(4) BINARY VALUE 1140.77 ASCII-CCSID PIC 9(4) BINARY VALUE 819.77 Input-EBCDIC PIC X(80).77 ASCII-Output PIC X(80)....* Convert EBCDIC to ASCIIMove Function Display-of(Function National-of (Input-EBCDIC EBCDIC-CCSID),ASCII-CCSID)to ASCII-outputRELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED TASKS“Converting to or from national (Unicode) representation” on page 134Evaluating data items (intrinsic functions)You can use intrinsic functions to determine the ordinal position of a character inthe collating sequence, to find the largest or smallest item in a series, to find thelength of data item, or to determine when a program was compiled.Use these intrinsic functions:v CHAR and ORD to evaluate integers and single alphabetic or alphanumericcharacters with respect to the collating sequence used in a programv MAX, MIN, ORD-MAX, and ORD-MIN to find the largest and smallest items in a seriesof data items, including USAGE NATIONAL data itemsv LENGTH to find the length of data items, including USAGE NATIONAL data itemsv WHEN-COMPILED to find the date and time when a program was compiledRELATED CONCEPTS“Unicode and the encoding of language characters” on page 125RELATED TASKS“Evaluating single characters <strong>for</strong> collating sequence”“Finding the largest or smallest data item” on page 116“Finding the length of data items” on page 118“Finding the date of compilation” on page 119Evaluating single characters <strong>for</strong> collating sequenceTo find out the ordinal position of a given alphabetic or alphanumeric character inthe collating sequence, use the ORD function with the character as the argument. ORDreturns an integer that represents that ordinal position.Chapter 6. Handling strings 115


You can use a one-character substring of a data item as the argument to ORD:IF Function Ord(Customer-record(1:1)) IS > 194 THEN ...If you know the ordinal position in the collating sequence of a character, and wantto find the character that it corresponds to, use the CHAR function with the integerordinal position as the argument. CHAR returns the desired character. For example:INITIALIZE Customer-Name REPLACING ALPHABETIC BY Function Char(65)RELATED REFERENCESCHAR (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)ORD (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Finding the largest or smallest data itemTo determine which of two or more alphanumeric, alphabetic, or national dataitems has the largest value, use the MAX or ORD-MAX intrinsic function. To determinewhich item has the smallest value, use MIN or ORD-MIN. These functions evaluateaccording to the collating sequence.To compare numeric items, including those that have USAGE NATIONAL, you can useMAX, ORD-MAX, MIN, orORD-MIN. With these intrinsic functions, the algebraic values ofthe arguments are compared.The MAX and MIN functions return the content of one of the arguments that yousupply. For example, suppose that your program has the following datadefinitions:05 Arg1 Pic x(10) Value "THOMASSON ".05 Arg2 Pic x(10) Value "THOMAS ".05 Arg3 Pic x(10) Value "VALLEJO ".The following statement assigns VALLEJObbb to the first 10 character positions ofCustomer-record, where b represents a blank space:Move Function Max(Arg1 Arg2 Arg3) To Customer-record(1:10)If you used MIN instead, then THOMASbbbb would be assigned.The functions ORD-MAX and ORD-MIN return an integer that represents the ordinalposition (counting from the left) of the argument that has the largest or smallestvalue in the list of arguments that you supply. If you used the ORD-MAX function inthe example above, the compiler would issue an error message because thereference to a numeric function is not in a valid place. The following statement is avalid use of ORD-MAX:Compute x = Function Ord-max(Arg1 Arg2 Arg3)The statement above assigns the integer 3 to x if the same arguments are used asin the previous example. If you used ORD-MIN instead, the integer 2 would bereturned. The examples above might be more realistic if Arg1, Arg2, and Arg3 weresuccessive elements of an array (table).If you specify a national item <strong>for</strong> any argument, you must specify all arguments asclass national.RELATED TASKS“Per<strong>for</strong>ming arithmetic” on page 57116 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Processing table items using intrinsic functions” on page 86“Returning variable-length results with alphanumeric or national functions”RELATED REFERENCESMAX (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MIN (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)ORD-MAX (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)ORD-MIN (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Returning variable-length results with alphanumeric or nationalfunctionsThe results of alphanumeric or national functions could be of varying lengths andvalues depending on the function arguments.In the following example, the amount of data moved to R3 and the results of theCOMPUTE statement depend on the values and sizes of R1 and R2:01 R1 Pic x(10) value "e".01 R2 Pic x(05) value "f".01 R3 Pic x(20) value spaces.01 L Pic 99....Move Function Max(R1 R2) to R3Compute L = Function Length(Function Max(R1 R2))This code has the following results:v R2 is evaluated to be larger than R1.v The string ’fbbbb’ is moved to R3, where b represents a blank space. (The unfilledcharacter positions in R3 are padded with spaces.)v L evaluates to the value 5.If R1 contained ’g’ instead of ’e’, the code would have the following results:v R1 would evaluate as larger than R2.v The string ’gbbbbbbbbb’ would be moved to R3. (The unfilled character positionsin R3 would be padded with spaces.)v The value 10 would be assigned to L.If a program uses national data <strong>for</strong> function arguments, the lengths and values ofthe function results could likewise vary. For example, the following code isidentical to the fragment above, but uses national data instead of alphanumericdata.01 R1 Pic n(10) national value "e".01 R2 Pic n(05) national value "f".01 R3 Pic n(20) national value spaces.01 L Pic 99 national....Move Function Max(R1 R2) to R3Compute L = Function Length(Function Max(R1 R2))This code has the following results, which are similar to the first set of resultsexcept that these are <strong>for</strong> national characters:v R2 is evaluated to be larger than R1.vThe string NX"0066 0020 0020 0020 0020" (the equivalent in national charactersof ’fbbbb’, where b represents a blank space), shown here in hexadecimal notationwith added spaces <strong>for</strong> readability, is moved to R3. The unfilled characterpositions in R3 are padded with national spaces.Chapter 6. Handling strings 117


v 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 nationalfunctions. Plan your program accordingly. For example, you might need to thinkabout using variable-length files when the records that you are writing could be ofdifferent 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 > R2Write Short-Customer-Record from R1ElseWrite Long-Customer-Record from R2End-ifRELATED TASKS“Finding the largest or smallest data item” on page 116“Per<strong>for</strong>ming arithmetic” on page 57RELATED REFERENCESMAX (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Finding the length of data itemsYou can use the LENGTH function in many contexts (including tables and numericdata) to determine the length of an item. For example, you can use the LENGTHfunction to determine the length of an alphanumeric or national literal, or a dataitem of any type except DBCS.The LENGTH function returns the length of a national item (a literal, or any item thathas USAGE NATIONAL, including national group items) as an integer equal to thelength of the argument in national character positions. It returns the length of anyother data item as an integer equal to the length of the argument in alphanumericcharacter positions.The following <strong>COBOL</strong> statement demonstrates moving a data item into the field ina record that holds customer names:Move Customer-name To Customer-record(1:Function Length(Customer-name))You can also use the LENGTH OF special register, which returns the length in byteseven <strong>for</strong> national data. Coding either Function Length(Customer-name) or LENGTHOF Customer-name returns the same result <strong>for</strong> alphanumeric items: the length ofCustomer-name in bytes.You can use the LENGTH function only where arithmetic expressions are allowed.However, you can use the LENGTH OF special register in a greater variety ofcontexts. For example, you can use the LENGTH OF special register as an argumentto an intrinsic function that accepts integer arguments. (You cannot use an intrinsicfunction as an operand to the LENGTH OF special register.) You can also use theLENGTH OF special register as a parameter in a CALL statement.118 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Per<strong>for</strong>ming arithmetic” on page 57“Creating variable-length tables (DEPENDING ON)” on page 81“Processing table items using intrinsic functions” on page 86RELATED REFERENCESLENGTH (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)LENGTH OF (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Finding the date of compilationYou can use the WHEN-COMPILED intrinsic function to determine when a programwas compiled. The 21-character result indicates the four-digit year, month, day, andtime (in hours, minutes, seconds, and hundredths of seconds) of compilation, andthe difference in hours and minutes from Greenwich mean time.The first 16 positions are in the following <strong>for</strong>mat:YYYYMMDDhhmmsshhYou can instead use the WHEN-COMPILED special register to determine the date andtime of compilation in the following <strong>for</strong>mat:MM/DD/YYhh.mm.ssThe WHEN-COMPILED special register supports only a two-digit year, and carries thetime out only to seconds. You can use this special register only as the sending fieldin a MOVE statement.RELATED REFERENCESWHEN-COMPILED (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 6. Handling strings 119


120 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 7. Processing data in an international environment<strong>Enterprise</strong> <strong>COBOL</strong> supports Unicode UTF-16 as national character data at runtime. UTF-16 provides a consistent and efficient way to encode plain text. UsingUTF-16, you can develop software that will work with various national languages.Use these <strong>COBOL</strong> facilities to code and compile programs that process nationaldata:v Data types and literals:– Character data types, defined with the USAGE NATIONAL clause and a PICTUREclause that defines data of category national, national-edited, ornumeric-edited– Numeric data types, defined with the USAGE NATIONAL clause and a PICTUREclause that defines a numeric data item (a national decimal item) or an externalfloating-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, orZERO, which havenational character (UTF-16) values when used in national-character contextsvvvvThe <strong>COBOL</strong> statements shown in the related reference below about <strong>COBOL</strong>statements and national dataIntrinsic 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 aselected code page (EBCDIC, ASCII, EUC, or UTF-8)– The other intrinsic functions shown in the related reference below aboutintrinsic functions and national dataThe GROUP-USAGE NATIONAL clause to define groups that contain only USAGENATIONAL data items and that behave like elementary category national items inmost operationsCompiler options:– CODEPAGE to specify the code page to use <strong>for</strong> alphanumeric and DBCS data inyour program– NSYMBOL to control whether national or DBCS processing is used <strong>for</strong> the Nsymbol in literals and PICTURE clausesYou can also take advantage of implicit conversions of alphanumeric or DBCS dataitems to national representation. The compiler per<strong>for</strong>ms such conversions (in mostcases) when you move these items to national data items, or compare these itemswith national data items.RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125“National groups” on page 129RELATED TASKS“Using national data (Unicode) in <strong>COBOL</strong>” on page 126“Converting to or from national (Unicode) representation” on page 134© Copyright IBM Corp. 1991, 2009 121


“Processing UTF-8 data” on page 137“Processing Chinese GB 18030 data” on page 138“Comparing national (UTF-16) data” on page 139“Coding <strong>for</strong> use of DBCS support” on page 141Appendix C, “Converting double-byte character set (DBCS) data,” on page 703RELATED REFERENCES“<strong>COBOL</strong> statements and national data”“Intrinsic functions and national data” on page 124“CODEPAGE” on page 310“NSYMBOL” on page 331Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Data categories and PICTURE rules (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MOVE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)General relation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)<strong>COBOL</strong> statements and national dataYou can use national data with the PROCEDURE DIVISION and compiler-directingstatements shown in the table below.Table 15. <strong>COBOL</strong> statements and national data<strong>COBOL</strong>statement Can be national Comment For more in<strong>for</strong>mationACCEPT identifier-1, identifier-2 identifier-1 is convertedfrom the native code pagespecified in the CODEPAGEcompiler option only ifinput is from CONSOLE.ADDCALLCOMPUTECOPY...REPLACINGAll identifiers can benumeric items that haveUSAGE NATIONAL. identifier-3(GIVING) can benumeric-edited with USAGENATIONAL.identifier-2, identifier-3,identifier-4, identifier-5;literal-2, literal-3identifier-1 can be numericor numeric-edited withUSAGE NATIONAL.arithmetic-expression cancontain numeric items thathave USAGE NATIONAL.operand-1, operand-2 of theREPLACING phraseDISPLAY identifier-1 identifier-1 is converted toEBCDIC only if the CONSOLEmnemonic-name isspecified directly orindirectly.“Assigning input from a screen or file(ACCEPT)” on page 37“Using COMPUTE and otherarithmetic statements” on page 58“Passing data” on page 465“Using COMPUTE and otherarithmetic statements” on page 58Chapter 18, “Compiler-directingstatements,” on page 363“Displaying values on a screen or in afile (DISPLAY)” on page 38122 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 15. <strong>COBOL</strong> statements and national data (continued)<strong>COBOL</strong>statement Can be national Comment For more in<strong>for</strong>mationDIVIDEAll identifiers can benumeric items that haveUSAGE NATIONAL. identifier-3(GIVING) and identifier-4(REMAINDER) can benumeric-edited with USAGENATIONAL.“Using COMPUTE and otherarithmetic statements” on page 58INITIALIZEINSPECTINVOKEidentifier-1; identifier-2 orliteral-1 of the REPLACINGphraseAll identifiers and literals.(identifier-2, the TALLYINGinteger data item, can haveUSAGE NATIONAL.)Method-name as identifier-2or literal-1; identifier-3 orliteral-2 in the BY VALUEphraseIf you specify REPLACINGNATIONAL or REPLACINGNATIONAL-EDITED, identifier-2or literal-1 must be valid asa sending operand in amove to identifier-1.If any of these (other thanidentifier-2, the TALLYINGidentifier) have USAGENATIONAL, all must benational.MERGE Merge keys The COLLATING SEQUENCEphrase does not apply.MOVEMULTIPLYSEARCH ALL(binary search)Both the sender andreceiver, or only thereceiverAll identifiers can benumeric items that haveUSAGE NATIONAL. identifier-3(GIVING) can benumeric-edited with USAGENATIONAL.Both the key data item andits object of comparisonImplicit conversions areper<strong>for</strong>med <strong>for</strong> valid MOVEoperands.The key data item and itsobject of comparison mustbe compatible according tothe rules of comparison. Ifthe object of comparison isof class national, the keymust be also.SORT Sort keys The COLLATING SEQUENCEphrase does not apply.STRINGAll identifiers and literals.(identifier-4, the POINTERinteger data item, can haveUSAGE NATIONAL.)If identifier-3, the receivingdata item, is national, allidentifiers and literals(other than identifier-4, thePOINTER identifier) must benational.“Examples: initializing data items” onpage 30“Tallying and replacing data items(INSPECT)” on page 111“Invoking methods (INVOKE)” onpage 582“Setting sort or merge criteria” onpage 221“Assigning values to elementary dataitems (MOVE)” on page 34“Assigning values to group data items(MOVE)” on page 35“Using COMPUTE and otherarithmetic statements” on page 58“Doing a binary search (SEARCHALL)” on page 85“Setting sort or merge criteria” onpage 221“Joining data items (STRING)” onpage 101Chapter 7. Processing data in an international environment 123


Table 15. <strong>COBOL</strong> statements and national data (continued)<strong>COBOL</strong>statement Can be national Comment For more in<strong>for</strong>mationSUBTRACT All identifiers can benumeric items that haveUSAGE NATIONAL. identifier-3(GIVING) can benumeric-edited with USAGENATIONAL.“Using COMPUTE and otherarithmetic statements” on page 58UNSTRINGXML GENERATEXML PARSEAll identifiers and literals.(identifier-6 and identifier-7,the COUNT and TALLYINGinteger data items,respectively, can have USAGENATIONAL.)identifier-1 (the generatedXML document); identifier-2(the source field or fields);identifier-4 or literal-4 (thenamespace identifier);identifier-5 or literal-5 (thenamespace prefix)identifier-1 (the XMLdocument)If identifier-4, a receivingdata item, has USAGENATIONAL, the sending dataitem and each delimitermust have USAGE NATIONAL,and each literal must benational.The XML-NTEXT specialregister contains nationalcharacter documentfragments during parsing.XML-NNAMESPACE andXML-NNAMESPACE-PREFIXspecial registers contain theassociated namespaceidentifier and namespaceprefix, if any, in nationalcharacters.“Splitting data items (UNSTRING)” onpage 103Chapter 29, “Producing XML output,”on page 543Chapter 28, “Processing XML input,”on page 503RELATED TASKS“Defining numeric data” on page 45“Displaying numeric data” on page 47“Using national data (Unicode) in <strong>COBOL</strong>” on page 126“Comparing national (UTF-16) data” on page 139RELATED REFERENCES“CODEPAGE” on page 310Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Intrinsic functions and national dataYou can use arguments of class national with the intrinsic functions shown in thetable below.Table 16. Intrinsic functions and national character dataIntrinsic function Function type For more in<strong>for</strong>mationDISPLAY-OF Alphanumeric “Converting national to alphanumeric (DISPLAY-OF)” onpage 136124 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 16. Intrinsic functions and national character data (continued)Intrinsic function Function type For more in<strong>for</strong>mationLENGTH Integer “Finding the length of data items” on page 118LOWER-CASE, UPPER-CASE National “Converting to uppercase or lowercase (UPPER-CASE,LOWER-CASE)” on page 113NUMVAL, NUMVAL-C Numeric “Converting to numbers (NUMVAL, NUMVAL-C)” on page113MAX, MIN National “Finding the largest or smallest data item” on page 116ORD-MAX, ORD-MIN Integer “Finding the largest or smallest data item” on page 116REVERSE National “Trans<strong>for</strong>ming to reverse order (REVERSE)” on page 113You can use national decimal arguments wherever zoned decimal arguments areallowed. You can use national floating-point arguments wherever displayfloating-point arguments are allowed. (See the related reference below aboutarguments <strong>for</strong> a complete list of intrinsic functions that can take integer or numericarguments.)RELATED TASKS“Defining numeric data” on page 45“Using national data (Unicode) in <strong>COBOL</strong>” on page 126RELATED REFERENCESArguments (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Unicode and the encoding of language characters<strong>Enterprise</strong> <strong>COBOL</strong> provides basic runtime support <strong>for</strong> Unicode, which can handletens of thousands of characters that cover all commonly used characters andsymbols in the world.A character set is a defined set of characters, but is not associated with a codedrepresentation. A coded character set (also referred to in this documentation as a codepage) is a set of unambiguous rules that relate the characters of the set to theircoded representation. Each code page has a name and is like a table that sets upthe symbols <strong>for</strong> representing a character set; each symbol is associated with aunique bit pattern, or code point. Each code page also has a coded character setidentifier (CCSID), which is a value from 1 to 65,536.Unicode has several encoding schemes, called Unicode Trans<strong>for</strong>mation Format (UTF),such as UTF-8, UTF-16, and UTF-32. <strong>Enterprise</strong> <strong>COBOL</strong> uses UTF-16 (CCSID 1200)in big-endian <strong>for</strong>mat as the representation <strong>for</strong> national literals and data items thathave USAGE NATIONAL.UTF-8 represents ASCII invariant characters a-z, A-Z, 0-9, and certain specialcharacters such as ’@,.+-=/*()thesame way that they are represented inASCII. UTF-16 represents these characters as NX'00nn', where X'nn' is therepresentation of the character in ASCII.For example, the string 'ABC' is represented in UTF-16 as NX'004100420043'. InUTF-8, 'ABC' is represented as X'414243'.Chapter 7. Processing data in an international environment 125


One or more encoding units are used to represent a character from a codedcharacter set. For UTF-16, an encoding unit takes 2 bytes of storage. Any characterdefined in any EBCDIC, ASCII, or EUC code page is represented in one UTF-16encoding unit when the character is converted to the national data representation.Cross-plat<strong>for</strong>m considerations: <strong>Enterprise</strong> <strong>COBOL</strong> and <strong>COBOL</strong> <strong>for</strong> AIX ® supportUTF-16 in big-endian <strong>for</strong>mat in national data. <strong>COBOL</strong> <strong>for</strong> Windows ® supportsUTF-16 in little-endian <strong>for</strong>mat (UTF-16LE) in national data. If you are portingUnicode data that is encoded in UTF-16LE representation to <strong>Enterprise</strong> <strong>COBOL</strong>from another plat<strong>for</strong>m, you must convert that data to UTF-16 in big-endian <strong>for</strong>matto process the data as national data.RELATED TASKS“Converting to or from national (Unicode) representation” on page 134RELATED REFERENCES“Storage of character data” on page 133Character sets and code pages (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using national data (Unicode) in <strong>COBOL</strong>In <strong>Enterprise</strong> <strong>COBOL</strong>, you can specify national (UTF-16) data in any of severalways.These types of national data are available:v National data items (categories national, national-edited, and numeric-edited)v National literalsv Figurative constants as national charactersv Numeric data items (national decimal and national floating-point)In addition, you can define national groups that contain only data items thatexplicitly or implicitly have USAGE NATIONAL, and that behave in the same way aselementary category national data items in most operations.These declarations affect the amount of storage that is needed.RELATED CONCEPTS“Unicode and the encoding of language characters” on page 125“National groups” on page 129RELATED TASKS“Defining national data items” on page 127“Using national literals” on page 127“Using national-character figurative constants” on page 128“Defining national numeric data items” on page 129“Using national groups” on page 130“Converting to or from national (Unicode) representation” on page 134“Comparing national (UTF-16) data” on page 139RELATED REFERENCES“Storage of character data” on page 133Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)126 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Defining national data itemsDefine national data items with the USAGE NATIONAL clause to hold national(UTF-16) character strings.You can define national data items of the following categories:v Nationalv National-editedv Numeric-editedTo define a category national data item, code a PICTURE clause that contains onlyone or more PICTURE symbols N.To define a national-edited data item, code a PICTURE clause that contains at leastone of each of the following symbols:v Symbol Nv Simple insertion editing symbol B, 0, or/To define a numeric-edited data item of class national, code a PICTURE clause thatdefines a numeric-edited item (<strong>for</strong> example, -$999.99) and code a USAGE NATIONALclause. You can use a numeric-edited data item that has USAGE NATIONAL in thesame way that you use a numeric-edited item that has USAGE DISPLAY.You can also define a data item as numeric-edited by coding the BLANK WHEN ZEROclause <strong>for</strong> an elementary item that is defined as numeric by its PICTURE clause.If you code a PICTURE clause but do not code a USAGE clause <strong>for</strong> data items thatcontain only one or more PICTURE symbols N, you can use the compiler optionNSYMBOL(NATIONAL) to ensure that such items are treated as national data itemsinstead of as DBCS items.RELATED TASKS“Displaying numeric data” on page 47RELATED REFERENCES“NSYMBOL” on page 331BLANK WHEN ZERO clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using national literalsTo specify national literals, use the prefix character N and compile with the optionNSYMBOL(NATIONAL).You can use either of these notations:v N"character-data"v N'character-data'If you compile with the option NSYMBOL(DBCS), the literal prefix character Nspecifies a DBCS literal, not a national literal.To specify a national literal as a hexadecimal value, use the prefix NX. You can useeither of these notations:v NX"hexadecimal-digits"Chapter 7. Processing data in an international environment 127


vNX'hexadecimal-digits'Each of the following MOVE statements sets the national data item Y to the UTF-16value of the characters ’AB’:01 Y pic NN usage national....Move NX"00410042" to YMove N"AB" to YMove "AB" to YDo not use alphanumeric hexadecimal literals in contexts that call <strong>for</strong> nationalliterals, because such usage is easily misunderstood. For example, the followingstatement also results in moving the UTF-16 characters ’AB’ (not the hexadecimalbit pattern C1C2) toY, where Y is defined as USAGE NATIONAL:Move X"C1C2" to YYou cannot use national literals in the SPECIAL-NAMES paragraph or asprogram-names. You can use a national literal to name an object-oriented methodin the METHOD-ID paragraph or to specify a method-name in an INVOKE statement.RELATED TASKS“Using literals” on page 27RELATED REFERENCES“NSYMBOL” on page 331National literals (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using national-character figurative constantsYou can use the figurative constant ALL national-literal in a context that requiresnational characters. ALL national-literal represents all or part of the string that isgenerated by successive concatenations of the encoding units that make up thenational literal.You can use the figurative constants QUOTE, SPACE, HIGH-VALUE, LOW-VALUE, orZEROin a context that requires national characters, such as a MOVE statement, an implicitmove, or a relation condition that has national operands. In these contexts, thefigurative constant represents a national-character (UTF-16) value.When you use the figurative constant HIGH-VALUE in a context that requiresnational characters, its value is NX'FFFF'. When you use LOW-VALUE in a contextthat requires national characters, its value is NX'0000'.Restrictions: You must not use HIGH-VALUE or the value assigned from HIGH-VALUEin a way that results in conversion of the value from one data representation toanother (<strong>for</strong> example, between USAGE DISPLAY and USAGE NATIONAL). X'FF' (thevalue of HIGH-VALUE in an alphanumeric context when the EBCDIC collatingsequence is being used) does not represent a valid EBCDIC character, and NX'FFFF'does not represent a valid national character. Conversion of such a value toanother representation results in a substitution character being used (not X'FF' orNX'FFFF'). Consider the following example:01 natl-data PIC NN Usage National.01 alph-data PIC XX....MOVE HIGH-VALUE TO natl-data, alph-dataIF natl-data = alph-data. . .128 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The IF statement above evaluates as false even though each of its operands was setto HIGH-VALUE. Be<strong>for</strong>e an elementary alphanumeric operand is compared to anational operand, the alphanumeric operand is treated as though it were moved toa temporary national data item, and the alphanumeric characters are converted tothe corresponding national characters. When X'FF' is converted to UTF-16,however, the UTF-16 item gets a substitution character value and so does notcompare equally to NX'FFFF'.RELATED TASKS“Converting to or from national (Unicode) representation” on page 134“Comparing national (UTF-16) data” on page 139RELATED REFERENCESFigurative constants (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)DISPLAY-OF (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Support <strong>for</strong> Unicode: Using Unicode ServicesDefining national numeric data itemsDefine data items with the USAGE NATIONAL clause to hold numeric data that isrepresented in national characters (UTF-16). You can define national decimal itemsand national floating-point items.To define a national decimal item, code a PICTURE clause that contains only thesymbols 9, P, S, and V. IfthePICTURE clause contains S, the SIGN IS SEPARATEclause must be in effect <strong>for</strong> that item.To define a national floating-point item, code a PICTURE clause that defines afloating-point item (<strong>for</strong> example, +99999.9E-99).You can use national decimal items in the same way that you use zoned decimalitems. You can use national floating-point items in the same way that you usedisplay floating-point items.RELATED TASKS“Defining numeric data” on page 45“Displaying numeric data” on page 47RELATED REFERENCESSIGN clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)National groupsNational groups, which are specified either explicitly or implicitly with theGROUP-USAGE NATIONAL clause, contain only data items that have USAGE NATIONAL. Inmost cases, a national group item is processed as though it were redefined as anelementary category national item described as PIC N(m), where m is the numberof national (UTF-16) characters in the group.For some operations on national groups, however (just as <strong>for</strong> some operations onalphanumeric groups), group semantics apply. Such operations (<strong>for</strong> example, MOVECORRESPONDING and INITIALIZE) recognize or process the elementary items withinthe national group.Chapter 7. Processing data in an international environment 129


Where possible, use national groups instead of alphanumeric groups that containUSAGE NATIONAL items. National groups provide several advantages <strong>for</strong> theprocessing of national data compared to the processing of national data withinalphanumeric groups:vvvvWhen 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 movean alphanumeric group that contains national characters to a longeralphanumeric group that contains national characters, alphanumeric spaces areused <strong>for</strong> padding. As a result, mishandling of data items could occur.When you move a national group to a shorter data item that has USAGENATIONAL, the national group is truncated at national-character boundaries. Bycontrast, if you move an alphanumeric group that contains national characters toa shorter alphanumeric group that contains national characters, truncation mightoccur 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 alphanumericgroup to an edited item, no editing takes place.When you use a national group as an operand in a STRING, UNSTRING, orINSPECTstatement:– The group content is processed as national characters rather than assingle-byte characters.– TALLYING and POINTER operands operate at the logical level of nationalcharacters.– The national group operand is supported with a mixture of other nationaloperand types.By contrast, if you use an alphanumeric group that contains national charactersin these contexts, the characters are processed byte by byte. As a result, invalidhandling or corruption of data could occur.USAGE NATIONAL groups: A group item can specify the USAGE NATIONAL clause at thegroup level as a convenient shorthand <strong>for</strong> the USAGE of each of the elementary dataitems within the group. Such a group is not a national group, however, but analphanumeric group, and behaves in many operations, such as moves andcompares, like an elementary data item of USAGE DISPLAY (except that no editing orconversion of data occurs).RELATED TASKS“Assigning values to group data items (MOVE)” on page 35“Joining data items (STRING)” on page 101“Splitting data items (UNSTRING)” on page 103“Tallying and replacing data items (INSPECT)” on page 111“Using national groups”RELATED REFERENCESGROUP-USAGE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using national groupsTo define a group data item as a national group, code a GROUP-USAGE NATIONALclause at the group level <strong>for</strong> the item. The group can contain only data items thatexplicitly or implicitly have USAGE NATIONAL.The following data description entry specifies that a level-01 group and itssubordinate groups are national group items:130 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


01 Nat-Group-1 GROUP-USAGE NATIONAL.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 USAGE NATIONAL.In the example above, Nat-Group-1 is a national group, and its subordinate groupsGroup-1 and Group-2 are also national groups. A GROUP-USAGE NATIONAL clause isimplied <strong>for</strong> Group-1, and USAGE NATIONAL is implied <strong>for</strong> the subordinate items inGroup-1. Month, DayOf, and Year are national decimal items, and Amount is anumeric-edited item that has USAGE NATIONAL.You can subordinate national groups within alphanumeric groups as in thefollowing example: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; USAGEDISPLAY is implied <strong>for</strong> the subordinate items in Group-1. (If Alpha-Group-1 specifiedUSAGE NATIONAL at the group level, USAGE NATIONAL would be implied <strong>for</strong> each ofthe subordinate items in Group-1. However, Alpha-Group-1 and Group-1 would bealphanumeric groups, not national groups, and would behave like alphanumericgroups during operations such as moves and compares.) Group-2 is a nationalgroup, and USAGE NATIONAL is implied <strong>for</strong> the numeric-edited item Amount.You cannot subordinate alphanumeric groups within national groups. Allelementary items within a national group must be explicitly or implicitly describedas USAGE NATIONAL, and all group items within a national group must be explicitlyor implicitly described as GROUP-USAGE NATIONAL.RELATED CONCEPTS“National groups” on page 129RELATED TASKS“Using national groups as elementary items”“Using national groups as group items” on page 132RELATED REFERENCESGROUP-USAGE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using national groups as elementary itemsIn most cases, you can use a national group as though it were an elementary dataitem.In the following example, a national group item, Group-1, is moved to anational-edited item, Edited-date. Because Group-1 is treated as an elementarydata item during the move, editing takes place in the receiving data item. Thevalue in Edited-date after the move is 06/23/2009 in national characters.Chapter 7. Processing data in an international environment 131


01 Edited-date PIC NN/NN/NNNN USAGE NATIONAL.01 Group-1 GROUP-USAGE NATIONAL.02 Month PIC 99 VALUE 06.02 DayOf PIC 99 VALUE 23.02 Year PIC 9999 VALUE 2009....MOVE Group-1 to Edited-date.If Group-1 were instead an alphanumeric group in which each of its subordinateitems had USAGE NATIONAL (specified either explicitly with a USAGE NATIONAL clauseon each elementary item, or implicitly with a USAGE NATIONAL clause at the grouplevel), a group move, rather than an elementary move, would occur. Neitherediting nor conversion would take place during the move. The value in the firsteight character positions of Edited-date after the move would be 06232009 innational characters, and the value in the remaining two character positions wouldbe 4 bytes of alphanumeric spaces.RELATED TASKS“Assigning values to group data items (MOVE)” on page 35“Comparing national data and alphanumeric-group operands” on page 141“Using national groups as group items”RELATED REFERENCESMOVE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using national groups as group itemsIn some cases when you use a national group, it is handled with group semantics;that is, the elementary items in the group are recognized or processed.In the following example, an INITIALIZE statement that acts upon national groupitem Group-OneN causes the value 15 in national characters to be moved to only thenumeric items in the group:01 Group-OneN Group-Usage National.05 Trans-codeN Pic N Value "A".05 Part-numberN Pic NN Value "XX".05 Trans-quanN Pic 99 Value 10....Initialize Group-OneN Replacing Numeric Data By 15Because only Trans-quanN in Group-OneN above is numeric, only Trans-quanNreceives the value 15. The other subordinate items are unchanged.The table below summarizes the cases where national groups are processed withgroup semantics.Table 17. National group items that are processed with group semanticsLanguage feature Uses of national group items CommentCORRESPONDING phraseof the ADD, SUBTRACT,or MOVE statementHost variable in EXECSQL statementSpecify a national group item <strong>for</strong>processing as a group inaccordance with the rules of theCORRESPONDING phrase.Specify a national group item as ahost variable.Elementary items within thenational group are processedlike elementary items thathave USAGE NATIONAL withinan alphanumeric group.The national group item is ineffect shorthand <strong>for</strong> the set ofhost variables that aresubordinate to the group item.132 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 17. National group items that are processed with group semantics (continued)Language feature Uses of national group items CommentINITIALIZE statement Specify a national group <strong>for</strong>processing as a group inaccordance with the rules of theINITIALIZE statement.Elementary items within thenational group are initializedlike elementary items thathave USAGE NATIONAL withinan alphanumeric group.Name qualificationTHROUGH phrase of theRENAMES clauseFROM phrase of theXML GENERATEstatementUse the name of a national groupitem to qualify the names ofelementary data items and ofsubordinate group items in thenational group.To specify a national group item inthe THROUGH phrase, use the samerules as <strong>for</strong> an alphanumeric groupitem.Specify a national group item inthe FROM phrase <strong>for</strong> processing as agroup in accordance with the rulesof the XML GENERATE statement.Follow the same rules <strong>for</strong>qualification as <strong>for</strong> analphanumeric group.The result is an alphanumericgroup item.Elementary items within thenational group are processedlike elementary items thathave USAGE NATIONAL withinan alphanumeric group.RELATED TASKS“Initializing a structure (INITIALIZE)” on page 32“Initializing a table (INITIALIZE)” on page 76“Assigning values to elementary data items (MOVE)” on page 34“Assigning values to group data items (MOVE)” on page 35“Finding the length of data items” on page 118“Generating XML output” on page 543“Using national group items in SQL statements” on page 422RELATED REFERENCESQualification (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)RENAMES clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Storage of character dataUse the table below to compare alphanumeric (DISPLAY), DBCS (DISPLAY-1), andUnicode (NATIONAL) encoding and to plan storage usage.Table 18. Encoding and size of alphanumeric, DBCS, and national dataCharacteristic DISPLAY DISPLAY-1 NATIONALCharacter encoding unit 1 byte 2 bytes 2 bytesCode page EBCDIC EBCDIC DBCS UTF-16BE 1Encoding units per graphiccharacter1 1 1or2 2Bytes per graphic character 1 byte 2 bytes 2 or 4 bytesChapter 7. Processing data in an international environment 133


Table 18. Encoding and size of alphanumeric, DBCS, and national data (continued)Characteristic DISPLAY DISPLAY-1 NATIONAL1. Use the CODEPAGE compiler option to specify the EBCDIC code page that is applicable toalphanumeric or DBCS data.2. Most characters are represented in UTF-16 using one encoding unit. In particular, thefollowing characters are represented using a single UTF-16 encoding unit per character:v <strong>COBOL</strong> characters A-Z, a-z, 0-9, space, +-*/=$,;.″ ()>


You can likewise move the following kinds of data to numeric-edited data itemsthat have USAGE NATIONAL:v Alphanumericv Display floating-point (floating-point of USAGE DISPLAY)v Numeric-edited of USAGE DISPLAYv Integer of USAGE DISPLAYFor complete rules about moves to national data, see the related reference aboutthe MOVE statement.For example, the MOVE statement below moves the alphanumeric literal "AB" to thenational data item UTF16-Data:01 UTF16-Data Pic N(2) Usage National....Move "AB" to UTF16-DataAfter the MOVE statement above, UTF16-Data contains NX'00410042', the nationalrepresentation of the alphanumeric characters ’AB’.If padding is required in a receiving data item that has USAGE NATIONAL, the defaultUTF-16 space character (NX'0020') is used. If truncation is required, it occurs at theboundary of a national-character position.RELATED TASKS“Assigning values to elementary data items (MOVE)” on page 34“Assigning values to group data items (MOVE)” on page 35“Displaying numeric data” on page 47“Coding <strong>for</strong> use of DBCS support” on page 141RELATED REFERENCESMOVE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Converting alphanumeric or DBCS to national (NATIONAL-OF)Use the NATIONAL-OF intrinsic function to convert alphabetic, alphanumeric, orDBCS data to a national data item. Specify the source code page as the secondargument if the source is encoded in a different code page than is in effect with theCODEPAGE compiler option.“Example: converting to and from national data” on page 137RELATED TASKS“Processing UTF-8 data” on page 137“Processing Chinese GB 18030 data” on page 138“Processing alphanumeric data items that contain DBCS data” on page 143RELATED REFERENCES“CODEPAGE” on page 310NATIONAL-OF (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 7. Processing data in an international environment 135


Converting national to alphanumeric (DISPLAY-OF)Use the DISPLAY-OF intrinsic function to convert national data to an alphanumeric(USAGE DISPLAY) character string that is represented in a code page that you specifyas the second argument.If you omit the second argument, the output code page is the one that was ineffect with the CODEPAGE compiler option when the source was compiled.If you specify an EBCDIC or ASCII code page that combines single-byte characterset (SBCS) and DBCS characters, the returned string might contain a mixture ofSBCS and DBCS characters. The DBCS substrings are delimited by shift-in andshift-out characters if the code page in effect <strong>for</strong> the function is an EBCDIC codepage.“Example: converting to and from national data” on page 137RELATED TASKS“Processing UTF-8 data” on page 137“Processing Chinese GB 18030 data” on page 138RELATED REFERENCESDISPLAY-OF (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Overriding the default code pageIn some cases, you might need to convert data to or from a code page that differsfrom the CCSID that is specified as the CODEPAGE option value. To do so, convertthe item by using a conversion function in which you explicitly specify the codepage.If you specify a code page as an argument to the DISPLAY-OF intrinsic function, andthe code page differs from the code page that is in effect with the CODEPAGEcompiler option, do not use the function result in any operations that involveimplicit conversion (such as an assignment to, or comparison with, a national dataitem). Such operations assume the EBCDIC code page that is specified with theCODEPAGE compiler option.RELATED REFERENCES“CODEPAGE” on page 310Conversion exceptionsImplicit or explicit conversion between national data and alphanumeric data canfail and generate a severity-3 Language Environment condition.Failure can occur if the code page that you specified implicitly or explicitly is not avalid code page.A character that does not have a counterpart in the target CCSID does not result ina conversion exception. Such a character is converted to a substitution character inthe target code page.RELATED REFERENCES“CODEPAGE” on page 310136 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Example: converting to and from national dataProcessing UTF-8 dataThe following example shows the NATIONAL-OF and DISPLAY-OF intrinsic functionsand the MOVE statement <strong>for</strong> converting to and from national (UTF-16) data items. Italso demonstrates the need <strong>for</strong> explicit conversions when you operate on stringsthat are encoded in multiple code pages.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-GreekMove 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-GreekWrite Greek-record from Data-in-GreekThe 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 charactersin the item happen to be among those that have a common representation in boththe Greek and the English code pages:Move Data-in-Greek to Data-in-UnicodeThe MOVE statement above converts Data-in-Greek to Unicode representation basedon the CCSID 00037 (U.S. English) to UTF-16 conversion. This conversion does notproduce 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, therest of your program also handles EBCDIC data in Greek), you can code the sameexample 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 ...*...ordothefollowing (if need to process data in Unicode):Move Data-in-Greek to Data-in-Unicode*...process Data-in-UnicodeMove function Display-of(Data-in-Unicode) to Data-in-GreekWrite Greek-record from Data-in-GreekWhen you need to process UTF-8 data, first convert the UTF-8 data to UTF-16 in anational data item. After processing the national data, convert it back to UTF-8 <strong>for</strong>output. For the conversions, use the intrinsic functions NATIONAL-OF andDISPLAY-OF, respectively. Use code page 1208 <strong>for</strong> UTF-8 data.You need to do two steps to convert ASCII or EBCDIC data to UTF-8:1. Use the function NATIONAL-OF to convert the ASCII or EBCDIC string to anational (UTF-16) string.2. Use the function DISPLAY-OF to convert the national string to UTF-8.Chapter 7. Processing data in an international environment 137


The following example converts Greek EBCDIC data to UTF-8:Usage note: Use care if you use reference modification to refer to data encoded inUTF-8. UTF-8 characters are encoded with a varying number of bytes percharacter. Avoid operations that might split a multibyte character.RELATED TASKS“Referring to substrings of data items” on page 107“Converting to or from national (Unicode) representation” on page 134“Parsing XML documents encoded in UTF-8” on page 525Processing Chinese GB 18030 dataGB 18030 is a national-character standard specified by the government of thePeople’s Republic of China.GB 18030 characters can be encoded in either UTF-16 or in code page CCSID 1392.Code page 1392 is an ASCII multibyte code page that uses 1, 2, or 4 bytes percharacter. A subset of the GB 18030 characters can be encoded in the Chinese ASCIIcode page, CCSID 1386, or in the Chinese EBCDIC code page, CCSID 1388.<strong>Enterprise</strong> <strong>COBOL</strong> does not have explicit support <strong>for</strong> GB 18030, but does supportthe processing of GB 18030 characters in several ways. You can:vvvUse DBCS data items to process GB 18030 characters that are represented inCCSID 1388.Use national data items to define and process GB 18030 characters that arerepresented in UTF-16, CCSID 01200.Process data in any code page (including CCSID 1388 or 1392) by converting thedata to UTF-16, processing the UTF-16 data, and then converting the data backto the original code-page representation.When you need to process Chinese GB 18030 data that requires conversion, firstconvert the input data to UTF-16 in a national data item. After you process thenational data item, convert it back to Chinese GB 18030 <strong>for</strong> output. For theconversions, 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:RELATED TASKS“Converting to or from national (Unicode) representation” on page 134“Coding <strong>for</strong> use of DBCS support” on page 141138 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED REFERENCES“Storage of character data” on page 133Comparing national (UTF-16) dataYou can compare national (UTF-16) data, that is, national literals and data itemsthat have USAGE NATIONAL (whether of class national or class numeric), explicitly orimplicitly with other kinds of data in relation conditions.You can code conditional expressions that use national data in the followingstatements:v EVALUATEv IFv INSPECTv PERFORMv SEARCHv STRINGv UNSTRINGThe following sections provide an overview about comparing national data toother data items. For full details, see the related references.RELATED TASKS“Comparing two class national operands”“Comparing class national and class numeric operands” on page 140“Comparing national numeric and other numeric operands” on page 140“Comparing national and other character-string operands” on page 140“Comparing national data and alphanumeric-group operands” on page 141RELATED REFERENCESRelation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)General relation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)National comparisons (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Group comparisons (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Comparing two class national operandsYou can compare the character values of two operands of class national.Either operand (or both) can be any of the following types of items:v A national groupv An elementary category national or national-edited data itemv A numeric-edited data item that has USAGE NATIONALOne of the operands can instead be a national literal or a national intrinsicfunction.When you compare two class national operands that have the same length, theyare 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 charactersdetermines the operand with the larger binary value.Chapter 7. Processing data in an international environment 139


When you compare operands that have unequal lengths, the shorter operand istreated 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 twoclass national operands.RELATED CONCEPTS“National groups” on page 129RELATED TASKS“Using national groups” on page 130RELATED REFERENCESNational comparisons (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Comparing class national and class numeric operandsYou can compare national literals or class national data items to integer literals ornumeric data items that are defined as integer (that is, national decimal items orzoned decimal items). At most one of the operands can be a literal.You can also compare national literals or class national data items to floating-pointdata items (that is, display floating-point or national floating-point items).Numeric operands are converted to national (UTF-16) representation if they are notalready in national representation. A comparison is made of the national charactervalues of the operands.RELATED REFERENCESGeneral relation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Comparing national numeric and other numeric operandsNational numeric operands (national decimal and national floating-point operands)are data items of class numeric that have USAGE NATIONAL.You can compare the algebraic values of numeric operands regardless of theirUSAGE. Thus you can compare a national decimal item or a national floating-pointitem with a binary item, an internal-decimal item, a zoned decimal item, a displayfloating-point item, or any other numeric item.RELATED TASKS“Defining national numeric data items” on page 129RELATED REFERENCESGeneral relation conditions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Comparing national and other character-string operandsYou can compare the character value of a national literal or class national data itemwith the character value of any of the following other character-string operands:alphabetic, alphanumeric, alphanumeric-edited, DBCS, or numeric-edited of USAGEDISPLAY.140 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


These operands are treated as if they were moved to an elementary national dataitem. The characters are converted to national (UTF-16) representation, and thecomparison proceeds with two national character operands.RELATED TASKS“Using national-character figurative constants” on page 128RELATED REFERENCESNational comparisons (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Comparing national data and alphanumeric-group operandsYou can compare a national literal, a national group item, or any elementary dataitem that has USAGE NATIONAL to an alphanumeric group.Neither operand is converted. The national operand is treated as if it were movedto 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 regardlessof the representation of the subordinate items in the alphanumeric group operand.For example, Group-XN is an alphanumeric group that consists of two subordinateitems 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 literalN"AB123" are compared byte by byte to the content of Group-XN. The items compareequally, and ″EQUAL″ is displayed.RELATED REFERENCESGroup comparisons (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Coding <strong>for</strong> use of DBCS supportIBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> supports using applications in any of manynational languages, including languages that use double-byte character sets(DBCS).The following list summarizes the support <strong>for</strong> DBCS:v DBCS characters in user-defined words (DBCS names)v DBCS characters in commentsv DBCS data items (defined with PICTURE N, G, orG and B)v DBCS literalsv DBCS compiler optionRELATED TASKS“Declaring DBCS data” on page 142“Using DBCS literals” on page 142“Testing <strong>for</strong> valid DBCS characters” on page 143Chapter 7. Processing data in an international environment 141


“Processing alphanumeric data items that contain DBCS data” on page 143Appendix C, “Converting double-byte character set (DBCS) data,” on page 703RELATED REFERENCES“DBCS” on page 317Declaring DBCS dataUse the PICTURE and USAGE clauses to declare DBCS data items. DBCS data itemscan use PICTURE symbols G, G and B, orN. Each DBCS character position is 2 bytesin length.You can specify a DBCS data item by using the USAGE DISPLAY-1 clause. When youuse PICTURE symbol G, you must specify USAGE DISPLAY-1. When you use PICTUREsymbol N but omit the USAGE clause, USAGE DISPLAY-1 or USAGE NATIONAL is implieddepending on the setting of the NSYMBOL compiler option.If you use a VALUE clause with the USAGE clause in the declaration 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 dataitem is considered to occupy the number of bytes that corresponds to thecode-page width (that is, 2).RELATED REFERENCES“NSYMBOL” on page 331Using DBCS literalsYou can use the prefix N or G to represent a DBCS literal.That is, you can specify a DBCS literal in either of these ways:v N'dbcs characters' (provided that the compiler option NSYMBOL(DBCS) is in effect)v G'dbcs characters'You can use quotation marks (") or single quotation marks (') as the delimiters ofa DBCS literal irrespective of the setting of the AP<strong>OS</strong>T or QUOTE compiler option. Youmust code the same opening and closing delimiter <strong>for</strong> a DBCS literal.The shift-out (SO) control character X'0E' must immediately follow the openingdelimiter, and the shift-in (SI) control character X'0F' must immediately precedethe closing delimiter.In addition to DBCS literals, you can use alphanumeric literals to specify anycharacter in one of the supported code pages. However, any string of DBCScharacters that is within an alphanumeric literal must be delimited by the SO andSI characters, and the DBCS compiler option must be in effect <strong>for</strong> the SO and SIcharacters to be recognized as shift codes.You cannot continue an alphanumeric literal that contains DBCS characters. Thelength of a DBCS literal is likewise limited by the available space in Area B on asingle source line. The maximum length of a DBCS literal is thus 28 double-bytecharacters.142 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


An alphanumeric literal that contains DBCS characters is processed byte by byte,that is, with semantics appropriate <strong>for</strong> single-byte characters, except when it isconverted explicitly or implicitly to national data representation, as <strong>for</strong> example inan assignment to or comparison with a national data item.RELATED TASKS“Using figurative constants” on page 28RELATED REFERENCES“DBCS” on page 317“NSYMBOL” on page 331“QUOTE/AP<strong>OS</strong>T” on page 340DBCS literals (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Testing <strong>for</strong> valid DBCS charactersThe Kanji class test tests <strong>for</strong> valid Japanese graphic characters. This testing includesKatakana, Hiragana, Roman, and Kanji character sets.The Kanji class test is done by checking characters <strong>for</strong> the range X'41' throughX'7E' in the first byte and X'41' through X'FE' in the second byte, plus the spacecharacter X'4040'.The DBCS class test tests <strong>for</strong> valid graphic characters <strong>for</strong> the code page.The DBCS class test is done by checking characters <strong>for</strong> the range X'41' throughX'FE' in both the first and second byte of each character, plus the space characterX'4040'.RELATED TASKS“Coding conditional expressions” on page 94RELATED REFERENCESClass condition (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Processing alphanumeric data items that contain DBCS dataIf you use byte-oriented operations (<strong>for</strong> example, STRING, UNSTRING, or referencemodification) on an alphanumeric data item that contains DBCS characters, resultsare unpredictable. You should instead convert the item to a national data itembe<strong>for</strong>e you process it.That is, do these steps:1. Convert the item to UTF-16 in a national data item by using a MOVE statementor the NATIONAL-OF intrinsic function.2. Process the national data item as needed.3. Convert the result back to an alphanumeric data item by using the DISPLAY-OFintrinsic function.RELATED TASKS“Joining data items (STRING)” on page 101“Splitting data items (UNSTRING)” on page 103“Referring to substrings of data items” on page 107“Converting to or from national (Unicode) representation” on page 134Chapter 7. Processing data in an international environment 143


144 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 8. Processing filesReading and writing data is an essential part of every program. Your programretrieves in<strong>for</strong>mation, processes it as you request, and then produces the results.The source of the in<strong>for</strong>mation and the target <strong>for</strong> the results can be one or more ofthe following items:v Another programv Direct-access storage devicev Magnetic tapev Printerv Terminalv Card reader or punchThe in<strong>for</strong>mation as it exists on an external device is in a physical record or block, acollection of in<strong>for</strong>mation that is handled as a unit by the system during input oroutput operations.Your <strong>COBOL</strong> program does not directly handle physical records. It processeslogical records. A logical record can correspond to a complete physical record, partof a physical record, or to parts or all of one or more physical records. Your<strong>COBOL</strong> program handles logical records exactly as you have defined them.In <strong>COBOL</strong>, a collection of logical records is a file, a sequence of pieces ofin<strong>for</strong>mation that your program can process.RELATED CONCEPTS“File organization and input-output devices”RELATED TASKS“Choosing file organization and access mode” on page 147“Allocating files” on page 149“Checking <strong>for</strong> input or output errors” on page 150File organization and input-output devicesDepending on the input-output devices, your file organization can be sequential,line sequential, indexed, or relative. Decide on the file types and devices to be usedwhen you design your program.You have the following choices of file organization:Sequential file organizationThe chronological order in which records are entered when a file is createdestablishes the arrangement of the records. Each record except the first hasa unique predecessor record, and each record except the last has a uniquesuccessor record. Once established, these relationships do not change.The access (record transmission) mode allowed <strong>for</strong> sequential files issequential only.© Copyright IBM Corp. 1991, 2009 145


Line-sequential file organizationLine-sequential files are sequential files that reside on the hierarchical filesystem (HFS) and that contain only characters as data. Each record endswith a newline character.The only access (record transmission) mode allowed <strong>for</strong> line-sequential filesis sequential.Indexed file organizationEach record in the file contains a special field whose contents <strong>for</strong>m therecord key. The position of the key is the same in each record. The indexcomponent of the file establishes the logical arrangement of the file, anordering by record key. The actual physical arrangement of the records inthe file is not significant to your <strong>COBOL</strong> program.An indexed file can also use alternate indexes in addition to the record key.These keys let you access the file using a different logical ordering of therecords.The access (record transmission) modes allowed <strong>for</strong> indexed files aresequential, random, or dynamic. When you read or write indexed filessequentially, the sequence is that of the key values.Relative file organizationRecords in the file are identified by their location relative to the beginningof the file. The first record in the file has a relative record number of 1, thetenth record has a relative record number of 10, and so on.The access (record transmission) modes allowed <strong>for</strong> relative files aresequential, random, or dynamic. When relative files are read or writtensequentially, the sequence is that of the relative record number.With IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong>, requests to the operating system <strong>for</strong> thestorage and retrieval of records from input-output devices are handled by the twoaccess methods QSAM and VSAM, and the UNIX file system.The device type upon which you elect to store your data could affect the choices offile organization available to you. Direct-access storage devices provide greaterflexibility in the file organization options. Sequential-only devices limitorganization options but have other characteristics, such as the portability of tapes,that might be useful.Sequential-only devicesTerminals, printers, card readers, and punches are called unit-record devicesbecause they process one line at a time. There<strong>for</strong>e, you must also processrecords one at a time sequentially in your program when it reads from orwrites to unit-record devices.On tape, records are ordered sequentially, so your program must processthem sequentially. Use QSAM physical sequential files when processingtape files. The records on tape can be fixed length or variable length.Direct-access storage devicesDirect-access storage devices hold many records. The record arrangementof files stored on these devices determines the ways that your program canprocess the data. When using direct-access devices, you have greaterflexibility within your program, because your can use several types of fileorganization:v Sequential (VSAM or QSAM)v Line sequential (UNIX)146 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvIndexed (VSAM)Relative (VSAM)RELATED TASKS“Allocating files” on page 149Chapter 9, “Processing QSAM files,” on page 151Chapter 10, “Processing VSAM files,” on page 179Chapter 11, “Processing line-sequential files,” on page 207“Choosing file organization and access mode”Choosing file organization and access modeThere are several guidelines you can use to determine which file organization andaccess mode to use in an application.Consider the following guidelines when choosing file organization:v If an application accesses records (whether fixed-length or variable-length) onlysequentially and does not insert records between existing records, a QSAM orVSAM sequential file is the simplest type.v If you are developing an application <strong>for</strong> UNIX that sequentially accesses recordsthat contain only printable characters and certain control characters,line-sequential files work best.v If an application requires both sequential and random access (whether recordsare fixed length or variable length), a VSAM indexed file is the most flexibletype.v If an application inserts and deletes records randomly, a relative file works well.Consider the following guidelines when choosing access mode:v If a large percentage of a file is referenced or updated in an application,sequential access is faster than random or dynamic access.v 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 <strong>for</strong>mats of <strong>COBOL</strong>filesFile organizationSequentialaccessRandomaccessDynamicaccessFixedlengthVariablelengthQSAM (physicalX X Xsequential)Line sequential X X 1 XVSAM sequential (ESDS) X X XVSAM indexed (KSDS) X X X X XVSAM relative (RRDS) X X X X X1. The data itself is in variable <strong>for</strong>mat but can be read into and written from <strong>COBOL</strong>fixed-length records.RELATED REFERENCES“Format <strong>for</strong> coding input and output” on page 148“Allowable control characters” on page 208Chapter 8. Processing files 147


Format <strong>for</strong> coding input and outputThe following code shows the general <strong>for</strong>mat of input-output coding. Explanationsof the user-supplied in<strong>for</strong>mation follow the code.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 filename01 recordname (6)nn...fieldlength & type (7) (8)nn...fieldlength & type...WORKING-STORAGE SECTION01 file-status PICTURE 99....PROCEDURE DIVISION....OPEN iomode filename (9)...READ filename...WRITE recordname...CL<strong>OS</strong>E filename...STOP RUN.The user-supplied in<strong>for</strong>mation in the code above is as follows:(1) filenameAny legal <strong>COBOL</strong> name. You must use the same file-name in the SELECTclause and in the FD entry, and on the READ, OPEN, and CL<strong>OS</strong>E statements. Inaddition, the file-name is required if you use the START or DELETEstatements. This name is not necessarily the actual name of the data set asknown to the system. Each file requires its own SELECT clause, FD entry,and input-output statements.(2) assignment-nameAny name you choose, provided that it follows <strong>COBOL</strong> and systemnaming rules. The name can be 1-30 characters long if it is a user-definedword, or 1-160 characters long if it is a literal. You code the name part ofthe assignment-name on a DD statement, in an ALLOCATE command (TSO) oras an environment variable (<strong>for</strong> example, in an export command) (UNIX).(3) org The organization can be SEQUENTIAL, LINE SEQUENTIAL, INDEXED, orRELATIVE. This clause is optional <strong>for</strong> QSAM files.(4) accessThe access mode can be SEQUENTIAL, RANDOM, orDYNAMIC. For sequential fileprocessing, including line-sequential, you can omit this clause.(5) file-statusThe <strong>COBOL</strong> file status key. You can specify the file status key as a148 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


two-character category alphanumeric or category national item, or as atwo-digit zoned decimal (USAGE DISPLAY) or national decimal (USAGENATIONAL) item.(6) recordnameThe name of the record used in the WRITE and REWRITE statements.(7) fieldlengthThe logical length of the field.(8) typeThe record <strong>for</strong>mat of the file. If you break the record entry beyond thelevel-01 description, each element should map accurately against the fieldsin the record.(9) iomodeThe INPUT or OUTPUT mode. If you are only reading from a file, code INPUT.If you are only writing to it, code OUTPUT or EXTEND. If you are both readingand writing, code I-O, except <strong>for</strong> organization LINE SEQUENTIAL.Allocating filesRELATED TASKSChapter 9, “Processing QSAM files,” on page 151Chapter 10, “Processing VSAM files,” on page 179Chapter 11, “Processing line-sequential files,” on page 207For any type of file (sequential, line sequential, indexed, or relative) in your z/<strong>OS</strong>or UNIX applications, you can define the external name with either a ddname oran environment-variable name. The external name is the name in theassignment-name of the ASSIGN clause.If the file is in the HFS, you can use either a DD definition or an environmentvariable to define the file by specifying its path name with the PATH keyword.The environment-variable name must be uppercase. The allowable attributes <strong>for</strong> itsvalue depend on the organization of the file being defined.Because you can define the external name in either of two ways, the <strong>COBOL</strong> runtime 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 DDstatement in JCL, an ALLOCATE command from TSO/E, or a user-initiateddynamic allocation.2. If the ddname is not explicitly allocated and an environment variable of thesame name is set, the value of the environment variable is used.The file is dynamically allocated using the attributes specified by theenvironment variable. At a minimum, you must specify either the PATH() orDSN() option. All options and attributes must be in uppercase, except <strong>for</strong> thepath-name suboption of the PATH option, which is case sensitive. You cannotspecify a temporary data-set name in the DSN() option.File status code 98 results from any of the following:vvvThe contents (including a value of null or all blanks) of the environmentvariable are not valid.The dynamic allocation of the file fails.The dynamic deallocation of the file fails.Chapter 8. Processing files 149


The <strong>COBOL</strong> run time checks the contents of the environment variable at eachOPEN statement. If a file with the same external name was dynamically allocatedby a previous OPEN statement, and the contents of the environment variablehave changed since that OPEN, the run time dynamically deallocates theprevious allocation and reallocates the file using the options currently set in theenvironment variable. If the contents of the environment variable have notchanged, the run time uses the current allocation.3. If neither a ddname nor an environment variable is defined, the following stepsoccur:a. If the allocation is <strong>for</strong> a QSAM file and the CBLQDA runtime option is ineffect, CBLQDA dynamic allocation processing takes place <strong>for</strong> those eligiblefiles. This type of ″implicit″ dynamic allocation persists <strong>for</strong> the life of therun unit and cannot be reallocated.b. Otherwise, the allocation fails.The <strong>COBOL</strong> run time deallocates all dynamic allocations at run unit termination,except <strong>for</strong> implicit CBLQDA allocations.RELATED TASKS“Setting and accessing environment variables” on page 438“Defining and allocating QSAM files” on page 166“Dynamically creating QSAM files” on page 163“Allocating VSAM files” on page 200Checking <strong>for</strong> input or output errorsAfter each input or output statement is per<strong>for</strong>med, the file status key is updatedwith a value that indicates the success or failure of the operation.Using a FILE STATUS clause, test the file status key after each input or outputstatement, and call an error-handling procedure if a nonzero file status code isreturned. With VSAM files, you can use a second data item in the FILE STATUSclause to get additional VSAM status code in<strong>for</strong>mation.Another way of handling errors in input and output operations is to code ERROR(synonymous with EXCEPTION) declaratives.RELATED TASKS“Handling errors in input and output operations” on page 235“Coding ERROR declaratives” on page 238“Using file status keys” on page 239150 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 9. Processing QSAM filesQueued sequential access method (QSAM) files are unkeyed files in which therecords are placed one after another, according to entry order.Your program can process these files only sequentially, retrieving (with the READstatement) records in the same order as they are in the file. Each record is placedafter the preceding record. To process QSAM files in your program, use <strong>COBOL</strong>language statements that:vvIdentify and describe the QSAM files in the ENVIRONMENT DIVISION and the DATADIVISION.Process the records in these files in the PROCEDURE DIVISION.After you have created a record, you cannot change its length or its position in thefile, and you cannot delete it. You can, however, update QSAM files ondirect-access storage devices (using REWRITE), though not in the HFS.QSAM files can be on tape, direct-access storage devices (DASDs), unit-recorddevices, and terminals. QSAM processing is best <strong>for</strong> tables and intermediatestorage.You can also access byte-stream files in the HFS using QSAM. These files arebinary byte-oriented sequential files with no record structure. The recorddefinitions that you code in your <strong>COBOL</strong> program and the length of the variablesthat you read into and write from determine the amount of data transferred.RELATED CONCEPTS“Labels <strong>for</strong> QSAM files” on page 174z/<strong>OS</strong> DFSMS: Using Data Sets (Access methods)RELATED TASKS“Defining QSAM files and records in <strong>COBOL</strong>”“Coding input and output statements <strong>for</strong> QSAM files” on page 161“Handling errors in QSAM files” on page 165“Working with QSAM files” on page 166“Processing QSAM ASCII files on tape” on page 177“Processing ASCII file labels” on page 178Defining QSAM files and records in <strong>COBOL</strong>Use the FILE-CONTROL entry to define the files in a <strong>COBOL</strong> program as QSAM files,and to associate the files with their external file-names.An external file-name (a ddname or environment variable name) is the name bywhich a file is known to the operating system. In the following example,COMMUTER-FILE-MST is your program’s name <strong>for</strong> the file; COMMUTR is the externalname:FILE-CONTROL.SELECT COMMUTER-FILE-MSTASSIGN TO S-COMMUTRORGANIZATION IS SEQUENTIALACCESS MODE IS SEQUENTIAL.© Copyright IBM Corp. 1991, 2009 151


The ASSIGN clause name can include an S- be<strong>for</strong>e the external name to documentthat the file is a QSAM file. Both the ORGANIZATION and ACCESS MODE clauses areoptional.RELATED TASKS“Establishing record <strong>for</strong>mats”“Setting block sizes” on page 159Establishing record <strong>for</strong>matsIn the FD entry in the DATA DIVISION, code the record <strong>for</strong>mat and indication ofwhether the records are blocked. In the associated record description entry orentries, specify the record-name and record length.You can code a record <strong>for</strong>mat of F, V, S, orU in the RECORDING MODE clause. <strong>COBOL</strong>determines the record <strong>for</strong>mat from the RECORD clause or from the recorddescriptions associated with the FD entry <strong>for</strong> the file. If you want the records to beblocked, code the BLOCK CONTAINS clause in the FD entry.The following example shows how the FD entry might look <strong>for</strong> a file that hasfixed-length records:FILE SECTION.FDCOMMUTER-FILE-MSTRECORDING MODE IS FBLOCK CONTAINS 0 RECORDSRECORD 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 <strong>for</strong> files in the HFS. The above example isappropriate <strong>for</strong> such a file.RELATED CONCEPTS“Logical records”RELATED TASKS“Requesting fixed-length <strong>for</strong>mat” on page 153“Requesting variable-length <strong>for</strong>mat” on page 154“Requesting spanned <strong>for</strong>mat” on page 156“Requesting undefined <strong>for</strong>mat” on page 158“Defining QSAM files and records in <strong>COBOL</strong>” on page 151RELATED REFERENCES“FILE SECTION entries” on page 14Logical records<strong>COBOL</strong> uses the term logical record in a slightly different way than z/<strong>OS</strong> QSAM.For <strong>for</strong>mat-V and <strong>for</strong>mat-S files, a QSAM logical record includes a 4-byte prefix infront of the user data portion of the record that is not included in the definition ofa <strong>COBOL</strong> logical record.For <strong>for</strong>mat-F and <strong>for</strong>mat-U files, and <strong>for</strong> HFS byte-stream files, the definitions ofQSAM logical record and <strong>COBOL</strong> logical record are identical.152 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In this in<strong>for</strong>mation, QSAM logical record refers to the QSAM definition, and logicalrecord refers to the <strong>COBOL</strong> definition.RELATED REFERENCES“Layout of <strong>for</strong>mat-F records”“Layout of <strong>for</strong>mat-V records” on page 155“Layout of <strong>for</strong>mat-S records” on page 157“Layout of <strong>for</strong>mat-U records” on page 159Requesting fixed-length <strong>for</strong>matFixed-length records are in <strong>for</strong>mat F. Use RECORDING MODE F to explicitly requestthis <strong>for</strong>mat.You can omit the RECORDING MODE clause. The compiler determines the recordingmode to be F if the length of the largest level-01 record associated with the file isnot greater than the block size coded in the BLOCK CONTAINS clause, and you takeone of the following actions:vvUse the RECORD CONTAINS integer clause (<strong>for</strong>mat-1 RECORD clause) to indicate thelength of the record in bytes.When you use this clause, the file is always fixed <strong>for</strong>mat with record lengthinteger even if there are multiple level-01 record description entries with differentlengths associated with the file.Omit the RECORD CONTAINS integer clause, but code the same fixed size and noOCCURS DEPENDING ON clause <strong>for</strong> all level-01 record description entries associatedwith the file. This fixed size is the record length.In an unblocked <strong>for</strong>mat-F file, the logical record is the same as the block.In a blocked <strong>for</strong>mat-F file, the number of logical records in a block (the blockingfactor) is constant <strong>for</strong> every block in the file except the last block, which might beshorter.Files in the HFS are never blocked.RELATED CONCEPTS“Logical records” on page 152RELATED TASKS“Requesting variable-length <strong>for</strong>mat” on page 154“Requesting spanned <strong>for</strong>mat” on page 156“Requesting undefined <strong>for</strong>mat” on page 158“Establishing record <strong>for</strong>mats” on page 152RELATED REFERENCES“Layout of <strong>for</strong>mat-F records”Layout of <strong>for</strong>mat-F records:The layout of <strong>for</strong>mat-F QSAM records is shown below.Chapter 9. Processing QSAM files 153


RELATED CONCEPTS“Logical records” on page 152RELATED TASKS“Requesting fixed-length <strong>for</strong>mat” on page 153z/<strong>OS</strong> DFSMS: Using Data Sets (Fixed-length record <strong>for</strong>mats)RELATED REFERENCES“Layout of <strong>for</strong>mat-V records” on page 155“Layout of <strong>for</strong>mat-S records” on page 157“Layout of <strong>for</strong>mat-U records” on page 159Requesting variable-length <strong>for</strong>matVariable-length records can be in <strong>for</strong>mat V or <strong>for</strong>mat D. Format-D records arevariable-length records on ASCII tape files. Format-D records are processed in thesame way as <strong>for</strong>mat-V records.Use RECORDING MODE V <strong>for</strong> both. You can omit the RECORDING MODE clause. Thecompiler determines the recording mode to be V if the largest level-01 recordassociated with the file is not greater than the block size set in the BLOCK CONTAINSclause, and you take one of the following actions:v Use the RECORD IS VARYING clause (<strong>for</strong>mat-3 RECORD clause).If you provide values <strong>for</strong> integer-1 and integer-2 (RECORD IS VARYING FROMinteger-1 TO integer-2), the maximum record length is the value coded <strong>for</strong> integer-2regardless of the lengths coded in the level-01 record description entriesassociated with the file. The integer sizes indicate the minimum and maximumrecord lengths in numbers of bytes regardless of the USAGE of the data items inthe record.If you omit integer-1 and integer-2, the maximum record length is determined tobe the size of the largest level-01 record description entry associated with thefile.vvUse the RECORD CONTAINS integer-1 TO integer-2 clause (<strong>for</strong>mat-2 RECORD clause).Make integer-1 and integer-2 match the minimum length and the maximumlength in bytes of the level-01 record description entries associated with the file.The maximum record length is the integer-2 value.Omit the RECORD clause, but code multiple level-01 records (associated with thefile) that are of different sizes or contain an OCCURS DEPENDING ON clause.The maximum record length is determined to be the size of the largest level-01record description entry associated with the file.When you specify a READ INTO statement <strong>for</strong> a <strong>for</strong>mat-V file, the record size read<strong>for</strong> that file is used in the MOVE statement generated by the compiler. Consequently,you might not get the result you expect if the record just read does not correspondto the level-01 record description. All other rules of the MOVE statement apply. For154 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


example, when you specify a MOVE statement <strong>for</strong> a <strong>for</strong>mat-V record read in by theREAD statement, the size of the record moved corresponds to its level-01 recorddescription.When you specify a READ statement <strong>for</strong> a <strong>for</strong>mat-V file followed by a MOVE of thelevel-01 record, the actual record length is not used. The program will attempt tomove the number of bytes described by the level-01 record description. If thisnumber exceeds the actual record length and extends outside the area addressableby the program, results are unpredictable. If the number of bytes described by thelevel-01 record description is shorter than the physical record read, truncation ofbytes beyond the level-01 description occurs. To find the actual length of avariable-length record, specify data-name-1 in <strong>for</strong>mat 3 of the RECORD clause of theFile Definition (FD).RELATED TASKS“Requesting fixed-length <strong>for</strong>mat” on page 153“Requesting spanned <strong>for</strong>mat” on page 156“Requesting undefined <strong>for</strong>mat” on page 158“Establishing record <strong>for</strong>mats” on page 152RELATED REFERENCES“FILE SECTION entries” on page 14“Layout of <strong>for</strong>mat-V records”<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong> (Moving from theVS <strong>COBOL</strong> II run time)Layout of <strong>for</strong>mat-V records:Format-V QSAM records have control fields that precede the data. The QSAMlogical record length is determined by adding 4 bytes (<strong>for</strong> the control fields) to therecord length defined in your program, but you must not include these 4 bytes inthe description of the record and record length.CCccThe first 4 bytes of each block contain control in<strong>for</strong>mation.LL Represents 2 bytes designating the length of the block (including the’CC’ field).BB Represents 2 bytes reserved <strong>for</strong> system use.The first 4 bytes of each logical record contain control in<strong>for</strong>mation.ll Represents 2 bytes designating the logical record length (including the’cc’ field).bb Represents 2 bytes reserved <strong>for</strong> system use.The block length is determined as follows:v Unblocked <strong>for</strong>mat-V records: CC + cc + the data portionChapter 9. Processing QSAM files 155


vBlocked <strong>for</strong>mat-V records: CC + the cc of each record + the data portion of eachrecordThe operating system provides the control bytes when the file is written; thecontrol byte fields do not appear in your description of the logical record in theDATA DIVISION of your program. <strong>COBOL</strong> allocates input and output buffers largeenough to accommodate the control bytes. These control fields in the buffer are notavailable <strong>for</strong> you to use in your program. When variable-length records are writtenon 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. Ifyou move V-mode records from an input buffer to a WORKING-STORAGE area, they’llbe moved without the control bytes.Files in the HFS are never blocked.RELATED CONCEPTS“Logical records” on page 152RELATED TASKS“Requesting variable-length <strong>for</strong>mat” on page 154RELATED REFERENCES“Layout of <strong>for</strong>mat-F records” on page 153“Layout of <strong>for</strong>mat-S records” on page 157“Layout of <strong>for</strong>mat-U records” on page 159Requesting spanned <strong>for</strong>matSpanned records are in <strong>for</strong>mat S. A spanned record is a QSAM logical record thatcan be contained in one or more physical blocks.You can code RECORDING MODE S <strong>for</strong> spanned records in QSAM files that areassigned to magnetic tape or to direct access devices. Do not request spannedrecords <strong>for</strong> files in the HFS. You can omit the RECORDING MODE clause. The compilerdetermines the recording mode to be S if the maximum record length (in bytes)plus 4 is greater than the block size set in the BLOCK CONTAINS clause.For files with <strong>for</strong>mat S in your program, the compiler determines the maximumrecord length with the same rules as are used <strong>for</strong> <strong>for</strong>mat V. The length is based onyour usage of the RECORD clause.When creating files that contain <strong>for</strong>mat-S records and a record is larger than theremaining space in a block, <strong>COBOL</strong> writes a segment of the record to fill the block.The rest of the record is stored in the next block or blocks depending on its length.<strong>COBOL</strong> supports QSAM spanned records up to 32,760 bytes in length.When retrieving files that have <strong>for</strong>mat-S records, a program can retrieve onlycomplete records.Benefits of <strong>for</strong>mat-S files: You can efficiently use external storage and stillorganize your files with logical record lengths by defining files with <strong>for</strong>mat-Srecords:vvYou can set block lengths to efficiently use track capacities on direct accessdevices.You are not required to adjust the logical record lengths to device-dependentphysical block lengths. One logical record can span two or more physical blocks.156 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vYou have greater flexibility when you want to transfer logical records betweendirect access storage types.You will, however, have additional overhead in processing <strong>for</strong>mat-S files.Format-S files and READ INTO: When you specify a READ INTO statement <strong>for</strong> a<strong>for</strong>mat-S file, the compiler generates a MOVE statement that uses the size of therecord that it just read <strong>for</strong> that file. If the record just read does not correspond tothe level-01 record description, you might not get the result that you expect. Allother rules of the MOVE statement apply.RELATED CONCEPTS“Logical records” on page 152“Spanned blocked and unblocked files”RELATED TASKS“Requesting fixed-length <strong>for</strong>mat” on page 153“Requesting variable-length <strong>for</strong>mat” on page 154“Requesting undefined <strong>for</strong>mat” on page 158“Establishing record <strong>for</strong>mats” on page 152RELATED REFERENCES“FILE SECTION entries” on page 14“Layout of <strong>for</strong>mat-S records”Spanned blocked and unblocked files: A spanned blocked QSAM file is madeup of blocks, each containing one or more logical records or segments of logicalrecords. A spanned unblocked file is made up of physical blocks, each containingone logical record or one segment of a logical record.In a spanned blocked file, a logical record can be either fixed or variable in length,and its size can be smaller than, equal to, or larger than the physical block size.There are no required relationships between logical records and physical blocksizes.In a spanned unblocked file, the logical records can be either fixed or variable inlength. When the physical block contains one logical record, the block length isdetermined by the logical record size. When a logical record has to be segmented,the system always writes the largest physical block possible. The system segmentsthe logical record when the entire logical record cannot fit on a track.RELATED CONCEPTS“Logical records” on page 152RELATED TASKS“Requesting spanned <strong>for</strong>mat” on page 156Layout of <strong>for</strong>mat-S records:Spanned records are preceded by control fields, as shown below.Chapter 9. Processing QSAM files 157


Each block is preceded by a 4-byte block descriptor field (’BDF’ in the image).There is only one block descriptor field at the beginning of each physical block.Each segment of a record in a block, even if the segment is the entire record, ispreceded by a 4-byte segment descriptor field (’SDF’ in the image). There is onesegment descriptor field <strong>for</strong> each record segment in the block. The segmentdescriptor field also indicates whether the segment is the first, the last, or anintermediate segment.You do not describe these fields in the DATA DIVISION of your <strong>COBOL</strong> program,and the fields are not available <strong>for</strong> you to use in your program.RELATED TASKS“Requesting spanned <strong>for</strong>mat” on page 156RELATED REFERENCES“Layout of <strong>for</strong>mat-F records” on page 153“Layout of <strong>for</strong>mat-V records” on page 155“Layout of <strong>for</strong>mat-U records” on page 159Requesting undefined <strong>for</strong>matFormat-U records have undefined or unspecified characteristics. With <strong>for</strong>mat U,you can process blocks that do not meet <strong>for</strong>mat-F or <strong>for</strong>mat-V specifications.When you use <strong>for</strong>mat-U files, each block of storage is one logical record. A read ofa <strong>for</strong>mat-U file returns the entire block as a record. A write to a <strong>for</strong>mat-U filewrites a record out as a block. The compiler determines the recording mode to beU only if you code RECORDING MODE U.It is recommended that you not use <strong>for</strong>mat U to update or extend a file that waswritten with a different record <strong>for</strong>mat. If you use <strong>for</strong>mat U to update a file thatwas written with a different <strong>for</strong>mat, the RECFM value in the data-set label could bechanged or the data set could contain records written in different <strong>for</strong>mats.The record length is determined in your program based on how you use theRECORD clause:vvvIf you use the RECORD CONTAINS integer clause (<strong>for</strong>mat-1 RECORD clause), the recordlength is the integer value regardless of the lengths of the level-01 recorddescription entries associated with the file. The integer size indicates the numberof bytes in a record regardless of the USAGE of its data items.If you use the RECORD IS VARYING clause (<strong>for</strong>mat-3 RECORD clause), the recordlength is determined based on whether you code integer-1 and integer-2.If you code integer-1 and integer-2 (RECORD IS VARYING FROM integer-1 TOinteger-2), the maximum record length is the integer-2 value regardless of thelengths of the level-01 record description entries associated with the file. Theinteger sizes indicate the minimum and maximum record lengths in numbers ofbytes regardless of the USAGE of the data items in the record.If you omit integer-1 and integer-2, the maximum record length is determined tobe the size of the largest level-01 record description entry associated with thefile.If you use the RECORD CONTAINS integer-1 TO integer-2 clause (<strong>for</strong>mat-2 RECORDclause), with integer-1 and integer-2 matching the minimum length and themaximum length in bytes of the level-01 record description entries associatedwith the file, the maximum record length is the integer-2 value.158 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vIf you omit the RECORD clause, the maximum record length is determined to bethe size of the largest level-01 record description entry associated with the file.Format-U files and READ INTO: When you specify a READ INTO statement <strong>for</strong> a<strong>for</strong>mat-U file, the compiler generates a MOVE statement that uses the size of therecord that it just read <strong>for</strong> that file. If the record just read does not correspond tothe level-01 record description, you might not get the result that you expect. Allother rules of the MOVE statement apply.RELATED TASKS“Requesting fixed-length <strong>for</strong>mat” on page 153“Requesting variable-length <strong>for</strong>mat” on page 154“Requesting spanned <strong>for</strong>mat” on page 156“Establishing record <strong>for</strong>mats” on page 152RELATED REFERENCES“FILE SECTION entries” on page 14“Layout of <strong>for</strong>mat-U records”Layout of <strong>for</strong>mat-U records:With <strong>for</strong>mat-U, each block of external storage is handled as a logical record. Thereare no record-length or block-length fields.RELATED CONCEPTS“Logical records” on page 152RELATED TASKS“Requesting undefined <strong>for</strong>mat” on page 158RELATED REFERENCES“Layout of <strong>for</strong>mat-F records” on page 153“Layout of <strong>for</strong>mat-V records” on page 155“Layout of <strong>for</strong>mat-S records” on page 157Setting block sizesIn <strong>COBOL</strong>, you establish the size of a physical record by using the BLOCK CONTAINSclause. If you omit this clause, the compiler assumes that the records are notblocked.Blocking QSAM files on tape and disk can enhance processing speed and minimizestorage requirements. You can block files in the z/<strong>OS</strong> UNIX file system, PDSEmembers, and spooled data sets, but doing so has no effect on how the systemstores the data.If you set the block size explicitly in the BLOCK CONTAINS clause, the size must notbe greater than the maximum block size <strong>for</strong> the device. If you specify theCHARACTERS phrase of the BLOCK CONTAINS clause, size must indicate the number ofbytes in a record regardless of the USAGE of the data items in the record. The blocksize that is set <strong>for</strong> a <strong>for</strong>mat-F file must be an integral multiple of the record length.Chapter 9. Processing QSAM files 159


If your program uses QSAM files on tape, use a physical block size of at least 12 to18 bytes. Otherwise, the block will be skipped over when a parity check occursduring one of the following actions:v Reading a block of records of fewer than 12 bytesv Writing a block of records of fewer than 18 bytesLarger blocks generally give you better per<strong>for</strong>mance. Blocks of only a few kilobytesare particularly inefficient; you should choose a block size of at least tens ofkilobytes. If you specify record blocking and omit the block size, the system willpick a block size that is optimal <strong>for</strong> device utilization and <strong>for</strong> data transfer speed.Letting z/<strong>OS</strong> determine block size: To maximize per<strong>for</strong>mance, do not explicitly setthe block size <strong>for</strong> a blocked file in your <strong>COBOL</strong> source program. For new blockeddata sets, it is simpler to allow z/<strong>OS</strong> to supply a system-determined block size. Touse this feature, follow these guidelines:v Code BLOCK CONTAINS 0 in your source program.v Do not code RECORD CONTAINS 0 in your source program.v Do not code a BLKSIZE value in the JCL DD statement.Setting block size explicitly: If you prefer to set a block size explicitly, yourprogram will be most flexible if you follow these guidelines:v Code BLOCK CONTAINS 0 in your source program.v Code a BLKSIZE value in the ddname definition (the JCL DD statement).For extended-<strong>for</strong>mat data sets on z/<strong>OS</strong>, z/<strong>OS</strong> DFSMS adds a 32-byte block suffixto the physical record. If you specify a block size explicitly (using JCL or ISPF), donot include the size of this block suffix in the block size. This block suffix is notavailable <strong>for</strong> you to use in your program. z/<strong>OS</strong> DFSMS allocates the space used toread in the block suffix. However, when you calculate how many blocks of anextended-<strong>for</strong>mat data set will fit on a track of a direct-access device, you need toinclude the size of the block suffix in the block size.If you specify a block size that is larger than 32760 directly in the BLOCK CONTAINSclause or indirectly with the use of BLOCK CONTAINS n RECORDS, the OPEN of the dataset fails with file status code 90 unless you define the data set to be on tape.For existing blocked data sets, it is simplest to:v Code BLOCK CONTAINS 0 in your source program.v Not code a BLKSIZE value in the ddname definition.When you omit the BLKSIZE from the ddname definition, the block size isautomatically obtained by the system from the data-set label.Taking advantage of LBI: You can improve the per<strong>for</strong>mance of tape data sets byusing the large block interface (LBI) <strong>for</strong> large block sizes. When the LBI isavailable, the <strong>COBOL</strong> run time automatically uses this facility <strong>for</strong> those tape files<strong>for</strong> which you use system-determined block size. LBI is also used <strong>for</strong> those files <strong>for</strong>which you explicitly define a block size in JCL or a BLOCK CONTAINS clause. Use ofthe 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 32760in the following cases is diagnosed at compile time or results in a failure at OPEN:v Spanned records160 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vOPEN I-OUsing a block size that exceeds 32760 might result in your not being able to readthe tape on another system. A tape that you create with a block size greater than32760 can be read only on a system that has a tape device that supports block sizesgreater than 32760. If you specify a block size that is too large <strong>for</strong> the file, thedevice, 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:v The BLKSZLIM keyword on the DD statement <strong>for</strong> the data setvvBLKSZLIM <strong>for</strong> the data class by using the BLKSZLIM keyword (must be set by yoursystems programmer)A block-size limit <strong>for</strong> the system in the DEVSUPxx member of SYS1.PARMLIBby 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 checkingthese items.If no BLKSIZE or BLKSZLIM value is available from any source, the system limitsBLKSIZE to 32760. You can then enable block sizes larger than 32760 in one of twoways:vvSpecify a BLKSZLIM value greater than 32760 in the DD statement <strong>for</strong> the file anduse BLOCK CONTAINS 0 in your <strong>COBOL</strong> source.Specify a value greater than 32760 <strong>for</strong> the BLKSIZE in the DD statement or in theBLOCK CONTAINS clause in your <strong>COBOL</strong> source.BLKSZLIM is device-independent.Block size and the DCB RECFM subparameter: Under z/<strong>OS</strong>, you can code the Sor T option in the DCB RECFM subparameter:v Use the S (standard) option in the DCB RECFM subparameter <strong>for</strong> a <strong>for</strong>mat-F recordwith only standard blocks (ones that have no truncated blocks or unfilled tracksin the file, except <strong>for</strong> the last block of the file). S is also supported <strong>for</strong> records ontape. It is ignored if the records are not on DASD or tape.Using this standard block option might improve input-output per<strong>for</strong>mance,especially <strong>for</strong> direct-access devices.v The T (track overflow) option <strong>for</strong> QSAM files is no longer useful.RELATED TASKS“Defining QSAM files and records in <strong>COBOL</strong>” on page 151z/<strong>OS</strong> DFSMS: Using Data SetsRELATED REFERENCES“FILE SECTION entries” on page 14“BLOCK0” on page 307BLOCK CONTAINS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Coding input and output statements <strong>for</strong> QSAM filesYou can code the following input and output statements to process a QSAM file ora byte-stream file in the HFS using QSAM: OPEN, READ, WRITE, REWRITE, and CL<strong>OS</strong>E.Chapter 9. Processing QSAM files 161


OPENREADInitiates the processing of files. You can open all QSAM files as INPUT,OUTPUT, orEXTEND (depending on device capabilities).You can also open QSAM files on direct access storage devices as I-O. Youcannot open HFS files as I-O; a file status of 37 results if you attempt to doso.Reads a record from the file. With sequential processing, your programreads one record after another in the same order in which they wereentered when the file was created.WRITE Creates a record in the file. Your program writes new records to the end ofthe file.REWRITEUpdates a record. You cannot update a file in the HFS using REWRITE.CL<strong>OS</strong>E Releases the connection between the file and your program.RELATED TASKS“Opening QSAM files”“Adding records to QSAM files” on page 163“Updating QSAM files” on page 164“Writing QSAM files to a printer or spooled data set” on page 164“Closing QSAM files” on page 165RELATED REFERENCESOPEN statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)READ statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)WRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)REWRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CL<strong>OS</strong>E statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)File status key (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Opening QSAM filesBe<strong>for</strong>e your program can use any READ, WRITE, orREWRITE statements to processrecords in a file, it must first open the file with an OPEN statement.An OPEN statement works if both of the following conditions are true:v The file is available or has been dynamically allocated.v The fixed file attributes coded in the ddname definition or the data-set label <strong>for</strong>the file match the attributes coded <strong>for</strong> that file in the SELECT clause and FD entry.Mismatches in the file-organization attributes, code set, maximum record size, orrecord <strong>for</strong>mat (fixed or variable) result in a file status code 39, and the failure ofthe OPEN statement. Mismatches in maximum record size and record <strong>for</strong>mat arenot errors when opening files in the HFS.For fixed-length QSAM files, if you code RECORD CONTAINS 0 in the FD entry, therecord size attributes are not in conflict. The record size is taken from the DDstatement or the data-set label, and the OPEN statement is successful.Code CL<strong>OS</strong>E WITH LOCK so that the file cannot be opened again while the programis running.162 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


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 inreverse order, starting with the last record. The REVERSED option is supported only<strong>for</strong> files that have fixed-length records.RELATED TASKS“Dynamically creating QSAM files”“Ensuring that file attributes match your program” on page 170RELATED REFERENCESOPEN statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Dynamically creating QSAM filesSometimes a QSAM file is unavailable on the operating system, but a <strong>COBOL</strong>program specifies that the file be created. Under certain circumstances, the file iscreated <strong>for</strong> you dynamically.A QSAM file is considered to be available on z/<strong>OS</strong> when it has been identified tothe operating system using a valid DD statement, an export command <strong>for</strong> anenvironment variable, or a TSO ALLOCATE command. Otherwise the file isunavailable.Note that a DD statement with a misspelled ddname is equivalent to a missing DDstatement, and an environment variable with a value that is not valid is equivalentto an unset variable.The QSAM file is implicitly created if you use the runtime option CBLQDA and oneof the following circumstances exists:v An optional file is being opened as EXTEND or I-O.Optional files are files that are not necessarily available each time the program isrun. You define a file that is being opened in INPUT, I-O, orEXTEND mode asoptional by coding the SELECT OPTIONAL clause in the FILE-CONTROL paragraph.v The file is being opened <strong>for</strong> OUTPUT, regardless of the OPTIONAL phrase.The file is allocated with the system default attributes established at yourinstallation and the attributes coded in the SELECT clause and FD entry in yourprogram.Do not confuse this implicit allocation mechanism with the explicit dynamicallocation of files by means of environment variables. Explicit dynamic allocationrequires that a valid environment variable be set. CBLQDA support is used onlywhen the QSAM file is unavailable as defined above, which includes no validenvironment variable being set.Under z/<strong>OS</strong>, files created using the CBLQDA option are temporary data sets and donot exist after the program has run.RELATED TASKS“Opening QSAM files” on page 162Adding records to QSAM filesTo add to a QSAM file, open the file as EXTEND and use the WRITE statement to addrecords immediately after the last record in the file.Chapter 9. Processing QSAM files 163


To add records to a file opened as I-O, you must first close the file and open it asEXTEND.RELATED REFERENCESREAD statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)WRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Updating QSAM filesYou can update QSAM files only if they reside on direct access storage devices.You cannot update files in the HFS.Replace an existing record with another record of the same length by doing thesesteps:1. Open the file as I-O.2. Use REWRITE to update an existing record. (The last file processing statementbe<strong>for</strong>e REWRITE must have been a successful READ statement.)You cannot open as I-O an extended <strong>for</strong>mat data set that you allocate incompressed <strong>for</strong>mat.RELATED REFERENCESREWRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Writing QSAM files to a printer or spooled data set<strong>COBOL</strong> provides language statements to control the size of a printed page andcontrol the vertical positioning of records.Controlling the page size: Use the LINAGE clause of the FD entry to control the sizeof your printed page: the number of lines in the top and bottom margins and inthe footing area of the page. When you use the LINAGE clause, <strong>COBOL</strong> handles thefile as if you had also requested the ADV compiler option.If you use the LINAGE clause in combination with WRITE BEFORE|AFTER ADVANCINGnn LINES, be careful about the values you set. With the ADVANCING nn LINES phrase,<strong>COBOL</strong> first calculates the sum of LINAGE-COUNTER plus nn. Subsequent actionsdepend on the size of nn. The END-OF-PAGE imperative phrase is per<strong>for</strong>med afterthe LINAGE-COUNTER is increased. Consequently, the LINAGE-COUNTER could bepointing to the next logical page instead of to the current footing area when theEND-OF-PAGE phrase is per<strong>for</strong>med.AT END-OF-PAGE or NOT AT END-OF-PAGE imperative phrases are per<strong>for</strong>med only ifthe write operation completes successfully. If the write operation is unsuccessful,control is passed to the end of the WRITE statement, and all conditional phrases areomitted.Controlling the vertical positioning of records: Use the WRITE ADVANCINGstatement to control the vertical positioning of each record you write on a printedpage.BEFORE ADVANCING prints the record be<strong>for</strong>e the page is advanced. AFTER ADVANCINGprints the record after the page is advanced.164 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Specify the number of lines the page is advanced with an integer (or an identifierwith a mnemonic-name) following ADVANCING. If you omit the ADVANCING phrase froma WRITE statement, the effect is as if you had coded:AFTER ADVANCING 1 LINERELATED REFERENCESWRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Closing QSAM filesUse the CL<strong>OS</strong>E statement to disconnect your program from a QSAM file. If you tryto close a file that is already closed, you will get a logic error.If you do not close a QSAM file, the file is automatically closed <strong>for</strong> you under thefollowing conditions, except <strong>for</strong> files defined in any <strong>OS</strong>/VS <strong>COBOL</strong> programs inthe run unit:vvvvvvWhen the run unit ends normally, the run time closes all open files that aredefined in any <strong>COBOL</strong> programs in the run unit.If the run unit ends abnormally and the TRAP(ON) runtime option is in effect, therun time closes all open files that are defined in any <strong>COBOL</strong> programs in therun unit.When Language Environment condition handling has completed and theapplication resumes in a routine other than where the condition occurred, therun time closes all open files that are defined in any <strong>COBOL</strong> programs in therun unit that might be called again and reentered.You can change the location where the program resumes running (after acondition is handled) by moving the resume cursor with the LanguageEnvironment CEEMRCR callable service or by using language constructs such asa C longjmp.When you use CANCEL <strong>for</strong> a <strong>COBOL</strong> subprogram, the run time closes any opennonexternal files that are defined in that program.When a <strong>COBOL</strong> subprogram with the INITIAL attribute returns control, the runtime closes any open nonexternal files that are defined in that program.When a thread of a multithreaded application ends, both external andnonexternal 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 CL<strong>OS</strong>Eoperations are per<strong>for</strong>med, but your EXCEPTION/ERROR and LABEL declaratives are notinvoked.Errors: If you open a QSAM file in a multithreaded application, you must close itfrom the same thread of execution from which the file was opened. Attempting toclose the file from a different thread results in a close failure with file-statuscondition 90.RELATED REFERENCESCL<strong>OS</strong>E statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Handling errors in QSAM filesWhen an input statement or output statement fails, <strong>COBOL</strong> does not takecorrective action <strong>for</strong> you. You choose whether your program should continuerunning after a less-than-severe input or output error occurs.Chapter 9. Processing QSAM files 165


<strong>COBOL</strong> provides these ways <strong>for</strong> you to intercept and handle certain QSAM inputand output errors:v End-of-file phrase (AT END)v EXCEPTION/ERROR declarativev FILE STATUS clausev INVALID KEY phraseIf you do not code a FILE STATUS key or a declarative, serious QSAM processingerrors will cause a message to be issued and a Language Environment condition tobe signaled, which will cause an abend if you specify the runtime optionABTERMENC(ABEND).If you use the FILE STATUS clause or the EXCEPTION/ERROR declarative, codeEROPT=ACC in the DCB of the DD statement <strong>for</strong> that file. Otherwise, your <strong>COBOL</strong>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 appropriateaction based on its value. If you do not check the key, your program mightcontinue, but the results will probably not be what you expected.Working with QSAM filesRELATED TASKS“Handling errors in input and output operations” on page 235To work with QSAM files in a <strong>COBOL</strong> program, you define and allocate them,retrieve them, and ensure that their file attributes match those in your program.You can also use striped extended-<strong>for</strong>mat QSAM data sets to help improveper<strong>for</strong>mance.RELATED TASKS“Defining and allocating QSAM files”“Retrieving QSAM files” on page 169“Ensuring that file attributes match your program” on page 170“Using striped extended-<strong>for</strong>mat QSAM data sets” on page 172RELATED REFERENCES“Allocation of buffers <strong>for</strong> QSAM files” on page 173Defining and allocating QSAM filesYou can define a QSAM file or a byte-stream file in the HFS by using either a DDstatement or an environment variable. Allocation of these files follows the generalrules <strong>for</strong> the allocation of <strong>COBOL</strong> files.When you use an environment variable, the name must be in uppercase. Specifythe MVS data set in one of these ways:v DSN(dataset-name)v DSN(dataset-name(member-name))dataset-name must be fully qualified and cannot be a temporary data set (that is, itmust not start with &).166 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Restriction: You cannot create a PDS or PDSE by using an environment variable.You can optionally specify the following attributes in any order after DSN:v A disposition value, one of: NEW, OLD, SHR, orMODv TRACKS or CYLv SPACE(nnn,mmm)v VOL(volume-serial)v UNIT(type)v KEEP, DELETE, CATALOG, orUNCATALOGv STORCLAS(storage-class)v MGMTCLAS(management-class)v DATACLAS(data-class)You can use either an environment variable or a DD definition to define a file in theHFS. To do so, define one of the following items with a name that matches theexternal name in the ASSIGN clause:v A DD allocation that uses PATH='absolute-path-name' and FILEDATA=BINARYvAn environment variable with a value PATH(pathname), where pathname is anabsolute path name (starting with /)For compatibility with releases of <strong>COBOL</strong> be<strong>for</strong>e <strong>COBOL</strong> <strong>for</strong> <strong>OS</strong>/390 & VMVersion 2 Release 2, you can also specify FILEDATA=TEXT when using a DD allocation<strong>for</strong> HFS files, but this use is not recommended. To process text files in the HFS, useLINE SEQUENTIAL organization. If you do use QSAM to process text files in the HFS,you cannot use environment variables to define the files.When you define a QSAM file, use the parameters as shown below.Table 20. QSAM file allocationWhat you want to do DD parameter to use EV keyword to useName the file. DSNAME (data-set name) DSNSelect the type and quantity ofinput-output devices to beallocated <strong>for</strong> the file.Give instructions <strong>for</strong> the volume inwhich the file will reside and <strong>for</strong>volume mounting.Allocate the type and amount ofspace the file needs. (Only <strong>for</strong>direct-access storage devices.)Specify the type and some of thecontents of the label associatedwith the file.Indicate whether you want tocatalog, pass, or keep the file afterthe job step is completed.Complete any data control blockin<strong>for</strong>mation that you want to add.UNITVOLUME (or let the systemchoose an output volume)SPACELABELDISPDCB subparametersUNIT <strong>for</strong> type onlyVOLSPACE <strong>for</strong> the amount ofspace (primary andsecondary only); TRACKS orCYL <strong>for</strong> the type of spacen/aNEW, OLD, SHR, MOD plusKEEP, DELETE, CATALOG, orUNCATALOGn/aChapter 9. Processing QSAM files 167


Some of the in<strong>for</strong>mation about the QSAM file must always be coded in theFILE-CONTROL paragraph, the FD entry, and other <strong>COBOL</strong> clauses. Otherin<strong>for</strong>mation must be coded in the DD statement or environment variable <strong>for</strong> outputfiles. For input files, the system can obtain in<strong>for</strong>mation from the file label (<strong>for</strong>standard label files). If DCB in<strong>for</strong>mation is provided in the DD statement <strong>for</strong> inputfiles, it overrides in<strong>for</strong>mation on the data-set label. For example, the amount ofspace allocated <strong>for</strong> a new direct-access device file can be set in the DD statement bythe SPACE parameter.You cannot express certain characteristics of QSAM files in the <strong>COBOL</strong> language,but you can code them in the DD statement <strong>for</strong> the file by using the DCB parameter.Use the subparameters of the DCB parameter to provide in<strong>for</strong>mation that the systemneeds <strong>for</strong> completing the data set definition, including the following items:vvvvBlock size (BLKSIZE=), if BLOCK CONTAINS 0 RECORDS was coded at compile time(recommended)Options to be executed if an error occurs in reading or writing a recordTRACK OVERFLOW or standard blocksMode of operation <strong>for</strong> a card reader or punchDCB attributes coded <strong>for</strong> a DD DUMMY do not override those coded in the FD entry ofyour <strong>COBOL</strong> program.“Example: setting and accessing environment variables” on page 440RELATED TASKS“Setting block sizes” on page 159“Defining QSAM files and records in <strong>COBOL</strong>” on page 151“Allocating files” on page 149RELATED REFERENCES“Parameters <strong>for</strong> creating QSAM files” on page 169MVS Program Management: User’s <strong>Guide</strong> and Reference168 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


((Parameters <strong>for</strong> creating QSAM filesThe following DD statement parameters are frequently used to create QSAM files.DSNAME=DSN=dataset-namedataset-name(member-name)&&name&&name(member-name)UNIT=( name[,unitcount] )VOLUME= ( [PRIVATE] [,RETAIN] [,vol-sequence-num] [,volume-count] ...VOL=... ,SER=(volume-serial[,volume-serial]...),REF= dsname*.ddname*.stepname.ddname*.stepname.procstep.ddnameSPACE=( TRK,(primary-quantity[,secondary-quantity][,directory-quantity]))CYLaverage-record-lengthLABEL=( [Data-set-sequence-number,] NLSLSUL,EXPDT= yydddyyyy/ddd,RETPD=xxxxDISP=(NEW ,DELETE ,DELETE )MOD ,KEEP ,KEEP,PASS ,CATLG,CATLGDCB=( subparameter-list )RELATED TASKS“Defining and allocating QSAM files” on page 166Retrieving QSAM filesYou retrieve QSAM files, cataloged or not, by using job control statements orenvironment variables.Cataloged filesAll data set in<strong>for</strong>mation, such as volume and space, is stored in the catalogand file label. All you have to code are the data set name and adisposition. When you use a DD statement, this is the DSNAME parameter andthe DISP parameter. When you use an environment variable, this is the DSNparameter and one of the parameters OLD, SHR, orMOD.Noncataloged filesSome in<strong>for</strong>mation is stored in the file label, but you must code the unitand volume in<strong>for</strong>mation, and the dsname and disposition.If you are using JCL, and you created the file in the current job step or in aprevious job step in the current job, you can refer to the previous DD statement <strong>for</strong>most of the data set in<strong>for</strong>mation. You do, however, need to code DSNAME and DISP.RELATED REFERENCES“Parameters <strong>for</strong> retrieving QSAM files” on page 170Chapter 9. Processing QSAM files 169


Parameters <strong>for</strong> retrieving QSAM filesThe following DD statement parameters are used to retrieve previously created files.RELATED TASKS“Retrieving QSAM files” on page 169Ensuring that file attributes match your programWhen the fixed file attributes in the DD statement or the data-set label and theattributes that are coded <strong>for</strong> that file in the SELECT clause and FD entry are notconsistent, an OPEN statement in your program might not work.Mismatches in the attributes <strong>for</strong> file organization, record <strong>for</strong>mat (fixed or variable),record length, or the code set result in file status code 39 and the failure of theOPEN statement. An exception exists <strong>for</strong> files in the HFS: mismatches in record<strong>for</strong>mat and record length do not cause an error.To prevent common file status 39 problems, follow the guidelines <strong>for</strong> processingexisting or new files.If you have not made a file available with a DD statement or a TSO ALLOCATEcommand, and your <strong>COBOL</strong> program specifies that the file be created, <strong>Enterprise</strong><strong>COBOL</strong> dynamically allocates the file. When the file is opened, the file attributesthat are coded in your program are used. You do not have to worry about fileattribute conflicts.Remember that in<strong>for</strong>mation in the JCL or environment variable overridesin<strong>for</strong>mation in the data-set label.170 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Processing existing files”“Processing new files” on page 172“Opening QSAM files” on page 162RELATED REFERENCES“FILE SECTION entries” on page 14Processing existing filesWhen your program processes an existing file, code the description of the file inyour <strong>COBOL</strong> program to be consistent with the file attributes of the data set. Usethe guidelines below to define the maximum record length.Table 21. Maximum record length of QSAM filesFor this <strong>for</strong>mat: Specify this:V or SExactly 4 bytes less than the length attribute of the data setFSame value as the length attribute of the data setUSame value as the length attribute of the data setThe easiest way to define variable-length (<strong>for</strong>mat-V) records in a program is to usethe RECORD IS VARYING FROM integer-1 TO integer-2 clause in the FD entry and set anappropriate value <strong>for</strong> integer-2. Express the integer sizes in bytes regardless of theunderlying USAGE of the data items in the record. For example, assume that youdetermine that the length attribute of the data set is 104 bytes (LRECL=104).Remembering that the maximum record length is determined from the RECORD ISVARYING clause and not from the level-01 record descriptions, you could define a<strong>for</strong>mat-V file in your program with this code:FILE SECTION.FDCOMMUTER-FILE-MSTRECORDING MODE IS VRECORD 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 <strong>for</strong>mat-U instead of<strong>for</strong>mat-V. If the 104 bytes are all user data, you could define the file in yourprogram with this code:FILE SECTION.FDCOMMUTER-FILE-MSTRECORDING MODE IS URECORD 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 CONTAINSinteger clause, or omit this clause and code all level-01 record descriptions to be thesame fixed size. In either case, use a value that equals the value of the lengthattribute of the data set. If you intend to use the same program to process differentfiles at run time, and those files have differing fixed lengths, avoid record-lengthconflicts by coding RECORD CONTAINS 0.If the existing file is an ASCII data set (DCB=(OPTCD=Q)), you must use the CODE-SETclause in the FD entry <strong>for</strong> the file.Chapter 9. Processing QSAM files 171


RELATED TASKS“Processing new files”“Requesting fixed-length <strong>for</strong>mat” on page 153“Requesting variable-length <strong>for</strong>mat” on page 154“Requesting undefined <strong>for</strong>mat” on page 158“Opening QSAM files” on page 162RELATED REFERENCES“FILE SECTION entries” on page 14Processing new filesIf your <strong>COBOL</strong> program writes records to a new file that will be made availablebe<strong>for</strong>e the program runs, ensure that the file attributes in the DD statement, theenvironment variable, or the allocation do not conflict with the attributes in theprogram.Usually you need to code only a minimum of parameters when predefining files.But if you need to explicitly set a length attribute <strong>for</strong> the data set (<strong>for</strong> example, youare using an ISPF allocation panel, or your DD statement is <strong>for</strong> a batch job in whichthe program uses RECORD CONTAINS 0), follow these guidelines:vFor <strong>for</strong>mat-V and <strong>for</strong>mat-S files, set a length attribute that is 4 bytes larger thanthat defined in the program.v For <strong>for</strong>mat-F and <strong>for</strong>mat-U files, set a length attribute that is the same as thatdefined in the program.v If you open the file as OUTPUT and write it to a printer, the compiler might add 1byte to the record length to account <strong>for</strong> the carriage-control character, dependingon the ADV compiler option and the language used in your program. In such acase, take the added byte into account when coding the LRECL value.For example, if your program contains the following code <strong>for</strong> a file that hasvariable-length records, the LRECL value in the DD statement or allocation should be54.FILE SECTION.FDCOMMUTER-FILE-MSTRECORDING MODE IS VRECORD 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 171“Requesting fixed-length <strong>for</strong>mat” on page 153“Requesting variable-length <strong>for</strong>mat” on page 154“Requesting undefined <strong>for</strong>mat” on page 158“Opening QSAM files” on page 162“Dynamically creating QSAM files” on page 163RELATED REFERENCES“FILE SECTION entries” on page 14Using striped extended-<strong>for</strong>mat QSAM data setsStriped extended-<strong>for</strong>mat QSAM data sets can benefit applications that process filesthat have large amounts of data or in which the time needed <strong>for</strong> I/O operationssignificantly affects overall per<strong>for</strong>mance.172 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


A striped extended-<strong>for</strong>mat QSAM data set is an extended-<strong>for</strong>mat QSAM data setthat is spread over multiple volumes, thus allowing parallel data access.For you to gain the maximum benefit from using QSAM striped data sets, z/<strong>OS</strong>DFSMS needs to be able to allocate the required number of buffers above the16-MB line. When you develop applications that contain files allocated to QSAMstriped data sets, follow these guidelines:vvvvAvoid using a QSAM striped data set <strong>for</strong> a file that cannot have buffersallocated above the 16-MB line.Omit the RESERVE clause in the FILE-CONTROL entry <strong>for</strong> the file. Doing so letsz/<strong>OS</strong> DFSMS determine the optimum number of buffers <strong>for</strong> the data set.Compile your program with the DATA(31) and RENT compiler options, and makethe load module AMODE 31.Specify the ALL31(ON) runtime option if the file is an EXTERNAL file with <strong>for</strong>mat-F,<strong>for</strong>mat-V, or <strong>for</strong>mat-U records.Note that all striped data sets are extended-<strong>for</strong>mat data sets, but not allextended-<strong>for</strong>mat data sets are striped.RELATED TASKSz/<strong>OS</strong> DFSMS: Using Data SetsRELATED REFERENCES“Allocation of buffers <strong>for</strong> QSAM files”Allocation of buffers <strong>for</strong> QSAM filesz/<strong>OS</strong> DFSMS automatically allocates buffers <strong>for</strong> storing input and output <strong>for</strong> aQSAM file above or below the 16-MB line as appropriate <strong>for</strong> the file.Most QSAM files have buffers allocated above the 16-MB line. Exceptions are:v Programs running in AMODE 24.v Programs compiled with the DATA(24) and RENT options.v Programs compiled with the NORENT and RMODE(24) options.v Programs compiled with the NORENT and RMODE(AUTO) options.v EXTERNAL files when the ALL31(OFF) runtime option is specified. To specify theALL31(ON) runtime option, all programs in the run unit must be capable ofrunning in 31-bit addressing mode.v Files allocated to the TSO terminal.v A file with <strong>for</strong>mat-S (spanned) records, if the file is any of the following:– An EXTERNAL file (even if ALL31(ON) is specified)– A file specified in a SAME RECORD AREA clause of the I-O-CONTROL paragraph– A blocked file that is opened I-O and updated using the REWRITE statementRELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Using striped extended-<strong>for</strong>mat QSAM data sets” on page 172Chapter 9. Processing QSAM files 173


Accessing HFS files using QSAMYou can process byte-stream files in the hierarchical file system (HFS) asORGANIZATION SEQUENTIAL files using QSAM. To do this, specify as theassignment-name in the ASSIGN clause either a ddname or an environment-variablename.ddnameA DD allocation that identifies the file with the keywords PATH= andFILEDATA=BINARYEnvironment-variable nameAn environment variable that holds the runtime value of the HFS path <strong>for</strong>the fileObserve the following restrictions:v Spanned record <strong>for</strong>mat is not supported.v OPEN I-O and REWRITE are not supported. If you attempt one of these operations,one of the following file-status conditions results:– 37 from OPEN I-O– 47 from REWRITE (because you could not have successfully opened the file asI-O)Usage notesv File status 39 (fixed file attribute conflict) is not en<strong>for</strong>ced <strong>for</strong> either of thefollowing types of conflicts:– Record-length conflict– Record-type conflict (fixed as opposed to variable)v A READ returns the number of bytes of the maximum logical record size <strong>for</strong> thefile except <strong>for</strong> the last record, which might be shorter.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’, thesecond READ returns ’klmnopqr ’, and the third READ results in the AT ENDcondition.For compatibility with releases of IBM <strong>COBOL</strong> be<strong>for</strong>e <strong>COBOL</strong> <strong>for</strong> <strong>OS</strong>/390 & VMVersion 2 Release 2, you can also specify FILEDATA=TEXT when using a DD allocation<strong>for</strong> HFS files, but this use is not recommended. To process text files in the HFS, useLINE SEQUENTIAL organization. If you use QSAM to process text files in the HFS,you cannot use environment variables to define the files.Labels <strong>for</strong> QSAM filesRELATED TASKS“Allocating files” on page 149“Defining and allocating QSAM files” on page 166z/<strong>OS</strong> DFSMS: Using Data Sets (Using HFS data sets)You can use labels to identify magnetic tape and direct access volumes and datasets. The operating system uses label-processing routines to identify and verifylabels and locate volumes and data sets.174 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


There are two kinds of labels: standard and nonstandard. <strong>Enterprise</strong> <strong>COBOL</strong> doesnot support nonstandard user labels. In addition, standard user labels containuser-specified in<strong>for</strong>mation about the associated data set.Standard labels consist of volume labels and groups of data-set labels. Volumelabels precede or follow data on the volume, and identify and describe the volume.The data-set labels precede or follow each data set on the volume, and identify anddescribe the data set.v The data-set labels that precede the data set are called header labels.vvvThe data-set labels that follow the data set are called trailer labels. They aresimilar to the header labels, except that they also contain a count of blocks in thedata set.The data-set label groups can optionally include standard user labels.The volume label groups can optionally include standard user labels.RELATED TASKS“Using trailer and header labels”RELATED REFERENCES“Format of standard labels” on page 176Using trailer and header labelsYou can create, examine, or update user labels when the beginning or end of adata set or volume (reel) is reached. End-of-volume or beginning-of-volume exitsare allowed. You can also create or examine intermediate trailers and headers.You can create, examine, or update up to eight header labels and eight trailerlabels on each volume of the data set. (QSAM EXTEND works in a manner identicalto OUTPUT except that the beginning-of-file label is not processed.) Labels reside onthe initial volume of a multivolume data set. This volume must be mounted asCL<strong>OS</strong>E if trailer labels are to be created, examined, or updated. Trailer labels <strong>for</strong> filesopened as INPUT or I-O are processed when a CL<strong>OS</strong>E statement is per<strong>for</strong>med <strong>for</strong> thefile that has reached an AT END condition.If you code a header or trailer with the wrong position number, the result isunpredictable. (Data management might <strong>for</strong>ce the label to the correct relativeposition.)When you use standard label processing, code the label type of the standard anduser labels (SUL) on the DD statement that describes the data set.Getting a user-label track: If you use a LABEL subparameter of SUL <strong>for</strong> direct accessvolumes, a separate user-label track is allocated when the data set is created. Thisadditional track is allocated at initial allocation and <strong>for</strong> sequential data sets atend-of-volume (volume switch). The user-label track (one per volume of asequential data set) contains both user header and user trailer labels. If a LABELname is referenced outside the user LABEL declarative, results are unpredictable.Handling user labels: The USE AFTER LABEL declarative provides procedures <strong>for</strong>handling user labels on supported files. The AFTER option indicates processing ofstandard user labels.List the labels as data-names in the LABEL RECORDS clause in the FD entry <strong>for</strong> the file.Chapter 9. Processing QSAM files 175


Table 22. Handling of QSAM user labelsWhen the file isopened as: And: Result:INPUTOUTPUTINPUT or I-OUSE ...LABEL declarative iscoded <strong>for</strong> the OPEN option or <strong>for</strong>the file.USE ...LABEL declarative iscoded <strong>for</strong> the OPEN option or <strong>for</strong>the file.CL<strong>OS</strong>E statement is per<strong>for</strong>med<strong>for</strong> the file that has reached theAT END condition.The label is read and control ispassed to the LABEL declarative.A buffer area <strong>for</strong> the label isprovided, and control is passed tothe LABEL declarative.Control is passed to the LABELdeclarative <strong>for</strong> processing trailerlabels.You can specify a special exit by using the statement GO TO MORE-LABELS. Whenthis statement results in an exit from a label DECLARATIVE SECTION, the system takesone of the following actions:vvWrites the current beginning or ending label, and then reenters the USE section atits beginning to create more labels. After creating the last label, the system exitsby per<strong>for</strong>ming the last statement of the section.Reads an additional beginning or ending label, and then reenters the USE sectionat its beginning to check more labels. When processing user labels, the systemreenters the section only if there is another user label to check. Hence, a programpath that flows through the last statement in the section is not needed.If a GO TO MORE-LABELS statement is not per<strong>for</strong>med <strong>for</strong> a user label, theDECLARATIVE SECTION is not reentered to check or create any immediatelysucceeding user labels.RELATED CONCEPTS“Labels <strong>for</strong> QSAM files” on page 174Format of standard labelsStandard labels are 80-character records that are recorded in EBCDIC or ASCII. Thefirst four characters are always used to identify the labels.Table 23. Identifiers <strong>for</strong> standard tape labelsIdentifierVOL1HDR1 or HDR2EOV1 or EOV2EOF1 or EOF2UHL1 to UHL8UTL1 to UTL8DescriptionVolume labelData set header labelsData set trailer labels (end-of-volume)Data set trailer labels (end-of-data-set)User header labelsUser trailer labelsThe <strong>for</strong>mat of the label <strong>for</strong> a direct-access volume is the almost the same as the<strong>for</strong>mat of the label group <strong>for</strong> a tape volume label group. The difference is that adata-set label of the initial DASTO volume label consists of the data set controlblock (DSCB). The DSCB appears in the volume table of contents (VTOC) andcontains the equivalent of the tape data set header and trailer, in addition tocontrol in<strong>for</strong>mation such as space allocation.176 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Standard user labelsUser labels are optional within the standard label groups. The <strong>for</strong>mat <strong>for</strong> userheader labels (UHL1-8) and user trailer labels (UTL1-8) consists of a label 80characters in length recorded in either:v EBCDIC on DASD or on IBM standard labeled tapesv ASCII or ISO/ANSI labeled tapesThe first 3 bytes consist of the characters that identify the label as either:v UHL <strong>for</strong> a user header label (at the beginning of a data set)v UTL <strong>for</strong> a user trailer label (at the end-of-volume or end-of-data set)The next byte contains the relative position of this label within a set of labels of thesame type; one to eight labels are permitted. The remaining 76 bytes consist ofuser-specified in<strong>for</strong>mation.Standard user labels are not supported <strong>for</strong> QSAM striped data sets.RELATED CONCEPTS“Labels <strong>for</strong> QSAM files” on page 174Processing QSAM ASCII files on tapeIf your program processes a QSAM ASCII file, you must request the ASCIIalphabet, define the record <strong>for</strong>mats, and define the ddname (with JCL).In addition, if your program processes signed numeric data items from ASCII files,define the numeric data as zoned decimal items with separate signs, that is, asUSAGE DISPLAY and with the SEPARATE phrase of the SIGN clause.The CODEPAGE compiler option has no effect on the code page used <strong>for</strong> conversionsbetween ASCII and EBCDIC <strong>for</strong> ASCII tape support. See the z/<strong>OS</strong> DFSMSdocumentation <strong>for</strong> in<strong>for</strong>mation about how CCSIDs used <strong>for</strong> the ASCII tape supportare selected and what the default CCSIDs are.Requesting the ASCII alphabet: In the SPECIAL-NAMES paragraph, code STANDARD-1<strong>for</strong> ASCII:ALPHABET-NAME IS STANDARD-1In the FD entry <strong>for</strong> the file, code:CODE-SET IS ALPHABET-NAMEDefining the record <strong>for</strong>mats: Process QSAM ASCII tape files with any of theserecord <strong>for</strong>mats:v Fixed length (<strong>for</strong>mat F)v Undefined (<strong>for</strong>mat U)v Variable length (<strong>for</strong>mat V)If you use variable-length records, you cannot explicitly code <strong>for</strong>mat D; instead,code RECORDING MODE V. The <strong>for</strong>mat in<strong>for</strong>mation is internally converted to D mode.D-mode records have a 4-byte record descriptor <strong>for</strong> each record.Chapter 9. Processing QSAM files 177


Defining the ddname: Under z/<strong>OS</strong>, processing ASCII files requires special JCLcoding. 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 theblock prefix)n The length of the block prefix:v For input, from 0 through 99v For output, either 0 or 4Use this value if you coded BLOCK CONTAINS 0.BLKSIZE=nn The size of the block, including the length of the block prefixLABEL=[AL|AUL|NL]AL American National Standard (ANS) labelsAUL ANS and user labelsNL No labelsOPTCD=QQ This value is required <strong>for</strong> ASCII files and is the default if the file iscreated using <strong>Enterprise</strong> <strong>COBOL</strong>.RELATED TASKS“Processing ASCII file labels”Processing ASCII file labelsRELATED REFERENCESz/<strong>OS</strong> DFSMS: Using Data Sets (Character data conversion)Standard label processing <strong>for</strong> ASCII files is the same as standard label processing<strong>for</strong> EBCDIC files. The system translates ASCII code into EBCDIC be<strong>for</strong>e processing.All ANS user labels are optional. ASCII files can have user header labels (UHLn)and user trailer labels (UTLn). There is no limit to the number of user labels at thebeginning and the end of a file; you can write as many labels as you need. All userlabels must be 80 bytes in length.To create or verify user labels (user label exit), code a USE AFTER STANDARD LABELprocedure. You cannot use USE BEFORE STANDARD LABEL procedures.ASCII files on tape can have:v ANS labelsv ANS and user labelsv No labelsAny labels on an ASCII tape must be in ASCII code only. Tapes that contain acombination of ASCII and EBCDIC cannot be read.RELATED TASKS“Processing QSAM ASCII files on tape” on page 177178 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 10. Processing VSAM filesVirtual storage access method (VSAM) is an access method <strong>for</strong> files ondirect-access storage devices. With VSAM you can load files, retrieve records fromfiles, update files, and add, replace, and delete records in files.VSAM processing has these advantages over QSAM:v Protection of data against unauthorized accessv Compatibility across systemsv Independence of devices (no need to be concerned with block size and othercontrol in<strong>for</strong>mation)v Simpler JCL (in<strong>for</strong>mation needed by the system is provided in integratedcatalogs)v Ability to use indexed file organization or relative file organizationThe table below shows how VSAM terms differ from <strong>COBOL</strong> terms and otherterms that you might be familiar with.Table 24. Comparison of VSAM, <strong>COBOL</strong>, and non-VSAM terminologyVSAM term <strong>COBOL</strong> term Similar non-VSAM termData set File Data setEntry-sequenced data set (ESDS) Sequential file QSAM data setKey-sequenced data set (KSDS) Indexed file ISAM data setRelative-record data set (RRDS) Relative file BDAM data setControl intervalControl interval size (CISZ)Buffers (BUFNI/BUFND)Access method control block (ACB)Cluster (CL)Cluster definitionAMP parameter of JCL DD statementRecord sizeBlockBlock sizeBUFNOData control block (DCB)Data setData-set allocationDCB parameter of JCL DD statementRecord lengthThe term file in this VSAM documentation refers to either a <strong>COBOL</strong> file or aVSAM data set.If you have complex requirements or frequently use VSAM, review the VSAMpublications <strong>for</strong> your operating system.RELATED CONCEPTS“VSAM files” on page 180RELATED TASKS“Defining VSAM file organization and records” on page 181“Coding input and output statements <strong>for</strong> VSAM files” on page 187“Handling errors in VSAM files” on page 195“Protecting VSAM files with a password” on page 196© Copyright IBM Corp. 1991, 2009 179


“Working with VSAM data sets under z/<strong>OS</strong> and z/<strong>OS</strong> UNIX” on page 197“Improving VSAM per<strong>for</strong>mance” on page 203RELATED REFERENCESz/<strong>OS</strong> DFSMS: Using Data Setsz/<strong>OS</strong> DFSMS Macro Instructions <strong>for</strong> Data Setsz/<strong>OS</strong> DFSMS: Access Method Services <strong>for</strong> CatalogsVSAM filesThe physical organization of VSAM data sets differs considerably from theorganizations used by other access methods.VSAM data sets are held in control intervals (CI) and control areas (CA). The sizeof the CI and CA is normally determined by the access method, and the way inwhich 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.) InVSAM sequential file organization, the records are stored in the order inwhich 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 aVSAM indexed file (KSDS), the records are ordered according to thecollating sequence of an embedded prime key field, which you define. Theprime key consists of one or more consecutive characters in the records.The prime key uniquely identifies the record and determines the sequencein which it is accessed with respect to other records. A prime key <strong>for</strong> arecord might be, <strong>for</strong> 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 therelative record number, which represents the location of the record relativeto where the file begins. The relative record number identifies the fixed- orvariable-length record.In a VSAM fixed-length RRDS, records are placed in a series offixed-length slots in storage. Each slot is associated with a relative recordnumber. For example, in a fixed-length RRDS containing 10 slots, the firstslot has a relative record number of 1, and the tenth slot has a relativerecord number of 10.In a VSAM variable-length RRDS, the records are ordered according totheir relative record number. Records are stored and retrieved according tothe relative record number that you set.Throughout this documentation, the term VSAM relative-record data set (orRRDS) is used to mean both relative-record data sets with fixed-lengthrecords and with variable-length records, unless they need to bedifferentiated.180 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The following table compares the characteristics of the different types of VSAMdata sets.Table 25. Comparison of VSAM data-set typesCharacteristicOrder of recordsEntry-sequenced data set(ESDS)Order in which they arewrittenKey-sequenced data set(KSDS)Collating sequence by keyfieldRelative-record data set(RRDS)Order of relative recordnumberAccess Sequential By key through an index By relative record number,which is handled like a keyAlternate indexesRelative byte address(RBA) and relativerecord number (RRN)of a recordSpace <strong>for</strong> addingrecordsSpace from deletingrecordsCan have one or morealternate indexes, althoughnot supported in <strong>COBOL</strong>Can have one or morealternate indexesCannot have alternate indexesRBA cannot change. RBA can change. RRN cannot change.Uses space at the end ofthe data setYou cannot delete a record,but you can reuse its space<strong>for</strong> a record of the samelength.Uses distributed free space<strong>for</strong> inserting records andchanging their lengths inplaceSpace from a deleted orshortened record isautomatically reclaimed in acontrol interval.For fixed-length RRDS, usesempty slots in the data setFor variable-length RRDS, usesdistributed free space andchanges the lengths of addedrecords in placeSpace from a deleted recordcan be reused.Spanned records Can have spanned records Can have spanned records Cannot have spanned recordsReuse as work file Can be reused unless it hasan alternate index, isassociated with key ranges,or exceeds 123 extents pervolumeCan be reused unless it hasan alternate index, isassociated with key ranges, orexceeds 123 extents pervolumeCan be reusedRELATED TASKS“Specifying sequential organization <strong>for</strong> VSAM files” on page 182“Specifying indexed organization <strong>for</strong> VSAM files” on page 182“Specifying relative organization <strong>for</strong> VSAM files” on page 184“Defining VSAM files” on page 197Defining VSAM file organization and recordsUse an entry in the FILE-CONTROL paragraph in the ENVIRONMENT DIVISION to definethe file organization and access modes <strong>for</strong> the VSAM files in your <strong>COBOL</strong>program.In the FILE SECTION of the DATA DIVISION, code a file description (FD) entry <strong>for</strong> thefile. In the associated record description entry or entries, define the record-name andrecord length. Code the logical size of the records with the RECORD clause.Important: You can process VSAM data sets in <strong>Enterprise</strong> <strong>COBOL</strong> programs onlyafter you define them with access method services.Chapter 10. Processing VSAM files 181


Table 26. VSAM file organization, access mode, and record <strong>for</strong>matFile organizationVSAM sequential(ESDS)VSAM indexed(KSDS)VSAM relative(RRDS)SequentialaccessRandomaccessDynamicaccessFixedlengthYes No No Yes YesYes Yes Yes Yes YesYes Yes Yes Yes YesVariablelengthRELATED TASKS“Specifying sequential organization <strong>for</strong> VSAM files”“Specifying indexed organization <strong>for</strong> VSAM files”“Specifying relative organization <strong>for</strong> VSAM files” on page 184“Specifying access modes <strong>for</strong> VSAM files” on page 185“Defining record lengths <strong>for</strong> VSAM files” on page 185“Using file status keys” on page 239“Using VSAM status codes (VSAM files only)” on page 241“Defining VSAM files” on page 197Specifying sequential organization <strong>for</strong> VSAM filesIdentify VSAM ESDS files in a <strong>COBOL</strong> program with the ORGANIZATION ISSEQUENTIAL clause. You can access (read or write) records in sequential files onlysequentially.After you place a record in the file, you cannot shorten, lengthen, or delete it.However, you can update (REWRITE) a record if the length does not change. Newrecords are added at the end of the file.The following example shows typical FILE-CONTROL entries <strong>for</strong> a VSAM sequentialfile (ESDS):SELECT S-FILEASSIGN TO SEQUENTIAL-AS-FILEORGANIZATION IS SEQUENTIALACCESS IS SEQUENTIALFILE STATUS IS FSTAT-CODE VSAM-CODE.RELATED CONCEPTS“VSAM files” on page 180Specifying indexed organization <strong>for</strong> VSAM filesIdentify a VSAM KSDS file in a <strong>COBOL</strong> program by using the ORGANIZATION ISINDEXED clause. Code a prime key <strong>for</strong> the record by using the RECORD KEY clause.You can also use alternate keys and an alternate index.RECORD KEY IS data-nameIn the example above, data-name is the name of the prime key field as you define itin the record description entry in the DATA DIVISION. The prime key data item canbe class alphabetic, alphanumeric, DBCS, numeric, or national. If it has USAGENATIONAL, the prime key can be category national, or can be a national-edited,182 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


numeric-edited, national decimal, or national floating-point data item. The collationof record keys is based on the binary value of the keys regardless of the class orcategory of the keys.The following example shows the statements <strong>for</strong> a VSAM indexed file (KSDS) thatis accessed dynamically. In addition to the primary key, COMMUTER-NO, an alternatekey, LOCATION-NO, is specified:SELECT I-FILEASSIGN TO INDEXED-FILEORGANIZATION IS INDEXEDACCESS IS DYNAMICRECORD KEY IS IFILE-RECORD-KEYALTERNATE RECORD KEY IS IFILE-ALTREC-KEYFILE STATUS IS FSTAT-CODE VSAM-CODE.RELATED CONCEPTS“VSAM files” on page 180RELATED TASKS“Using alternate keys”“Using an alternate index”RELATED REFERENCESRECORD KEY clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using alternate keysIn addition to the primary key, you can code one or more alternate keys <strong>for</strong> aVSAM KSDS file. By using alternate keys, you can access an indexed file to readrecords in some sequence other than the prime-key sequence.Alternate keys do not need to be unique. More than one record could be accessedif alternate keys are coded to allow duplicates. For example, you could access thefile through employee department rather than through employee number.You define the alternate key in your <strong>COBOL</strong> program with the ALTERNATE RECORDKEY clause:ALTERNATE RECORD KEY IS data-nameIn the example above, data-name is the name of the alternate key field as youdefine it in the record description entry in the DATA DIVISION. Alternate key dataitems, like prime key data items, can be class alphabetic, alphanumeric, DBCS,numeric, or national. The collation of alternate keys is based on the binary value ofthe keys regardless of the class or category of the keys.Using an alternate indexTo use an alternate index <strong>for</strong> a VSAM KSDS file, you need to define a data setcalled the alternate index (AIX) by using access method services.The AIX contains one record <strong>for</strong> each value of a given alternate key. The recordsare in sequential order by alternate-key value. Each record contains thecorresponding primary keys of all records in the associated indexed files thatcontain the alternate-key value.Chapter 10. Processing VSAM files 183


RELATED TASKS“Creating alternate indexes” on page 198Specifying relative organization <strong>for</strong> VSAM filesIdentify VSAM RRDS files in a <strong>COBOL</strong> program by using the ORGANIZATION ISRELATIVE clause. Use the RELATIVE KEY IS clause to associate each logical recordwith its relative record number.The following example shows a relative-record data set (RRDS) that is accessedrandomly by the value in the relative key:SELECT R-FILEASSIGN TO RELATIVE-FILEORGANIZATION IS RELATIVEACCESS IS RANDOMRELATIVE KEY IS RFILE-RELATIVE-KEYFILE STATUS IS FSTAT-CODE VSAM-CODE.You can use a randomizing routine to associate a key value in each record with therelative record number <strong>for</strong> that record. Although there are many techniques toconvert a record key to a relative record number, the most commonly used is thedivision/remainder technique. With this technique, you divide the key by a valueequal to the number of slots in the data set to produce a quotient and remainder.When you add one to the remainder, the result is a valid relative record number.Alternate indexes are not supported <strong>for</strong> VSAM RRDS.RELATED CONCEPTS“VSAM files” on page 180“Fixed-length and variable-length RRDS”RELATED TASKS“Using variable-length RRDS”“Defining VSAM files” on page 197Fixed-length and variable-length RRDSIn an RRDS that has fixed-length records, each record occupies one slot. You storeand retrieve records according to the relative record number of the slot. Avariable-length RRDS does not have slots; instead, the free space that you defineallows <strong>for</strong> more efficient record insertions.When you load an RRDS that has fixed-length records, you have the option ofskipping over slots and leaving them empty. When you load an RRDS that hasvariable-length records, you can skip over relative record numbers.Using variable-length RRDSTo use relative-record data sets (RRDS) that have variable-length records, you mustuse VSAM variable-length RRDS support.Do these steps:1. Define the file with the ORGANIZATION IS RELATIVE clause.2. Use FD entries to describe the records with variable-length sizes.3. Use the N<strong>OS</strong>IMVRD runtime option.4. Define the VSAM file through access-method services as an RRDS.184 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Defining VSAM files” on page 197RELATED REFERENCESz/<strong>OS</strong> DFSMS: Access Method Services <strong>for</strong> CatalogsSpecifying access modes <strong>for</strong> VSAM filesYou can access records in VSAM sequential files only sequentially. You can accessrecords in VSAM indexed and relative files in three ways: sequentially, randomly,or dynamically.For sequential access, code ACCESS IS SEQUENTIAL in the FILE-CONTROL entry.Records in indexed files are then accessed in the order of the key field selected(either primary or alternate). Records in relative files are accessed in the order ofthe relative record numbers.For random access, code ACCESS IS RANDOM in the FILE-CONTROL entry. Records inindexed files are then accessed according to the value you place in a key field.Records in relative files are accessed according to the value you place in therelative key.For dynamic access, code ACCESS IS DYNAMIC in the FILE-CONTROL entry. Dynamicaccess is a mixed sequential-random access in the same program. Using dynamicaccess, you can write one program to per<strong>for</strong>m both sequential and randomprocessing, accessing some records in sequential order and others by their keys.“Example: using dynamic access with VSAM files”RELATED TASKS“Reading records from a VSAM file” on page 192Example: using dynamic access with VSAM filesSuppose that you have an indexed file of employee records, and the employee’shourly wage <strong>for</strong>ms the record key.If your program processes those employees who earn between $15.00 and $20.00per hour and those who earn $25.00 per hour and above, using dynamic access ofVSAM files, the program would:1. Retrieve the first record randomly (with a random-retrieval READ) based on thekey of 1500.2. Read sequentially (using READ NEXT) until the salary field exceeds 2000.3. Retrieve the next record randomly, based on a key of 2500.4. Read sequentially until the end of the file.RELATED TASKS“Reading records from a VSAM file” on page 192Defining record lengths <strong>for</strong> VSAM filesYou can define VSAM records to be fixed or variable in length. <strong>COBOL</strong> determinesthe record <strong>for</strong>mat from the RECORD clause and the record descriptions that areassociated with the FD entry <strong>for</strong> a file.Chapter 10. Processing VSAM files 185


Because the concept of blocking has no meaning <strong>for</strong> VSAM files, you can omit theBLOCK CONTAINS clause. The clause is syntax-checked, but it has no effect on howthe program runs.RELATED TASKS“Defining fixed-length records”“Defining variable-length records”<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong>RELATED REFERENCES“FILE SECTION entries” on page 14Defining fixed-length recordsTo define VSAM records as fixed length, use one of these coding options.Table 27. Definition of VSAM fixed-length recordsRECORD clauseCode RECORD CONTAINSinteger.Omit the RECORD clause,but code all level-01records that areassociated with the file asthe same size; and codenone with an OCCURSDEPENDING ON clause.Clause<strong>for</strong>mat Record length Comments1 Fixed in size with alength of integer-3 bytesThe fixed size that youcodedThe lengths of thelevel-01 recorddescription entriesassociated with the filedo not matter.RELATED REFERENCESRECORD clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Defining variable-length recordsTo define VSAM records as variable length, use one of these coding options.Table 28. Definition of VSAM variable-length recordsRECORD clauseCode RECORD IS VARYINGFROM integer-6 TO integer-7.Clause<strong>for</strong>mat Maximum record length Comments3 integer-7 bytes The lengths of thelevel-01 recorddescription entriesassociated with the filedo not matter.Code RECORD IS VARYING. 3 Size of the largest level-01record description entryassociated with the fileCode RECORD CONTAINSinteger-4 TO integer-5.The compiler determinesthe maximum recordlength.2 integer-5 bytes The minimum recordlength is integer-4 bytes.186 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 28. Definition of VSAM variable-length records (continued)RECORD clauseOmit the RECORD clause,but code multiple level-01records that areassociated with the fileand are of different sizesor contain an OCCURSDEPENDING ON clause.Clause<strong>for</strong>mat Maximum record length CommentsSize of the largest level-01record description entryassociated with the fileThe compiler determinesthe maximum recordlength.When you specify a READ INTO statement <strong>for</strong> a <strong>for</strong>mat-V file, the record size that isread <strong>for</strong> that file is used in the MOVE statement generated by the compiler.Consequently, you might not get the result you expect if the record read in doesnot correspond to the level-01 record description. All other rules of the MOVEstatement apply. For example, when you specify a MOVE statement <strong>for</strong> a <strong>for</strong>mat-Vrecord read in by the READ statement, the size of the record corresponds to itslevel-01 record description.RELATED REFERENCESRECORD clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Coding input and output statements <strong>for</strong> VSAM filesUse the <strong>COBOL</strong> statements shown below to process VSAM files.OPEN To connect the VSAM data set to your <strong>COBOL</strong> program <strong>for</strong> processing.WRITE To add records to a file or load a file.START To establish the current location in the cluster <strong>for</strong> a READ NEXT statement.START does not retrieve a record; it only sets the current record pointer.READ and READ NEXTTo retrieve records from a file.REWRITETo update records.DELETE To logically remove records from indexed and relative files only.CL<strong>OS</strong>E To disconnect the VSAM data set from your program.All of the following factors determine which input and output statements you canuse <strong>for</strong> a given VSAM data set:v Access mode (sequential, random, or dynamic)v File organization (ESDS, KSDS, or RRDS)v Mode of OPEN statement (INPUT, OUTPUT, I-O, orEXTEND)The following table shows the possible combinations of statements and openmodes <strong>for</strong> sequential files (ESDS). The X indicates that you can use a statementwith the open mode shown at the top of the column.Chapter 10. Processing VSAM files 187


Table 29. I/O statements <strong>for</strong> VSAM sequential files<strong>COBOL</strong>Access mode statement OPEN INPUT OPEN OUTPUT OPEN I-O OPEN EXTENDSequential OPEN X X X XWRITE X XSTARTREAD X XREWRITEXDELETECL<strong>OS</strong>E X X X XThe following table shows the possible combinations of statements and openmodes you can use with indexed (KSDS) files and relative (RRDS) files. The Xindicates that you can use the statement with the open mode shown at the top ofthe column.Table 30. I/O statements <strong>for</strong> VSAM relative and indexed files<strong>COBOL</strong>Access mode statement OPEN INPUT OPEN OUTPUT OPEN I-O OPEN EXTENDSequential OPEN X X X XWRITE X XSTART X XREAD X XREWRITEXDELETEXCL<strong>OS</strong>E X X X XRandom OPEN X X XWRITE X XSTARTREAD X XREWRITEXDELETEXCL<strong>OS</strong>E X X XDynamic OPEN X X XWRITE X XSTART X XREAD X XREWRITEXDELETEXCL<strong>OS</strong>E X X XThe fields that you code in the FILE STATUS clause are updated by VSAM aftereach input-output statement to indicate the success or failure of the operation.188 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED CONCEPTS“File position indicator”RELATED TASKS“Opening a file (ESDS, KSDS, or RRDS)”“Reading records from a VSAM file” on page 192“Updating records in a VSAM file” on page 193“Adding records to a VSAM file” on page 193“Replacing records in a VSAM file” on page 194“Deleting records from a VSAM file” on page 194“Closing VSAM files” on page 194RELATED REFERENCESFile status key (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)File position indicatorThe file position indicator marks the next record to be accessed <strong>for</strong> sequential<strong>COBOL</strong> requests. You do not set the file position indicator in your program. It isset by successful OPEN, START, READ, and READ NEXT statements.Subsequent READ or READ NEXT requests use the established file position indicatorlocation and update it.The file position indicator is not used or affected by the output statements WRITE,REWRITE, orDELETE. The file position indicator has no meaning <strong>for</strong> randomprocessing.RELATED TASKS“Reading records from a VSAM file” on page 192Opening a file (ESDS, KSDS, or RRDS)Be<strong>for</strong>e you can use WRITE, START, READ, REWRITE, orDELETE statements to processrecords in a file, you must first open the file with an OPEN statement.File availability and creation affect OPEN processing, optional files, and file statuscodes 05 and 35. For example, if you open a file that is neither optional noravailable in EXTEND, I-O, orINPUT mode, you get file status 35 and the OPENstatement fails. If the file is OPTIONAL, the same OPEN statement creates the file andreturns file status 05.An OPEN operation works successfully only when you set fixed file attributes in theDD statement or data-set label <strong>for</strong> a file and specify consistent attributes <strong>for</strong> the filein the SELECT clause and FD entries of your <strong>COBOL</strong> program. Mismatches in thefollowing items result in a file status code 39 and the failure of the OPEN statement:v Attributes <strong>for</strong> file organization (sequential, relative, or indexed)v Prime record keyv Alternate record keysv Maximum record sizev Record type (fixed or variable)How you code the OPEN statement <strong>for</strong> a VSAM file depends on whether the file isempty (a file that has never contained records) or loaded. For either type of file,your program should check the file status key after each OPEN statement.Chapter 10. Processing VSAM files 189


RELATED TASKS“Opening an empty file”“Opening a loaded file (a file with records)” on page 191RELATED REFERENCES“Statements to load records into a VSAM file” on page 191Opening an empty fileTo open a file that has never contained records (an empty file), use a <strong>for</strong>m of theOPEN statement.Depending on the type of file that you are opening, use one of the followingstatements:v OPEN OUTPUT <strong>for</strong> ESDS files.vOPEN OUTPUT or OPEN EXTEND <strong>for</strong> KSDS and RRDS files. (Either coding has thesame effect.) If you coded the file <strong>for</strong> random or dynamic access and the file isoptional, you can use OPEN I-O.Optional files are files that are not necessarily available each time a program is run.You can define files opened in INPUT, I-O, orOUTPUT mode as optional by definingthem with the SELECT OPTIONAL clause in the FILE-CONTROL paragraph.Initially loading a file sequentially: Initially loading a file means writing recordsinto the file <strong>for</strong> the first time. Doing so is not the same as writing records into afile from which all previous records have been deleted. To initially load a VSAMfile:1. Open the file.2. Use sequential processing (ACCESS IS SEQUENTIAL). (Sequential processing isfaster than random or dynamic processing.)3. Use WRITE to add a record to the file.Using OPEN OUTPUT to load a VSAM file significantly improves the per<strong>for</strong>mance ofyour program. Using OPEN I-O or OPEN EXTEND has a negative effect on theper<strong>for</strong>mance of your program.When you load VSAM indexed files sequentially, you optimize both loadingper<strong>for</strong>mance and subsequent processing per<strong>for</strong>mance, because sequentialprocessing maintains user-defined free space. Future insertions will be moreefficient.With ACCESS IS SEQUENTIAL, you must write the records in ascending RECORD KEYorder.When you load VSAM relative files sequentially, the records are placed in the filein the ascending order of relative record numbers.Initially loading a file randomly or dynamically: You can use random or dynamicprocessing to load a file, but they are not as efficient as sequential processing.Because VSAM does not support random or dynamic processing, <strong>COBOL</strong> has toper<strong>for</strong>m some extra processing to enable you to use ACCESS IS RANDOM or ACCESSIS DYNAMIC with OPEN OUTPUT or OPEN I-O. These steps prepare the file <strong>for</strong> use andgive it the status of a loaded file because it has been used at least once.190 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In addition to extra overhead <strong>for</strong> preparing files <strong>for</strong> use, random processing doesnot consider any user-defined free space. As a result, any future insertions mightbe inefficient. Sequential processing maintains user-defined free space.When you are loading an extended-<strong>for</strong>mat VSAM data set, file status 30 will occur<strong>for</strong> the OPEN if z/<strong>OS</strong> DFSMS system-managed buffering sets the buffering to localshared resources (LSR). To successfully load the VSAM data set in this case, specifyACCBIAS=USER in the DD AMP parameter <strong>for</strong> the VSAM data set to bypasssystem-managed buffering.Loading a VSAM data set with access method services: You can load or update aVSAM data set by using the access method services REPRO command. Use REPROwhenever possible.RELATED TASKS“Opening a loaded file (a file with records)”RELATED REFERENCES“Statements to load records into a VSAM file”z/<strong>OS</strong> DFSMS: Access Method Services <strong>for</strong> Catalogs (REPRO)Statements to load records into a VSAM fileUse the statements shown below to load records into a VSAM file.Table 31. Statements to load records into a VSAM fileDivision ESDS KSDS RRDSENVIRONMENTDIVISIONSELECTASSIGNFILE STATUSPASSWORDACCESS MODESELECTASSIGNORGANIZATION IS INDEXEDRECORD KEYALTERNATE RECORD KEYFILE STATUSPASSWORDACCESS MODEDATA DIVISION FD entry FD entry FD entryPROCEDUREDIVISIONOPEN OUTPUTOPEN EXTENDWRITECL<strong>OS</strong>EOPEN OUTPUTOPEN EXTENDWRITECL<strong>OS</strong>ESELECTASSIGNORGANIZATION IS RELATIVERELATIVE KEYFILE STATUSPASSWORDACCESS MODEOPEN OUTPUTOPEN EXTENDWRITECL<strong>OS</strong>ERELATED TASKS“Opening an empty file” on page 190“Updating records in a VSAM file” on page 193Opening a loaded file (a file with records)To open a file that already contains records, use OPEN INPUT, OPEN I-O, orOPENEXTEND.If you open a VSAM entry-sequenced or relative-record file as EXTEND, the addedrecords are placed after the last existing records in the file.If you open a VSAM key-sequenced file as EXTEND, each record you add must havea record key higher than the highest record in the file.Chapter 10. Processing VSAM files 191


RELATED TASKS“Opening an empty file” on page 190“Working with VSAM data sets under z/<strong>OS</strong> and z/<strong>OS</strong> UNIX” on page 197RELATED REFERENCES“Statements to load records into a VSAM file” on page 191z/<strong>OS</strong> DFSMS: Access Method Services <strong>for</strong> CatalogsReading records from a VSAM fileUse the READ statement to retrieve (READ) records from a file. To read a record, youmust have opened the file INPUT or I-O. Your program should check the file statuskey after each READ.You can retrieve records in VSAM sequential files only in the sequence in whichthey were written.You can retrieve records in VSAM indexed and relative record files in any of thefollowing ways:SequentiallyAccording to the ascending order of the key you are using, the RECORD KEYor the ALTERNATE RECORD KEY, beginning at the current position of the fileposition indicator <strong>for</strong> indexed files, or according to ascending relativerecord locations <strong>for</strong> relative filesRandomlyIn any order, depending on how you set the RECORD KEY or ALTERNATERECORD KEY or the RELATIVE KEY be<strong>for</strong>e your READ requestDynamicallyMixed sequential and randomWith dynamic access, you can switch between reading a specific record directlyand reading records sequentially, by using READ NEXT <strong>for</strong> sequential retrieval andREAD <strong>for</strong> random retrieval (by key).When you want to read sequentially, beginning at a specific record, use STARTbe<strong>for</strong>e the READ NEXT statement to set the file position indicator to point to aparticular record. When you code START followed by READ NEXT, the next record isread and the file position indicator is reset to the next record. You can move thefile position indicator randomly by using START, but all reading is donesequentially from that point.START file-name KEY IS EQUAL TO ALTERNATE-RECORD-KEYWhen a direct READ is per<strong>for</strong>med <strong>for</strong> a VSAM indexed file, based on an alternateindex <strong>for</strong> which duplicates exist, only the first record in the data set (base cluster)with that alternate key value is retrieved. You need a series of READ NEXTstatements to retrieve each of the data set records with the same alternate key. Afile status code of 02 is returned if there are more records with the same alternatekey value to be read; a code of 00 is returned when the last record with that keyvalue has been read.RELATED CONCEPTS“File position indicator” on page 189192 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Specifying access modes <strong>for</strong> VSAM files” on page 185Updating records in a VSAM fileTo update a VSAM file, use these PROCEDURE DIVISION statements.Table 32. Statements to update records in a VSAM fileAccessmethod ESDS KSDS RRDSACCESS ISSEQUENTIALOPEN EXTENDWRITECL<strong>OS</strong>EOPEN EXTENDWRITECL<strong>OS</strong>EOPEN EXTENDWRITECL<strong>OS</strong>EorororOPEN I-OREADREWRITECL<strong>OS</strong>EOPEN I-OREADREWRITEDELETECL<strong>OS</strong>EOPEN I-OREADREWRITEDELETECL<strong>OS</strong>EACCESS ISRANDOMNot applicableOPEN I-OREADWRITEREWRITEDELETECL<strong>OS</strong>EOPEN I-OREADWRITEREWRITEDELETECL<strong>OS</strong>EACCESS ISDYNAMIC(sequentialprocessing)Not applicableOPEN I-OREAD NEXTWRITEREWRITESTARTDELETECL<strong>OS</strong>EOPEN I-OREAD NEXTWRITEREWRITESTARTDELETECL<strong>OS</strong>EACCESS ISDYNAMIC(randomprocessing)Not applicableOPEN I-OREADWRITEREWRITEDELETECL<strong>OS</strong>EOPEN I-OREADWRITEREWRITEDELETECL<strong>OS</strong>ERELATED REFERENCES“Statements to load records into a VSAM file” on page 191Adding records to a VSAM fileUse the <strong>COBOL</strong> WRITE statement to add a record to a file without replacing anyexisting records. The record to be added must not be larger than the maximumrecord size that you set when you defined the file. Your program should check thefile status key after each WRITE statement.Adding records sequentially: Use ACCESS IS SEQUENTIAL and code the WRITEstatement to add records sequentially to the end of a VSAM file that has beenopened with either OUTPUT or EXTEND.Chapter 10. Processing VSAM files 193


Sequential files are always written sequentially.For indexed files, you must write new records in ascending key sequence. If youopen the file EXTEND, the record keys of the records to be added must be higherthan the highest primary record key on the file when you opened the file.For relative files, the records must be in sequence. If you include a RELATIVE KEYdata item in the SELECT clause, the relative record number of the record to bewritten is placed in that data item.Adding records randomly or dynamically: When you write records to an indexeddata set and ACCESS IS RANDOM or ACCESS IS DYNAMIC, you can write the records inany order.Replacing records in a VSAM fileTo replace a record in a VSAM file, use REWRITE on a file that you opened as I-O. Ifthe file was not opened as I-O, the record is not rewritten and the status key is setto 49. Check the file status key after each REWRITE statement.For sequential files, the length of the replacement record must be the same as thelength of the original record. For indexed files or variable-length relative files, youcan change the length of the record you replace.To replace a record randomly or dynamically, you do not have to first READ therecord. Instead, locate the record you want to replace as follows:vvFor indexed files, move the record key to the RECORD KEY data item, and thenissue the REWRITE.For relative files, move the relative record number to the RELATIVE KEY dataitem, and then issue the REWRITE.Deleting records from a VSAM fileTo remove an existing record from an indexed or relative file, open the file I-O anduse the DELETE statement. You cannot use DELETE on a sequential file.When you use ACCESS IS SEQUENTIAL or the file contains spanned records, yourprogram must first read the record to be deleted. The DELETE then removes therecord that was read. If the DELETE is not preceded by a successful READ, thedeletion is not done and the status key value is set to 92.When you use ACCESS IS RANDOM or ACCESS IS DYNAMIC, your program does nothave to first read the record to be deleted. To delete a record, move the key of therecord to be deleted to the RECORD KEY data item, and then issue the DELETE. Yourprogram should check the file status key after each DELETE statement.Closing VSAM filesUse the CL<strong>OS</strong>E statement to disconnect your program from a VSAM file. If you tryto close a file that is already closed, you will get a logic error. Check the file statuskey after each CL<strong>OS</strong>E statement.194 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Handling errors in VSAM filesIf you do not close a VSAM file, the file is automatically closed <strong>for</strong> you under thefollowing conditions, except <strong>for</strong> files defined in any <strong>OS</strong>/VS <strong>COBOL</strong> programs inthe run unit:vvvvvvWhen the run unit ends normally, all open files defined in any <strong>COBOL</strong>programs in the run unit are closed.When the run unit ends abnormally, if the TRAP(ON) runtime option has been set,all open files defined in any <strong>COBOL</strong> programs in the run unit are closed.When Language Environment condition handling has completed and theapplication resumes in a routine other than where the condition occurred, openfiles defined in any <strong>COBOL</strong> programs in the run unit that might be called againand reentered are closed.You can change the location where a program resumes after a condition ishandled. To make this change, you can, <strong>for</strong> example, move the resume cursorwith the CEEMRCR callable service or use language constructs such as a Clongjmp statement.When you issue CANCEL <strong>for</strong> a <strong>COBOL</strong> subprogram, any open nonexternal filesdefined in that program are closed.When a <strong>COBOL</strong> subprogram with the INITIAL attribute returns control, anyopen nonexternal files defined in that program are closed.When a thread of a multithreaded application ends, both external andnonexternal files that were opened from within that same thread are closed.File status key data items in the DATA DIVISION are set when these implicit CL<strong>OS</strong>Eoperations are per<strong>for</strong>med, but your EXCEPTION/ERROR and LABEL declaratives are notinvoked.Errors: If you open a VSAM file in a multithreaded application, you must close itfrom the same thread of execution. Attempting to close the file from a differentthread results in a close failure with file-status condition 90.When an input or output statement operation fails, <strong>COBOL</strong> does not per<strong>for</strong>mcorrective action <strong>for</strong> you.All OPEN and CL<strong>OS</strong>E errors with a VSAM file, whether logical errors in yourprogram or input/output errors on the external storage media, return control toyour <strong>COBOL</strong> program even if you coded no DECLARATIVE and no FILE STATUSclause.If any other input or output statement operation fails, you choose whether yourprogram will continue running after a less-than-severe error.<strong>COBOL</strong> provides these ways <strong>for</strong> you to intercept and handle certain VSAM inputand output errors:v End-of-file phrase (AT END)v EXCEPTION/ERROR declarativev FILE STATUS clause (file status key and VSAM status code)v INVALID KEY phraseYou should define a status key <strong>for</strong> each VSAM file that you define in yourprogram. Check the status key value after each input or output request, especiallyOPEN and CL<strong>OS</strong>E.Chapter 10. Processing VSAM files 195


If you do not code a file status key or a declarative, serious VSAM processingerrors will cause a message to be issued and a Language Environment condition tobe signaled, which will cause an abend if you specify the runtime optionABTERMENC(ABEND).RELATED TASKS“Handling errors in input and output operations” on page 235“Using VSAM status codes (VSAM files only)” on page 241RELATED REFERENCESz/<strong>OS</strong> DFSMS Macro Instructions <strong>for</strong> Data Sets (VSAM macro return andreason codes)Protecting VSAM files with a passwordAlthough the preferred security mechanism on a z/<strong>OS</strong> system is RACF ® ,<strong>Enterprise</strong> <strong>COBOL</strong> also supports using explicit passwords on VSAM files toprevent unauthorized access and update.To use explicit passwords, code the PASSWORD clause in the FILE-CONTROLparagraph. Use this clause only if the catalog entry <strong>for</strong> the files includes a read oran update password:vvvIf the catalog entry includes a read password, you cannot open and access thefile in a <strong>COBOL</strong> program unless you use the PASSWORD clause in theFILE-CONTROL paragraph and describe it in the DATA DIVISION. The data-namereferred to must contain a valid password when the file is opened.If the catalog entry includes an update password, you can open and access it,but not update it, unless you code the PASSWORD clause in the FILE-CONTROLparagraph and describe it in the DATA DIVISION.If the catalog entry includes both a read password and an update password,specify the update password to both read and update the file in your program.If your program only retrieves records and does not update them, you need onlythe read password. If your program loads files or updates them, you need tospecify the update password that was cataloged.For indexed files, the PASSWORD data item <strong>for</strong> the RECORD KEY must contain the validpassword be<strong>for</strong>e the file can be successfully opened.If you password-protect a VSAM indexed file, you must also password-protecteach alternate index in order to be fully password protected. Where you place thePASSWORD clause is important because each alternate index has its own password.The PASSWORD clause must directly follow the key clause to which it applies.Example: password protection <strong>for</strong> a VSAM indexed fileThe following example shows the <strong>COBOL</strong> code used <strong>for</strong> a VSAM indexed file thathas password protection....INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT LIBFILEASSIGN TO PAYMASTORGANIZATION IS INDEXEDRECORD KEY IS EMPL-NUM196 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


PASSWORD IS BASE-PASSALTERNATE RECORD KEY IS EMPL-PHONEPASSWORD IS PATH1-PASS...WORKING-STORAGE SECTION.01 BASE-PASS PIC X(8) VALUE "25BSREAD".01 PATH1-PASS PIC X(8) VALUE "25ATREAD".Working with VSAM data sets under z/<strong>OS</strong> and z/<strong>OS</strong> UNIXBe aware of special coding considerations <strong>for</strong> VSAM files under z/<strong>OS</strong> and z/<strong>OS</strong>UNIX <strong>for</strong> access method services (IDCAMS) commands, environment variables,and JCL.A VSAM file is available if all of the following conditions are true:v You define it using access method services.v You define it <strong>for</strong> your program by providing a DD statement, an environmentvariable, or an ALLOCATE command.v It has previously contained a record.A VSAM file is unavailable if it has never contained a record, even if you havedefined the file.You always get a return code of zero on completion of the OPEN statement <strong>for</strong> aVSAM sequential file.Use the access method services REPRO command to empty a file. Deleting records inthis manner resets the high-use relative byte address (RBA) of the file to zero. Thefile is effectively empty and appears to <strong>COBOL</strong> as if it never contained a record.RELATED TASKS“Defining files to the operating system” on page 10“Defining VSAM files”“Creating alternate indexes” on page 198“Allocating VSAM files” on page 200“Sharing VSAM files through RLS” on page 202Defining VSAM filesYou can process VSAM entry-sequenced, key-sequenced, and relative-record datasets in <strong>Enterprise</strong> <strong>COBOL</strong> only after you define them through access methodservices (IDCAMS).A VSAM cluster is a logical definition <strong>for</strong> a VSAM data set and has one or twocomponents:v The data component of a VSAM cluster contains the data records.vThe index component of a VSAM key-sequenced cluster consists of the indexrecords.Use the DEFINE CLUSTER access-method services command to define VSAM datasets (clusters). This process includes creating an entry in an integrated catalogwithout any data transfer. Define the following in<strong>for</strong>mation about the cluster:v Name of the entryChapter 10. Processing VSAM files 197


vvvvvvName of the catalog to contain this definition and its password (can use defaultname)Organization (sequential, indexed, or relative)Device and volumes that the data set will occupySpace required <strong>for</strong> the data setRecord size and control interval sizes (CISIZE)Passwords (if any) required <strong>for</strong> future accessDepending on what kind of data set is in the cluster, also define the followingin<strong>for</strong>mation <strong>for</strong> each cluster:vvvFor VSAM indexed data sets (KSDS), specify length and position of the primekey in the records.For VSAM fixed-length relative-record data sets (RRDS), specify the record sizeas greater than or equal to the maximum size <strong>COBOL</strong> record:DEFINE CLUSTER NUMBEREDRECORDSIZE(n,n)When you define a data set in this way, all records are padded to the fixed slotsize n. If you use the RECORD IS VARYING ON data-name <strong>for</strong>m of the RECORD clause,a WRITE or REWRITE uses the length specified in DEPENDING ON data-name as thelength of the record to be transferred by VSAM. This data is then padded to thefixed slot size. READ statements always return the fixed slot size in the DEPENDINGON data-name.For VSAM variable-length relative-record data sets (RRDS), specify the averagesize <strong>COBOL</strong> record expected and the maximum size <strong>COBOL</strong> record expected:DEFINE CLUSTER NUMBEREDRECORDSIZE(avg,m)The average size <strong>COBOL</strong> record expected must be less than the maximum size<strong>COBOL</strong> record expected.RELATED TASKS“Creating alternate indexes”“Allocating VSAM files” on page 200“Specifying relative organization <strong>for</strong> VSAM files” on page 184RELATED REFERENCESz/<strong>OS</strong> DFSMS: Access Method Services <strong>for</strong> CatalogsCreating alternate indexesAn alternate index provides access to the records in a data set that uses more thanone key. It accesses records in the same way as the prime index key of an indexeddata set (KSDS).When planning to use an alternate index, you must know:v The type of data set (base cluster) with which the index will be associatedv Whether the keys will be unique or not uniquev Whether the index is to be password protectedv Some of the per<strong>for</strong>mance aspects of using alternate indexesBecause an alternate index is, in practice, a VSAM data set that contains pointers tothe keys of a VSAM data set, you must define the alternate index and the alternateindex path (the entity that establishes the relationship between the alternate index198 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


and the prime index). After you define an alternate index, make a catalog entry toestablish the relationship (or path) between the alternate index and its base cluster.This path allows you to access the records of the base cluster through the alternatekeys.To use an alternate index, do these steps:1. Define the alternate index by using the DEFINE ALTERNATEINDEX command. In it,specify these items:v Name of the alternate indexv Name of its related VSAM indexed data setv Location in the record of any alternate indexes and whether they are uniquev Whether alternate indexes are to be updated when the data set is changedv Name of the catalog to contain this definition and its password (can usedefault name)In your <strong>COBOL</strong> program, the alternate index is identified solely by theALTERNATE RECORD KEY clause in the FILE-CONTROL paragraph. The ALTERNATERECORD KEY definitions must match the definitions in the catalog entry. Anypassword entries that you cataloged should be coded directly after theALTERNATE RECORD KEY phrase.2. Relate the alternate index to the base cluster (the data set to which the alternateindex gives you access) by using the DEFINE PATH command. In it, specify theseitems:v Name of the pathv Alternate index to which the path is relatedv Name of the catalog that contains the alternate indexThe base cluster and alternate index are described by entries in the samecatalog.3. Load the VSAM indexed data set.4. Build the alternate index by using (typically) the BLDINDEX command. Identifythe input file as the indexed data set (base cluster) and the output file as thealternate index or its path. BLDINDEX reads all the records in the VSAM indexeddata set (or base cluster) and extracts the data needed to build the alternateindex.Alternatively, you can use the runtime option AIXBLD to build the alternateindex at run time. However, this option might adversely affect per<strong>for</strong>mance.“Example: entries <strong>for</strong> alternate indexes”RELATED TASKS“Using an alternate index” on page 183RELATED REFERENCESLanguage Environment <strong>Programming</strong> Reference (AIXBLD (<strong>COBOL</strong> only))Example: entries <strong>for</strong> alternate indexesThe following example maps the relationships between the <strong>COBOL</strong> FILE-CONTROLentry and the DD statements or environment variables <strong>for</strong> a VSAM indexed file thathas two alternate indexes.Using JCL:Chapter 10. Processing VSAM files 199


MASTERA DD DSNAME=clustername,DISP=OLD (1)//MASTERA1 DD DSNAME=path1,DISP=OLD (2)//MASTERA2 DD DSNAME=path2,DISP=OLD (3)Using environment variables:export MASTERA=DSN(clustername),OLD (1)export MASTERA=DSN(path1),OLD (2)export MASTERA=DSN(path2),OLD (3)...FILE-CONTROL.SELECT MASTER-FILE ASSIGN TO MASTERA (4)RECORD KEY IS EM-NAMEPASSWORD IS PW-BASE (5)ALTERNATE RECORD KEY IS EM-PHONE (6)PASSWORD IS PW-PATH1ALTERNATE RECORD KEY IS EM-CITY (7)PASSWORD IS PW-PATH2.(1) The base cluster name is clustername.(2) The name of the first alternate index path is path1.(3) The name of the second alternate index path is path2.(4) The ddname or environment variable name <strong>for</strong> the base cluster is specifiedwith the ASSIGN clause.(5) Passwords immediately follow their indexes.(6) The key EM-PHONE relates to the first alternate index.(7) The key EM-CITY relates to the second alternate index.RELATED TASKS“Creating alternate indexes” on page 198Allocating VSAM filesYou must predefine and catalog all VSAM data sets through the access methodservices DEFINE command. Most of the in<strong>for</strong>mation about a VSAM data set is in thecatalog, so you need to specify only minimal DD or environment variablein<strong>for</strong>mation.Allocation of VSAM files (indexed, relative, and sequential) follows the generalrules <strong>for</strong> the allocation of <strong>COBOL</strong> files.When you use an environment variable to allocate a VSAM file, the variable namemust be in uppercase. Usually the input and data buffers are the only variablesthat you are concerned about. You must specify these options in the order shown,but no others:1. DSN(dsname), where dsname is the name of the base cluster2. OLD or SHRThe basic DD statement that you need <strong>for</strong> VSAM files and the corresponding exportcommand are these://ddname DD DSN=dsname,DISP=SHR,AMP=AMORGexport evname="DSN(dsname),SHR"200 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In either case, dsname must be the same as the name used in the access methodservices DEFINE CLUSTER or DEFINE PATH command. DISP must be OLD or SHRbecause the data set is already cataloged. If you specify MOD when using JCL, thedata set is treated as OLD.AMP is a VSAM JCL parameter that supplements the in<strong>for</strong>mation that the programsupplies about the data set. AMP takes effect when your program opens the VSAMfile. Any in<strong>for</strong>mation that you set through the AMP parameter takes precedence overthe in<strong>for</strong>mation that is in the catalog or that the program supplies. The AMPparameter is required only under the following circumstances:v You use a dummy VSAM data set. For example,v//ddname DD DUMMY,AMP=AMORGYou request additional index or data buffers. For example,//ddname DD DSN=VSAM.dsname,DISP=SHR,// AMP=('BUFNI=4,BUFND=8')You cannot specify AMP if you allocate a VSAM data set with an environmentvariable.For a VSAM base cluster, specify the same system-name (ddname or environmentvariable name) that you specify in the ASSIGN clause after the SELECT clause.When you use alternate indexes in your <strong>COBOL</strong> program, you must specify notonly a system-name (using a DD statement or environment variable) <strong>for</strong> the basecluster, but also a system-name <strong>for</strong> each alternate index path. No languagemechanism exists to explicitly declare system-names <strong>for</strong> alternate index pathswithin the program. There<strong>for</strong>e, you must adhere to the following guidelines <strong>for</strong><strong>for</strong>ming the system-name (ddname or environment variable name) <strong>for</strong> eachalternate index path:v Concatenate the base cluster name with an integer.vvBegin with 1 <strong>for</strong> the path associated with the first alternate record defined <strong>for</strong>the file in your program (ALTERNATE RECORD KEY clause of the FILE-CONTROLparagraph).Increment by 1 <strong>for</strong> the path associated with each successive alternate recorddefinition <strong>for</strong> that file.For example, if the system-name of a base cluster is ABCD, the system-name <strong>for</strong> thefirst alternate index path defined <strong>for</strong> the file in your program is ABCD1, thesystem-name <strong>for</strong> the second alternate index path is ABCD2, and so on.If the length of the base cluster system-name together with the sequence numberexceeds eight characters, the base cluster portion of the system-name is truncatedon the right to reduce the concatenated result to eight characters. For example, ifthe system-name of a base cluster is ABCDEFGH, the system name of the firstalternate index path is ABCDEFG1, the tenth is ABCDEF10, and so on.RELATED TASKS“Allocating files” on page 149RELATED REFERENCESMVS Program Management: User’s <strong>Guide</strong> and ReferenceChapter 10. Processing VSAM files 201


Sharing VSAM files through RLSBy using the VSAM JCL parameter RLS, you can specify record-level sharing withVSAM. Specifying RLS is the only way to request the RLS mode when running<strong>COBOL</strong> programs.Use RLS=CR when consistent read protocols are required, and RLS=NRI when no readintegrity protocols are required. You cannot specify RLS if you allocate your VSAMdata set with an environment variableRELATED TASKS“Preventing update problems with VSAM files in RLS mode”“Handling errors in VSAM files in RLS mode” on page 203RELATED REFERENCES“Restrictions when using RLS” on page 203Preventing update problems with VSAM files in RLS modeWhen you open a VSAM data set in RLS mode <strong>for</strong> I-O (updates), the first READcauses an exclusive lock of the record regardless of the value of RLS (RLS=CR orRLS=NRI) that you specify.If the <strong>COBOL</strong> file is defined as ACCESS RANDOM, VSAM releases the exclusive lockon the record after a WRITE or REWRITE statement is issued or a READ statement isissued <strong>for</strong> another record. When a WRITE or REWRITE is done, VSAM writes therecord immediately.However, if the <strong>COBOL</strong> file is defined as ACCESS DYNAMIC, VSAM does not releasethe exclusive lock on the record after a WRITE or REWRITE statement, nor after a READstatement, unless the I-O statement causes VSAM to move to another controlinterval (CI). As a result, if a WRITE or REWRITE was done, VSAM does not write therecord until processing is moved to another CI and the lock is released. When youuse ACCESS DYNAMIC, one way to cause the record to be written immediately, torelease the exclusive lock immediately, or both, is to define the VSAM data set toallow only one record per CI.Specifying RLS=CR locks a record and prevents an update to it until another READ isrequested <strong>for</strong> another record. While a lock on the record being read is in effect,other users can request a READ <strong>for</strong> the same record, but they cannot update therecord until the read lock is released. When you specify RLS=NRI, no lock will be ineffect when a READ <strong>for</strong> input is issued. Another user might update the record.The locking rules <strong>for</strong> RLS=CR can cause the application to wait <strong>for</strong> availability of arecord lock. This wait might slow down the READ <strong>for</strong> input. You might need tomodify your application logic to use RLS=CR. Do not use the RLS parameter <strong>for</strong>batch jobs that update nonrecoverable spheres until you are sure that theapplication functions correctly in a multiple-updater environment.When you open a VSAM data set in RLS mode <strong>for</strong> INPUT or I-O processing, it isgood to issue an OPEN or START immediately be<strong>for</strong>e a READ. If there is a delaybetween the OPEN or START and the READ, another user might add records be<strong>for</strong>e therecord on which the application is positioned after the OPEN or START. The <strong>COBOL</strong>run time points explicitly to the beginning of the VSAM data set at the time whenOPEN was requested, but another user might add records that would alter the truebeginning of the VSAM data set if the READ is delayed.202 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Restrictions when using RLSWhen you use RLS mode, several restrictions apply to VSAM cluster attributes andto runtime options.Be aware of these restrictions:v The VSAM cluster attributes KEYRANGE and IMBED are not supported when youopen a VSAM file.v The VSAM cluster attribute REPLICATE is not recommended because the benefitsare negated by the system-wide buffer pool and potentially large CF cachestructure in the storage hierarchy.v The AIXBLD runtime option is not supported when you open a VSAM filebecause VSAM does not allow an empty path to be opened. If you need theAIXBLD runtime option to build the alternate index data set, open the VSAM dataset in non-RLS mode.v The SIMVRD runtime option is not supported <strong>for</strong> VSAM files.v Temporary data sets are not allowed.Handling errors in VSAM files in RLS modeIf your application accesses a VSAM data set in RLS mode, be sure to check the filestatus and VSAM feedback codes after each request.If your application encounters ″SMSVSAM server not available″ while processinginput or output, explicitly close the VSAM file be<strong>for</strong>e you try to open it again.VSAM generates return code 16 <strong>for</strong> such failures, and there is no feedback code.You can have <strong>COBOL</strong> programs check the first 2 bytes of the second file statusarea <strong>for</strong> VSAM return code 16. The <strong>COBOL</strong> run time generates message IGZ0205Wand automatically closes the file if the error occurs during OPEN processing.All other RLS mode errors return a VSAM return code of 4, 8, or 12.RELATED TASKS“Using VSAM status codes (VSAM files only)” on page 241Improving VSAM per<strong>for</strong>manceYour system programmer is most likely responsible <strong>for</strong> tuning the per<strong>for</strong>mance of<strong>COBOL</strong> and VSAM. As an application programmer, you can control the aspects ofVSAM that are listed below.Table 33. Methods <strong>for</strong> improving VSAM per<strong>for</strong>manceAspect of VSAM What you can do Rationale and commentsInvoking accessmethods serviceBuild your alternate indexes inadvance, using IDCAMS.Chapter 10. Processing VSAM files 203


Table 33. Methods <strong>for</strong> improving VSAM per<strong>for</strong>mance (continued)Aspect of VSAM What you can do Rationale and commentsBuffering For sequential access, requestmore data buffers; <strong>for</strong> randomaccess, request more indexbuffers. Specify both BUFNDand BUFNI when ACCESS ISDYNAMIC.The default is one index (BUFNI) andtwo data buffers (BUFND).Loading records,using accessmethods servicesAvoid coding additionalbuffers unless your applicationwill run interactively; thencode buffers only whenresponse-time problems arisethat might be caused bydelays in input and output.Use the access methods serviceREPRO command when:vvThe target indexed data setalready contains records.The input sequential dataset contains records to beupdated or inserted into theindexed data set.The REPRO command can update anindexed data set as fast or faster thanany <strong>COBOL</strong> program under theseconditions.If you use a <strong>COBOL</strong> programto load the file, use OPENOUTPUT and ACCESSSEQUENTIAL.File access modes For best per<strong>for</strong>mance, accessrecords sequentially.Key designMultiplealternate indexesRelative fileorganizationDesign the key in the recordsso that the high-order portionis relatively constant and thelow-order portion changesoften.Avoid using multiple alternateindexes.Use VSAM fixed-lengthrelative data sets rather thanVSAM variable-length relativedata sets.Dynamic access is less efficient thansequential access, but more efficientthan random access. Random accessresults in increased EXCPs becauseVSAM must access the index <strong>for</strong> eachrequest.This method compresses the key best.Updates must be applied through theprimary paths and are reflectedthrough multiple alternate paths,perhaps slowing per<strong>for</strong>mance.Although not as space efficient, VSAMfixed-length relative data sets are moreruntime efficient than VSAMvariable-length relative data sets.204 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 33. Methods <strong>for</strong> improving VSAM per<strong>for</strong>mance (continued)Aspect of VSAM What you can do Rationale and commentsControl intervalsizes (CISZ)Provide your systemprogrammer with in<strong>for</strong>mationabout the data access andfuture growth of your VSAMdata sets. From thisin<strong>for</strong>mation, your systemprogrammer can determinethe best control interval size(CISZ) and FREESPACE size(FSPC).Choose proper values <strong>for</strong> CISZand FSPC to minimize controlarea (CA) splits. You candiagnose the current numberof CA splits by issuing theLISTCAT ALL command on thecluster, and then compress(using EXPORT, IMPORT, orREPRO) the cluster to omit allCA splits periodically.VSAM calculates CISZ to best fit thedirect-access storage device (DASD)usage algorithm, which might not,however, be efficient <strong>for</strong> yourapplication.An average CISZ of 4K is suitable <strong>for</strong>most applications. A smaller CISZmeans faster retrieval <strong>for</strong> randomprocessing at the expense of inserts(that is, more CISZ splits and there<strong>for</strong>emore space in the data set). A largerCISZ results in the transfer of more dataacross the channel <strong>for</strong> each READ. This ismore efficient <strong>for</strong> sequential processing,similar to a large <strong>OS</strong> BLKSIZE.Many control area (CA) splits areunfavorable <strong>for</strong> VSAM per<strong>for</strong>mance.The FREESPACE value can affect CAsplits, depending on how the file isused.RELATED TASKS“Specifying access modes <strong>for</strong> VSAM files” on page 185z/<strong>OS</strong> DFSMS: Using Data Sets (Building a resource pool, Selecting the optimalpercentage of free space)RELATED REFERENCESz/<strong>OS</strong> DFSMS: Access Method Services <strong>for</strong> CatalogsChapter 10. Processing VSAM files 205


206 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 11. Processing line-sequential filesLine-sequential files reside in the hierarchical file system (HFS) and contain onlyprintable characters and certain control characters as data. Each record ends withan EBCDIC newline character (X’15’), which is not included in the record length.Because these are sequential files, records are placed one after another according toentry order. Your program can process these files only sequentially, retrieving (withthe READ statement) records in the same order as they are in the file. A new recordis placed after the preceding record.To process line-sequential files in your program, use <strong>COBOL</strong> language statementsthat:vvIdentify and describe the files in the ENVIRONMENT DIVISION and the DATADIVISIONProcess the records in the files in the PROCEDURE DIVISIONAfter you have created a record, you cannot change its length or its position in thefile, and you cannot delete it.RELATED TASKS“Defining line-sequential files and records in <strong>COBOL</strong>”“Describing the structure of a line-sequential file” on page 208“Coding input-output statements <strong>for</strong> line-sequential files” on page 209“Handling errors in line-sequential files” on page 212“Defining and allocating line-sequential files” on page 209UNIX System Services User’s <strong>Guide</strong>RELATED REFERENCES“Allowable control characters” on page 208Defining line-sequential files and records in <strong>COBOL</strong>Use the FILE-CONTROL paragraph in the ENVIRONMENT DIVISION to define the files ina <strong>COBOL</strong> program as line-sequential files, and to associate the files with thecorresponding external file-names (ddnames or environment variable names).An external file-name is the name by which a file is known to the operatingsystem. In the following example, COMMUTER-FILE is the name that your programuses <strong>for</strong> the file; COMMUTR is the external name:FILE-CONTROL.SELECT COMMUTER-FILEASSIGN TO COMMUTRORGANIZATION IS LINE SEQUENTIALACCESS MODE IS SEQUENTIALFILE STATUS IS ECODE.The ASSIGN assignment-name clause must not include an organization field (S- orAS-) be<strong>for</strong>e the external name. The ACCESS phrase and the FILE STATUS clause areoptional.RELATED TASKS“Describing the structure of a line-sequential file” on page 208© Copyright IBM Corp. 1991, 2009 207


“Coding input-output statements <strong>for</strong> line-sequential files” on page 209“Defining and allocating line-sequential files” on page 209RELATED REFERENCES“Allowable control characters”Allowable control charactersThe control characters shown in the table below are the only characters other thanprintable characters that line-sequential files can contain. The hexadecimal valuesare in EBCDIC.Hexadecimal valueX’05’X’0B’X’0C’X’0D’X’0E’X’0F’X’15’X’16’X’2F’Control characterHorizontal tabVertical tabForm feedCarriage returnDBCS shift-outDBCS shift-inNewlineBackspaceAlarmThe newline character is treated as a record delimiter. The other control charactersare treated as data and are part of the record.RELATED TASKS“Defining line-sequential files and records in <strong>COBOL</strong>” on page 207Describing the structure of a line-sequential fileIn the FILE SECTION, code a file description (FD) entry <strong>for</strong> the file. In the associatedrecord description entry or entries, define the record-name and record length.Code the logical size in bytes of the records by using the RECORD clause.Line-sequential files are stream files. Because of their character-oriented nature, thephysical records are of variable length.The following examples show how the FD entry might look <strong>for</strong> a line-sequentialfile:With fixed-length records:FILE SECTION.FD COMMUTER-FILERECORD CONTAINS 80 CHARACTERS.01 COMMUTER-RECORD.05 COMMUTER-NUMBER PIC X(16).05 COMMUTER-DESCRIPTION PIC X(64).With variable-length records:208 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


FILE SECTION.FDCOMMUTER-FILERECORD VARYING FROM 16 TO 80 CHARACTERS.01 COMMUTER-RECORD.05 COMMUTER-NUMBER PIC X(16).05 COMMUTER-DESCRIPTION PIC X(64).If you code the same fixed size and no OCCURS DEPENDING ON clause <strong>for</strong> any level-01record description entries associated with the file, that fixed size is the logicalrecord length. However, because blanks at the end of a record are not written tothe file, the physical records might be of varying lengths.RELATED TASKS“Defining line-sequential files and records in <strong>COBOL</strong>” on page 207“Coding input-output statements <strong>for</strong> line-sequential files”“Defining and allocating line-sequential files”RELATED REFERENCESData division--file description entries (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Defining and allocating line-sequential filesYou can define a line-sequential file in the HFS by using either a DD statement oran environment variable. Allocation of these files follows the general rules <strong>for</strong>allocating <strong>COBOL</strong> files.To define a line-sequential file, code a DD allocation or an environment variablewith a name that matches the external name in the ASSIGN clause:v A DD allocation:– A DD statement that specifies PATH='absolute-path-name'– A TSO allocation that specifies PATH('absolute-path-name')You can optionally also specify these options:– PATHOPTS– PATHMODE– PATHDISPvAn environment variable with a value of PATH(absolute-path-name). No othervalues can be specified.For example, to have your program use HFS file /u/myfiles/commuterfile <strong>for</strong> a<strong>COBOL</strong> file that has an assignment-name of COMMUTR, you could use the followingcommand:export COMMUTR="PATH(/u/myfiles/commuterfile)"RELATED TASKS“Allocating files” on page 149“Defining line-sequential files and records in <strong>COBOL</strong>” on page 207RELATED REFERENCESMVS Program Management: User’s <strong>Guide</strong> and ReferenceCoding input-output statements <strong>for</strong> line-sequential filesCode the input and output statements shown below to process a line-sequentialfile.Chapter 11. Processing line-sequential files 209


OPENREADWRITECL<strong>OS</strong>ETo initiate the processing of a file.You can open a line-sequential file as INPUT, OUTPUT, orEXTEND. You cannotopen a line-sequential file as I-O.To read a record from a file.With sequential processing, a program reads one record after another inthe same order in which the records were entered when the file wascreated.To create a record in a file.A program writes new records to the end of the file.To release the connection between a file and the program.RELATED TASKS“Defining line-sequential files and records in <strong>COBOL</strong>” on page 207“Describing the structure of a line-sequential file” on page 208“Opening line-sequential files”“Reading records from line-sequential files”“Adding records to line-sequential files” on page 211“Closing line-sequential files” on page 211“Handling errors in line-sequential files” on page 212RELATED REFERENCESOPEN statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)READ statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)WRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CL<strong>OS</strong>E statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Opening line-sequential filesBe<strong>for</strong>e your program can use any READ or WRITE statements to process records in afile, it must first open the file with an OPEN statement. An OPEN statement works ifthe file is available or has been dynamically allocated.Code CL<strong>OS</strong>E WITH LOCK so that the file cannot be opened again while the programis running.RELATED TASKS“Reading records from line-sequential files”“Adding records to line-sequential files” on page 211“Closing line-sequential files” on page 211“Defining and allocating line-sequential files” on page 209RELATED REFERENCESOPEN statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CL<strong>OS</strong>E statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Reading records from line-sequential filesTo read from a line-sequential file, open the file and use the READ statement. Yourprogram reads one record after another in the same order in which the recordswere entered when the file was created.210 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Characters in the file record are read one at a time into the record area until one ofthe following conditions occurs:v The record delimiter (the EBCDIC newline character) is encountered.The delimiter is discarded and the remainder of the record area is filled withspaces. (Record area is longer than the file record.)v The entire record area is filled with characters.If the next unread character is the record delimiter, it is discarded. The next READreads from the first character of the next record. (Record area is the same lengthas the file record.)Otherwise the next unread character is the first character to be read by the nextREAD. (Record area is shorter than the file record.)v End-of-file is encountered.The remainder of the record area is filled with spaces. (Record area is longerthan the file record.)RELATED TASKS“Opening line-sequential files” on page 210“Adding records to line-sequential files”“Closing line-sequential files”“Defining and allocating line-sequential files” on page 209RELATED REFERENCESOPEN statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)WRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Adding records to line-sequential filesTo add to a line-sequential file, open the file as EXTEND and use the WRITE statementto add records immediately after the last record in the file.Blanks at the end of the record area are removed, and the record delimiter isadded. The characters in the record area from the first character up to andincluding the added record delimiter are written to the file as one record.Records written to line-sequential files must contain only USAGE DISPLAY andDISPLAY-1 items. Zoned decimal data items must be unsigned or declared with theSEPARATE phrase of the SIGN clause if signed.RELATED TASKS“Opening line-sequential files” on page 210“Reading records from line-sequential files” on page 210“Closing line-sequential files”“Defining and allocating line-sequential files” on page 209RELATED REFERENCESOPEN statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)WRITE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Closing line-sequential filesUse the CL<strong>OS</strong>E statement to disconnect your program from a line-sequential file. Ifyou try to close a file that is already closed, you will get a logic error.Chapter 11. Processing line-sequential files 211


If you do not close a line-sequential file, the file is automatically closed <strong>for</strong> youunder the following conditions:v When the run unit ends normally.v When the run unit ends abnormally, if the TRAP(ON) runtime option is set.vWhen Language Environment condition handling is completed and theapplication resumes in a routine other than where the condition occurred, openfiles defined in any <strong>COBOL</strong> programs in the run unit that might be called againand reentered are closed.You can change the location where the program resumes (after a condition ishandled) by moving the resume cursor with the Language EnvironmentCEEMRCR callable service or using HLL language constructs such as a Clongjmp call.File status codes are set when these implicit CL<strong>OS</strong>E operations are per<strong>for</strong>med, butEXCEPTION/ERROR declaratives are not invoked.RELATED TASKS“Opening line-sequential files” on page 210“Reading records from line-sequential files” on page 210“Adding records to line-sequential files” on page 211“Defining and allocating line-sequential files” on page 209RELATED REFERENCESCL<strong>OS</strong>E statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Handling errors in line-sequential filesWhen an input or output statement fails, <strong>COBOL</strong> does not take corrective action<strong>for</strong> you. You choose whether your program should continue running after an inputor output statement fails.<strong>COBOL</strong> provides these language elements <strong>for</strong> intercepting and handling certainline-sequential input and output errors:v End-of-file phrase (AT END)v EXCEPTION/ERROR declarativev FILE STATUS clauseIf you do not use one of these techniques, an error in processing input or outputraises a Language Environment condition.If you use the FILE STATUS clause, be sure to check the key and take appropriateaction based on its value. If you do not check the key, your program mightcontinue, but the results will probably not be what you expected.RELATED TASKS“Coding input-output statements <strong>for</strong> line-sequential files” on page 209“Handling errors in input and output operations” on page 235212 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 12. Sorting and merging filesYou can arrange records in a particular sequence by using a SORT or MERGEstatement. You can mix SORT and MERGE statements in the same <strong>COBOL</strong> program.SORT statementAccepts input (from a file or an internal procedure) that is not in sequence,and produces output (to a file or an internal procedure) in a requestedsequence. You can add, delete, or change records be<strong>for</strong>e or after they aresorted.MERGE statementCompares records from two or more sequenced files and combines them inorder. You can add, delete, or change records after they are merged.A program can contain any number of sort and merge operations. They can be thesame operation per<strong>for</strong>med many times or different operations. However, oneoperation must finish be<strong>for</strong>e another begins.With <strong>Enterprise</strong> <strong>COBOL</strong>, your IBM licensed program <strong>for</strong> sorting and merging mustbe DFSORT or an equivalent. Where DFSORT is mentioned, you can use anyequivalent sort or merge product.<strong>COBOL</strong> programs that contain SORT or MERGE statements can reside above or belowthe 16-MB line.The steps you take to sort or merge are generally as follows:1. Describe the sort or merge file to be used <strong>for</strong> sorting or merging.2. Describe the input to be sorted or merged. If you want to process the recordsbe<strong>for</strong>e you sort them, code an input procedure.3. Describe the output from sorting or merging. If you want to process the recordsafter you sort or merge them, code an output procedure.4. Request the sort or merge.5. Determine whether the sort or merge operation was successful.Restrictions:v You cannot run a <strong>COBOL</strong> program that contains SORT or MERGE statements underz/<strong>OS</strong> UNIX. This restriction includes BPXBATCH.v You cannot use SORT or MERGE statements in programs compiled with the THREADoption. This includes programs that use object-oriented syntax andmultithreaded applications, both of which require the THREAD option.RELATED CONCEPTS“Sort and merge process” on page 214RELATED TASKS“Describing the sort or merge file” on page 214“Describing the input to sorting or merging” on page 215“Describing the output from sorting or merging” on page 217“Requesting the sort or merge” on page 220“Determining whether the sort or merge was successful” on page 224“Stopping a sort or merge operation prematurely” on page 225© Copyright IBM Corp. 1991, 2009 213


“Improving sort per<strong>for</strong>mance with FASTSRT” on page 225“Controlling sort behavior” on page 228DFSORT Application <strong>Programming</strong> <strong>Guide</strong>Sort and merge processRELATED REFERENCES“CICS SORT application restrictions” on page 232SORT statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MERGE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)During the sorting of a file, all of the records in the file are ordered according tothe contents of one or more fields (keys) in each record. You can sort the records ineither ascending or descending order of each key.If there are multiple keys, the records are first sorted according to the content ofthe first (or primary) key, then according to the content of the second key, and soon.To sort a file, use the <strong>COBOL</strong> SORT statement.During the merging of two or more files (which must already be sorted), therecords are combined and ordered according to the contents of one or more keys ineach record. You can order the records in either ascending or descending order ofeach key. As with sorting, the records are first ordered according to the content ofthe primary key, then according to the content of the second key, and so on.Use MERGE ...USING to name the files that you want to combine into onesequenced file. The merge operation compares keys in the records of the inputfiles, and passes the sequenced records one by one to the RETURN statement of anoutput procedure or to the file that you name in the GIVING phrase.RELATED TASKS“Setting sort or merge criteria” on page 221RELATED REFERENCESSORT statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MERGE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Describing the sort or merge fileDescribe the sort file to be used <strong>for</strong> sorting or merging. You need SELECT clausesand SD entries even if you are sorting or merging data items only fromWORKING-STORAGE or LOCAL-STORAGE.Code as follows:1. Write one or more SELECT clauses in the FILE-CONTROL paragraph of theENVIRONMENT DIVISION to name a sort file. For example:ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT Sort-Work-1 ASSIGN TO SortFile.Sort-Work-1 is the name of the file in your program. Use this name to refer tothe file.214 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


2. Describe the sort file in an SD entry in the FILE SECTION of the DATA DIVISION.Every SD entry must contain a record description. For example:DATA DIVISION.FILE SECTION.SDSort-Work-1RECORD CONTAINS 100 CHARACTERS.01 SORT-WORK-1-AREA.05 SORT-KEY-1 PIC X(10).05 SORT-KEY-2 PIC X(10).05 FILLER PIC X(80).The file described in an SD entry is the working file used <strong>for</strong> a sort or mergeoperation. You cannot per<strong>for</strong>m any input or output operations on this file and youdo not need to provide a ddname definition <strong>for</strong> it.RELATED REFERENCES“FILE SECTION entries” on page 14Describing the input to sorting or mergingDescribe the input file or files <strong>for</strong> sorting or merging by following the procedurebelow.1. Write one or more SELECT clauses in the FILE-CONTROL paragraph of theENVIRONMENT DIVISION to name the input files. For example:ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT Input-File ASSIGN TO InFile.Input-File is the name of the file in your program. Use this name to refer to thefile.2. Describe the input file (or files when merging) in an FD entry in the FILESECTION of the DATA DIVISION. For example:DATA DIVISION.FILE SECTION.FD Input-FileLABEL RECORDS ARE STANDARDBLOCK CONTAINS 0 CHARACTERSRECORDING MODE IS FRECORD CONTAINS 100 CHARACTERS.01 Input-Record PIC X(100).RELATED TASKS“Coding the input procedure” on page 216“Requesting the sort or merge” on page 220RELATED REFERENCES“FILE SECTION entries” on page 14Example: describing sort and input files <strong>for</strong> SORTThe following example shows the ENVIRONMENT DIVISION and DATA DIVISION entriesneeded to describe sort work files and an input file.ID Division.Program-ID. SmplSort.Environment Division.Input-Output Section.File-Control.Chapter 12. Sorting and merging files 215


** Assign name <strong>for</strong> a working file is treated as documentation.*Select Sort-Work-1 Assign To SortFile.Select Sort-Work-2 Assign To SortFile.Select Input-File...Data Division.File Section.SDAssign To InFile.Sort-Work-1Record Contains 100 Characters.01 Sort-Work-1-Area.05 Sort-Key-1 Pic X(10).05 Sort-Key-2 Pic X(10).05 Filler Pic X(80).SDSort-Work-2Record Contains 30 Characters.01 Sort-Work-2-Area.05 Sort-Key Pic X(5).05 Filler Pic X(25).FDInput-FileLabel Records Are StandardBlock Contains 0 CharactersRecording Mode is FRecord Contains 100 Characters.01 Input-Record Pic X(100)....Working-Storage Section.01 E<strong>OS</strong>-Sw Pic X.01 Filler.05 Table-Entry Occurs 100 Times...Indexed By X1Pic X(30).Coding the input procedureRELATED TASKS“Requesting the sort or merge” on page 220To process the records in an input file be<strong>for</strong>e they are released to the sort program,use the INPUT PROCEDURE phrase of the SORT statement.You can use an input procedure to:v Release data items to the sort file from WORKING-STORAGE or LOCAL-STORAGE.v Release records that have already been read elsewhere in the program.v Read records from an input file, select or process them, and release them to thesort file.Each input procedure must be contained in either paragraphs or sections. Forexample, to release records from a table in WORKING-STORAGE or LOCAL-STORAGE tothe sort file SORT-WORK-2, you could code as follows:SORT SORT-WORK-2ON ASCENDING KEY SORT-KEYINPUT PROCEDURE 600-SORT3-INPUT-PROC...600-SORT3-INPUT-PROC SECTION.PERFORM WITH TEST AFTERVARYING X1 FROM 1 BY 1 UNTIL X1 = 100RELEASE SORT-WORK-2-AREA FROM TABLE-ENTRY (X1)END-PERFORM.216 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


To transfer records to the sort program, all input procedures must contain at leastone RELEASE or RELEASE FROM statement. To release A from X, <strong>for</strong> example, you cancode:MOVEXTOA.RELEASE A.Alternatively, you can code:RELEASE A FROM X.The following table compares the RELEASE and RELEASE FROM statements.RELEASEMOVE EXT-RECORDTO SORT-EXT-RECORDPERFORM RELEASE-SORT-RECORD...RELEASE-SORT-RECORD.RELEASE SORT-RECORDRELEASE FROMPERFORM RELEASE-SORT-RECORD...RELEASE-SORT-RECORD.RELEASE SORT-RECORDFROM SORT-EXT-RECORDRELATED REFERENCES“Restrictions on input and output procedures” on page 219RELEASE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Describing the output from sorting or mergingIf the output from sorting or merging is a file, describe the file by following theprocedure below.1. Write a SELECT clause in the FILE-CONTROL paragraph of the ENVIRONMENTDIVISION to name the output file. For example:ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT Output-File ASSIGN TO OutFile.Output-File is the name of the file in your program. Use this name to refer tothe file.2. Describe the output file (or files when merging) in an FD entry in the FILESECTION of the DATA DIVISION. For example:DATA DIVISION.FILE SECTION.FD Output-FileLABEL RECORDS ARE STANDARDBLOCK CONTAINS 0 CHARACTERSRECORDING MODE IS FRECORD CONTAINS 100 CHARACTERS.01 Output-Record PIC X(100).RELATED TASKS“Coding the output procedure” on page 218“Requesting the sort or merge” on page 220RELATED REFERENCES“FILE SECTION entries” on page 14Chapter 12. Sorting and merging files 217


Coding the output procedureTo select, edit, or otherwise change sorted records be<strong>for</strong>e writing them from thesort work file into another file, use the OUTPUT PROCEDURE phrase of the SORTstatement.Each output procedure must be contained in either a section or a paragraph. Anoutput procedure must include both of the following elements:v At least one RETURN statement or one RETURN statement with the INTO phrasevAny statements necessary to process the records that are made available, one ata time, by the RETURN statementThe RETURN statement makes each sorted record available to the output procedure.(The RETURN statement <strong>for</strong> a sort file is similar to a READ statement <strong>for</strong> an input file.)You can use the AT END and END-RETURN phrases with the RETURN statement. Theimperative statements in the AT END phrase are per<strong>for</strong>med after all the records havebeen returned from the sort file. The END-RETURN explicit scope terminator delimitsthe scope of the RETURN statement.If you use RETURN INTO instead of RETURN, the records will be returned toWORKING-STORAGE, LOCAL-STORAGE, or to an output area.DFSORT coding: When you use DFSORT and a RETURN statement does notencounter an AT END condition be<strong>for</strong>e a <strong>COBOL</strong> program finishes running, the SORTstatement could end abnormally with DFSORT message IEC025A. To avoid thissituation, be sure to code the RETURN statement with the AT END phrase. In addition,ensure that the RETURN statement is executed until the AT END condition isencountered. The AT END condition occurs after the last record is returned to theprogram from the sort work file and a subsequent RETURN statement is executed.“Example: coding the output procedure when using DFSORT”RELATED REFERENCES“Restrictions on input and output procedures” on page 219RETURN statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: coding the output procedure when using DFSORTThe following example shows a coding technique that ensures that the RETURNstatement encounters the AT END condition be<strong>for</strong>e the program finishes running.The RETURN statement, coded with the AT END phrase, is executed until the AT ENDcondition occurs.IDENTIFICATION DIVISION.DATA DIVISION.FILE SECTION.SD OUR-FILE.01 OUR-SORT-REC.03 SORT-KEY PIC X(10).03 FILLER PIC X(70)....WORKING-STORAGE SECTION.01 WS-SORT-REC PIC X(80).01 END-OF-SORT-FILE-INDICATOR PIC X VALUE 'N'.88 NO-MORE-SORT-RECORDS VALUE 'Y'....218 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


PROCEDURE DIVISION.A-CONTROL SECTION.SORT OUR-FILE ON ASCENDING KEY SORT-KEYINPUT PROCEDURE IS B-INPUTOUTPUT PROCEDURE IS C-OUTPUT....B-INPUT SECTION.MOVE.......TOWS-SORT-REC.RELEASE OUR-SORT-REC FROM WS-SORT-REC....C-OUTPUT SECTION.DISPLAY 'STARTING READS OF SORTED RECORDS: '.RETURN OUR-FILEAT ENDSET NO-MORE-SORT-RECORDS TO TRUE.PERFORM WITH TEST BEFORE UNTIL NO-MORE-SORT-RECORDSIF SORT-RETURN = 0 THENDISPLAY 'OUR-SORT-REC = ' OUR-SORT-RECRETURN OUR-FILEAT ENDSET NO-MORE-SORT-RECORDS TO TRUEEND-IFEND-PERFORM.Restrictions on input and output proceduresSeveral restrictions apply to each input or output procedure called by SORT and toeach output procedure called by MERGE.Observe these restrictions:v The procedure must not contain any SORT or MERGE statements.v You can use ALTER, GO TO, and PERFORM statements in the procedure to refer toprocedure-names outside the input or output procedure. However, control mustreturn to the input or output procedure after a GO TO or PERFORM statement.v The remainder of the PROCEDURE DIVISION must not contain any transfers ofcontrol to points inside the input or output procedure (with the exception of thereturn of control from a declarative section).v In an input or output procedure, you can call a program that follows standardlinkage conventions. However, the called program cannot issue a SORT or MERGEstatement.v During a SORT or MERGE operation, the SD data item is used. You must not use itin the output procedure be<strong>for</strong>e the first RETURN executes. If you move data intothis record area be<strong>for</strong>e the first RETURN statement, the first record to be returnedwill be overwritten.v Language Environment condition handling does not let user-written conditionhandlers be established in an input or output procedure.RELATED TASKS“Coding the input procedure” on page 216“Coding the output procedure” on page 218Language Environment <strong>Programming</strong> <strong>Guide</strong> (Preparing to link-edit and run)Defining sort and merge data setsTo use DFSORT under z/<strong>OS</strong>, code DD statements in the runtime JCL to describe thenecessary data sets that are listed below.Chapter 12. Sorting and merging files 219


Sort or merge workDefine a minimum of three data sets: SORTWK01, SORTWK02, SORTWK03, ...,SORTWKnn (where nn is 99 or less). These data sets cannot be in the HFS.SYSOUT Define <strong>for</strong> sort diagnostic messages, unless you change the data-set name.(Change the name using either the MSGDDN keyword of the OPTION controlstatement in the SORT-CONTROL data set, or using the SORT-MESSAGE specialregister.)SORTCKPTDefine if the sort or merge is to take checkpoints.Input and outputDefine input and output data sets, if any.SORTLIB (DFSORT library)Define the library that contains the sort modules, <strong>for</strong> example,SYS1.SORTLIB.RELATED TASKS“Controlling sort behavior” on page 228“Using checkpoint/restart with DFSORT” on page 231Sorting variable-length recordsYour sort work file will be variable length only if you define it to be variablelength, even if the input file to the sort contains variable-length records.The compiler determines that the sort work file is variable length if you code oneof the following elements in the SD entry:v A RECORD IS VARYING clausevTwo or more record descriptions that define records that have different sizes, orrecords that contain an OCCURS DEPENDING ON clauseYou cannot use RECORDING MODE V <strong>for</strong> the sort work file because the SD entry doesnot allow the RECORDING MODE clause.Per<strong>for</strong>mance consideration: To improve sort per<strong>for</strong>mance of variable-length files,specify the most frequently occurring record length of the input file (the modallength) on the SMS= control card or in the SORT-MODE-SIZE special register.Requesting the sort or mergeRELATED TASKS“Changing DFSORT defaults with control statements” on page 229“Controlling sort behavior” on page 228To read records from an input file (files <strong>for</strong> MERGE) without preliminary processing,use SORT . . . USING or MERGE . . . USING and the name of the input file (files)that you declared in a SELECT clause.To transfer sorted or merged records from the sort or merge program to anotherfile without any further processing, use SORT . . . GIVING or MERGE ...GIVINGand the name of the output file that you declared in a SELECT clause. For example:220 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


SORT Sort-Work-1ON ASCENDING KEY Sort-Key-1USING Input-FileGIVING Output-File.For SORT . . . USING or MERGE . . . USING, the compiler generates an inputprocedure to open the file (files), read the records, release the records to the sort ormerge program, and close the file (files). The file (files) must not be open when theSORT or MERGE statement begins execution. For SORT . . . GIVING or MERGE . . .GIVING, the compiler generates an output procedure to open the file, return therecords, write the records, and close the file. The file must not be open when theSORT or MERGE statement begins execution.The USING or GIVING files in a SORT or MERGE statement can be sequential filesresiding in the HFS.“Example: describing sort and input files <strong>for</strong> SORT” on page 215If you want an input procedure to be per<strong>for</strong>med on the sort records be<strong>for</strong>e they aresorted, use SORT . . . INPUT PROCEDURE. If you want an output procedure to beper<strong>for</strong>med on the sorted records, use SORT . . . OUTPUT PROCEDURE. For example:SORT Sort-Work-1ON ASCENDING KEY Sort-Key-1INPUT PROCEDURE EditInputRecordsOUTPUT PROCEDURE FormatData.“Example: sorting with input and output procedures” on page 222Restriction: You cannot use an input procedure with the MERGE statement. Thesource of input to the merge operation must be a collection of already sorted files.However, if you want an output procedure to be per<strong>for</strong>med on the mergedrecords, use MERGE . . . OUTPUT PROCEDURE. For example:MERGE Merge-WorkON ASCENDING KEY Merge-KeyUSING Input-File-1 Input-File-2 Input-File-3OUTPUT PROCEDURE ProcessOutput.In the FILE SECTION, you must define Merge-Work in an SD entry, and the input filesin FD entries.RELATED TASKS“Defining sort and merge data sets” on page 219RELATED REFERENCESSORT statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MERGE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Setting sort or merge criteriaTo set sort or merge criteria, define the keys on which the operation is to beper<strong>for</strong>med.Do these steps:1. In the record description of the files to be sorted or merged, define the key orkeys.Chapter 12. Sorting and merging files 221


There is no maximum number of keys, but the keys must be located in the first4092 bytes of the record description. The total length of the keys cannot exceed4092 bytes unless the EQUALS keyword is coded in the DFSORT OPTION controlstatement, in which case the total length of the keys must not exceed 4088bytes.Restriction: A key cannot be variably located.2. In the SORT or MERGE statement, specify the key fields to be used <strong>for</strong> sequencingby coding the ASCENDING or DESCENDING KEY phrase, or both. When you codemore than one key, some can be ascending, and some descending.Specify the names of the keys in decreasing order of significance. The leftmostkey is the primary key. The next key is the secondary key, and so on.SORT and MERGE keys can be of class alphabetic, alphanumeric, national, or numeric(but not numeric of USAGE NATIONAL). If it has USAGE NATIONAL, a key can be ofcategory national or can be a national-edited or numeric-edited data item. A keycannot be a national decimal data item or a national floating-point data item.The collation order <strong>for</strong> national keys is determined by the binary order of the keys.If you specify a national data item as a key, any COLLATING SEQUENCE phrase in theSORT or MERGE statement does not apply to that key.You can mix SORT and MERGE statements in the same <strong>COBOL</strong> program. A programcan per<strong>for</strong>m any number of sort or merge operations. However, one operationmust end be<strong>for</strong>e another can begin.RELATED REFERENCESDFSORT Application <strong>Programming</strong> <strong>Guide</strong> (SORT control statement)SORT statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MERGE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: sorting with input and output proceduresThe following example shows the use of an input and an output procedure in aSORT statement. The example also shows how you can define a primary key(SORT-GRID-LOCATION) and a secondary key (SORT-SHIFT) be<strong>for</strong>e using them in theSORT statement.DATA DIVISION....SDSORT-FILERECORD CONTAINS 115 CHARACTERSDATA RECORD SORT-RECORD.01 SORT-RECORD.05 SORT-KEY.10 SORT-SHIFT PIC X(1).10 SORT-GRID-LOCATION PIC X(2).10 SORT-REPORT PIC X(3).05 SORT-EXT-RECORD.10 SORT-EXT-EMPLOYEE-NUM PIC X(6).10 SORT-EXT-NAME PIC X(30).10 FILLER PIC X(73)....WORKING-STORAGE SECTION.01 TAB1.05 TAB-ENTRY OCCURS 10 TIMESINDEXED BY TAB-INDX.10 WS-SHIFT PIC X(1).10 WS-GRID-LOCATION PIC X(2).10 WS-REPORT PIC X(3).222 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


10 WS-EXT-EMPLOYEE-NUM PIC X(6).10 WS-EXT-NAME PIC X(30).10 FILLER PIC X(73)....PROCEDURE DIVISION....SORT SORT-FILEON ASCENDING KEY SORT-GRID-LOCATION SORT-SHIFTINPUT PROCEDURE 600-SORT3-INPUTOUTPUT PROCEDURE 700-SORT3-OUTPUT....600-SORT3-INPUT.PERFORM VARYING TAB-INDX FROM 1 BY 1 UNTIL TAB-INDX > 10RELEASE SORT-RECORD FROM TAB-ENTRY(TAB-INDX)END-PERFORM....700-SORT3-OUTPUT.PERFORM VARYING TAB-INDX FROM 1 BY 1 UNTIL TAB-INDX > 10RETURN SORT-FILE INTO TAB-ENTRY(TAB-INDX)AT END DISPLAY 'Out Of Records In SORT File'END-RETURNEND-PERFORM.RELATED TASKS“Requesting the sort or merge” on page 220Choosing alternate collating sequencesYou can sort or merge records on the EBCDIC or ASCII collating sequence, or onanother collating sequence. The default collating sequence is EBCDIC unless youcode the PROGRAM COLLATING SEQUENCE clause in the OBJECT-COMPUTER paragraph.To override the default sequence, use the COLLATING SEQUENCE phrase of the SORT orMERGE statement. You can use different collating sequences <strong>for</strong> each SORT or MERGEstatement in your program.The PROGRAM COLLATING SEQUENCE clause and the COLLATING SEQUENCE phrase applyonly to keys of class alphabetic or alphanumeric.When you sort or merge an ASCII file, you have to request the ASCII collatingsequence. To do so, code the COLLATING SEQUENCE phrase of the SORT or MERGEstatement, and define the alphabet-name as STANDARD-1 in the SPECIAL-NAMESparagraph.RELATED TASKS“Specifying the collating sequence” on page 9“Setting sort or merge criteria” on page 221RELATED REFERENCESOBJECT-COMPUTER paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SORT statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Classes and categories of data (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Sorting on windowed date fieldsYou can specify windowed date fields as sort keys if your version of DFSORTsupports the Y2PAST option. If so, DFSORT can sort or merge on the windoweddate sequence.Chapter 12. Sorting and merging files 223


To sort on a windowed date field, use the DATE FORMAT clause to define awindowed date field; then use the field as the sort key. DFSORT will use the samecentury window as that used by the compilation unit. Specify the century windowwith the YEARWINDOW compiler option.DFSORT supports year-last windowed date fields, although the compiler itselfdoes not provide automatic windowing <strong>for</strong> year-last windowed date fields instatements other than MERGE or SORT.RELATED CONCEPTS“Millennium language extensions (MLE)” on page 636RELATED TASKS“Sorting and merging by date” on page 650RELATED REFERENCES“YEARWINDOW” on page 360DATE FORMAT clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)DFSORT Application <strong>Programming</strong> <strong>Guide</strong> (OPTION control statement: Y2PAST)Preserving the original sequence of records with equal keysYou can preserve the order of identical collating records from input to output.Use one of these techniques:v Install DFSORT with the EQUALS option as the default.v Provide, at run time, an OPTION card that has the EQUALS keyword in theIGZSRTCD data set.v Use the WITH DUPLICATES IN ORDER phrase in the SORT statement. Doing so addsthe EQUALS keyword to the OPTION card in the IGZSRTCD data set.Do not use both the NOEQUALS keyword on the OPTION card and the DUPLICATESphrase, or the run unit will end.RELATED REFERENCESDFSORT Application <strong>Programming</strong> <strong>Guide</strong> (OPTION control statement)Determining whether the sort or merge was successfulThe DFSORT program returns a completion code of either 0 (successfulcompletion) or 16 (unsuccessful completion) after each sort or merge has finished.The completion code is stored in the SORT-RETURN special register.You should test <strong>for</strong> successful completion after each SORT or MERGE statement. Forexample:SORT SORT-WORK-2ON ASCENDING KEY SORT-KEYINPUT PROCEDURE IS 600-SORT3-INPUT-PROCOUTPUT PROCEDURE IS 700-SORT3-OUTPUT-PROC.IF SORT-RETURN NOT=0DISPLAY "SORT ENDED ABNORMALLY. SORT-RETURN = " SORT-RETURN....600-SORT3-INPUT-PROC SECTION....700-SORT3-OUTPUT-PROC SECTION....224 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If you do not reference SORT-RETURN anywhere in your program, the <strong>COBOL</strong> runtime tests the completion code. If it is 16, <strong>COBOL</strong> issues a runtime diagnosticmessage.By default, DFSORT diagnostic messages are sent to the SYSOUT data set. If youwant to change this default, use the MSGDDN parameter of the DFSORT OPTIONcontrol card or use the SORT-MESSAGE special register.If you test SORT-RETURN <strong>for</strong> one or more (but not necessarily all) SORT or MERGEstatements, the <strong>COBOL</strong> run time does not check the completion code.RELATED TASKS“Checking <strong>for</strong> sort errors with NOFASTSRT” on page 227“Controlling sort behavior” on page 228RELATED REFERENCESDFSORT Application <strong>Programming</strong> <strong>Guide</strong> (DFSORT messages and return codes)Stopping a sort or merge operation prematurelyTo stop a sort or merge operation, move the integer 16 into the SORT-RETURN specialregister.Move 16 into the register in either of the following ways:v Use MOVE in an input or output procedure.Sort or merge processing will be stopped immediately after the next RELEASE orRETURN statement is per<strong>for</strong>med.v Reset the register in a declarative section entered during processing of a USING orGIVING file.Sort or merge processing will be stopped immediately after the next implicitRELEASE or RETURN is per<strong>for</strong>med, which will occur after a record has been readfrom or written to the USING or GIVING file.Control then returns to the statement following the SORT or MERGE statement.Improving sort per<strong>for</strong>mance with FASTSRTUsing the FASTSRT compiler option improves the per<strong>for</strong>mance of most sortoperations. With FASTSRT, the DFSORT product (instead of <strong>Enterprise</strong> <strong>COBOL</strong>)per<strong>for</strong>ms the I/O on the input and output files you name in the SORT...USINGand SORT...GIVING statements.The compiler issues in<strong>for</strong>mational messages to point out statements in whichFASTSRT can improve per<strong>for</strong>mance.Usage notesv You cannot use the DFSORT options SORTIN or SORTOUT if you use FASTSRT. TheFASTSRT compiler option does not apply to line-sequential files you use as USINGor GIVING files.v If you specify file status and use FASTSRT, file status is ignored during the sort.RELATED REFERENCES“FASTSRT” on page 322Chapter 12. Sorting and merging files 225


“FASTSRT requirements <strong>for</strong> JCL”“FASTSRT requirements <strong>for</strong> sort input and output files”FASTSRT requirements <strong>for</strong> JCLIn the runtime JCL, you must assign the sort work files (SORTWKnn) toadirect-access device, not to tape data sets.For the input and output files, the DCB parameter of the DD statement must matchthe FD description.FASTSRT requirements <strong>for</strong> sort input and output filesIf you specify FASTSRT but your code does not meet FASTSRT requirements, thecompiler issues a message and the <strong>COBOL</strong> run time per<strong>for</strong>ms the I/O instead.Your program will not experience the per<strong>for</strong>mance improvements that areotherwise possible.To use FASTSRT, you must describe and process the input files to the sort and theoutput files from the sort in these ways:v You can name only one input file in the USING phrase. You can name only oneoutput file in the GIVING phrase.v You cannot use an input procedure on an input file nor an output procedure onan output file.Instead of using input or output procedures, you might be able to use theseDFSORT control statements:– INREC– OUTFILE– OUTREC– INCLUDE– OMIT– STOPAFT– SKIPREC– SUMMany DFSORT functions per<strong>for</strong>m the same operations that are common in inputor output procedures. Code the appropriate DFSORT control statements instead,and place them either in the IGZSRTCD or SORTCNTL data set.v Do not code the LINAGE clause <strong>for</strong> the output FD entry.v Do not code any INPUT declarative (<strong>for</strong> input files), OUTPUT declarative (<strong>for</strong>output files), or file-specific declaratives (<strong>for</strong> either input or output files) toapply to any FDs used in the sort.v Do not use a variable relative file as the input or output file.v Do not use a line-sequential file as the input or output file.v For either an input or an output file, the record descriptions of the SD and FDentry must define the same <strong>for</strong>mat (fixed or variable), and the largest records ofthe SD and FD entry must define the same record length.If you code a RELATIVE KEY clause <strong>for</strong> an output file, it will not be set by the sort.Per<strong>for</strong>mance tip: If you block your input and output records, the sort per<strong>for</strong>mancecould be significantly improved.226 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


QSAM requirementsv QSAM files must have a record <strong>for</strong>mat of fixed, variable, or spanned.v A QSAM input file can be empty.vTo use the same QSAM file <strong>for</strong> both input and output, you must describe the fileusing two different DD statements. For example, in the FILE-CONTROL SECTIONyou might code this:SELECT FILE-IN ASSIGN INPUTF.SELECT FILE-OUT ASSIGN OUTPUTF.In the DATA DIVISION, you would have an FD entry <strong>for</strong> both FILE-IN andFILE-OUT, where FILE-IN and FILE-OUT are identical except <strong>for</strong> their names.In the PROCEDURE DIVISION, your SORT statement could look like this:SORT file-nameASCENDING KEY data-name-1USING FILE-IN GIVING FILE-OUTThen in your JCL, assuming that data set INOUT has been cataloged, you wouldcode://INPUTF DD DSN=INOUT,DISP=SHR//OUTPUTF DD DSN=INOUT,DISP=SHROn the other hand, if you code the same file-name in the USING and GIVINGphrases, or assign the input and output files the same ddname, then the file canbe accepted <strong>for</strong> FASTSRT either <strong>for</strong> input or output, but not both. If no otherconditions disqualify the file from being eligible <strong>for</strong> FASTSRT on input, then thefile will be accepted <strong>for</strong> FASTSRT on input, but not on output. If the file wasfound to be ineligible <strong>for</strong> FASTSRT on input, it might be eligible <strong>for</strong> FASTSRT onoutput.A QSAM file that qualifies <strong>for</strong> FASTSRT can be accessed by the <strong>COBOL</strong> programwhile the SORT statement is being per<strong>for</strong>med. For example, if the file is used <strong>for</strong>FASTSRT on input, you can access it in an output procedure; if it is used <strong>for</strong> FASTSRTon output, you can access it in an input procedure.VSAM requirementsv A VSAM input file must not be empty.v VSAM files cannot be password-protected.v You cannot name the same VSAM file in both the USING and GIVING phrases.vA VSAM file that qualifies <strong>for</strong> FASTSRT cannot be accessed by the <strong>COBOL</strong>program until the SORT statement processing is completed. For example, if thefile qualifies <strong>for</strong> FASTSRT on input, you cannot access it in an output procedureand vice versa. (If you do so, OPEN fails.)RELATED TASKSDFSORT Application <strong>Programming</strong> <strong>Guide</strong>Checking <strong>for</strong> sort errors with NOFASTSRTWhen you compile with the NOFASTSRT option, the sort process does not check <strong>for</strong>errors in open, close, or input or output operations <strong>for</strong> files that you reference inthe USING or GIVING phrase of the SORT statement. There<strong>for</strong>e, you might need tocheck whether SORT completed successfully.The code required depends on whether you code a FILE STATUS clause or an ERRORdeclarative <strong>for</strong> the files referenced in the USING and GIVING phrases, as shown inthe table below.Chapter 12. Sorting and merging files 227


Table 34. Methods <strong>for</strong> checking <strong>for</strong> sort errors with NOFASTSRTFILE STATUSclause?ERRORdeclarative?Then do:No No No special coding. Any failure during the sort processcauses the program to end abnormally.Yes No Test the SORT-RETURN special register after the SORTstatement, and test the file status key. (Not recommendedif you want complete file-status checking, because the filestatus code is set but <strong>COBOL</strong> cannot check it.)Maybe Yes In the ERROR declarative, set the SORT-RETURN specialregister to 16 to stop the sort process and indicate that itwas not successful. Test the SORT-RETURN special registerafter the SORT statement.Controlling sort behaviorRELATED TASKS“Determining whether the sort or merge was successful” on page 224“Using file status keys” on page 239“Coding ERROR declaratives” on page 238“Stopping a sort or merge operation prematurely” on page 225You can control several aspects of sort behavior by inserting values in specialregisters be<strong>for</strong>e the sort or by using compiler options. You might also have a choiceof control statements and keywords.You can verify sort behavior by examining the contents of special registers after thesort.The table below lists those aspects of sort behavior that you can affect by usingspecial registers or compiler options, and the equivalent sort control statementkeywords if any are available.Table 35. Methods <strong>for</strong> controlling sort behaviorTo set or testAmount of main storage to bereservedAmount of main storage to beusedModal length of records in afile with variable-lengthrecordsUse this special register orcompiler optionOr this control statement(and keyword ifapplicable)SORT-CORE-SIZE special register OPTION (keyword RESINV)SORT-CORE-SIZE special register OPTION (keywordsMAINSIZE or MAINSIZE=MAX)SORT-MODE-SIZE special register SMS=nnnnnName of sort control statement SORT-CONTROL special register Nonedata set (default IGZSRTCD)Name of sort message file SORT-MESSAGE special register OPTION (keyword MSGDDN)(default SYSOUT)Number of sort records SORT-FILE-SIZE special register OPTION (keyword FILSZ)Sort completion code SORT-RETURN special register None228 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 35. Methods <strong>for</strong> controlling sort behavior (continued)To set or testCentury window <strong>for</strong> sorting ormerging on date fieldsFormat of windowed datefields used as sort or mergekeysUse this special register orcompiler optionYEARWINDOW compiler option(Derived from PICTURE, USAGE,and DATE FORMAT clauses)Or this control statement(and keyword ifapplicable)OPTION (keyword Y2PAST)SORT (keywordFORMAT=Y2x)Sort special registers: SORT-CONTROL is an eight-character <strong>COBOL</strong> special registerthat contains the ddname of the sort control statement file. If you do not want touse the default ddname IGZSRTCD, assign to SORT-CONTROL the ddname of thedata set that contains your sort control statements.The SORT-CORE-SIZE, SORT-FILE-SIZE, SORT-MESSAGE, and SORT-MODE-SIZE specialregisters are used in the SORT interface if you assign them nondefault values. Atrun time, however, any parameters in control statements in the sort controlstatement data set override corresponding settings in the special registers, and amessage to that effect is issued.You can use the SORT-RETURN special register to determine whether the sort ormerge was successful and to stop a sort or merge operation prematurely.A compiler warning message (W-level) is issued <strong>for</strong> each sort special register thatyou set in a program.RELATED TASKS“Determining whether the sort or merge was successful” on page 224“Stopping a sort or merge operation prematurely” on page 225“Changing DFSORT defaults with control statements”“Allocating space <strong>for</strong> sort files” on page 231DFSORT Application <strong>Programming</strong> <strong>Guide</strong> (Using DFSORT programcontrol statements)RELATED REFERENCES“Default characteristics of the IGZSRTCD data set” on page 230Changing DFSORT defaults with control statementsIf you want to change DFSORT system defaults to improve sort per<strong>for</strong>mance, passin<strong>for</strong>mation to DFSORT through control statements in the runtime data setIGZSRTCD.The control statements that you can include in IGZSRTCD (in the order listed) are:1. SMS=nnnnn, where nnnnn is the length in bytes of the most frequently occurringrecord size. (Use only if the SD file is variable length.)2. OPTION (except keywords SORTIN or SORTOUT).3. Other DFSORT control statements (except SORT, MERGE, RECORD, orEND).Chapter 12. Sorting and merging files 229


Code control statements between columns 2 and 71. You can continue a controlstatement record by ending the line with a comma and starting the next line with anew keyword. You cannot use labels or comments on a record, and a record itselfcannot be a DFSORT comment statement.RELATED TASKS“Controlling sort behavior” on page 228DFSORT Application <strong>Programming</strong> <strong>Guide</strong> (Using DFSORT programcontrol statements)RELATED REFERENCES“Default characteristics of the IGZSRTCD data set”Default characteristics of the IGZSRTCD data setThe IGZSRTCD data set is optional. Its defaults are LRECL=80, BLKSIZE=400, andddname IGZSRTCD.You can use a different ddname by coding it in the SORT-CONTROL special register. Ifyou defined a ddname <strong>for</strong> the SORT-CONTROL data set and you receive the messageIGZ0027W, an OPEN failure occurred that you should investigate.RELATED TASKS“Controlling sort behavior” on page 228Allocating storage <strong>for</strong> sort or merge operationsCertain parameters set during the installation of DFSORT determine the amount ofstorage that DFSORT uses. In general, the more storage DFSORT has available, thefaster the sort or merge operations in your program will be.DFSORT installation should not allocate all the free space in the region <strong>for</strong> its<strong>COBOL</strong> operation, however. When your program is running, storage must beavailable <strong>for</strong>:v <strong>COBOL</strong> programs that are dynamically called from an input or output procedurev Language Environment runtime library modulesvvData management modules that can be loaded into the region <strong>for</strong> use by aninput or output procedureAny storage obtained by these modulesFor a specific sort or merge operation, you can override the DFSORT storagevalues set at installation. To do so, code the MAINSIZE and RESINV keywords on theOPTION control statement in the sort control statement data set, or use theSORT-CORE-SIZE special register.Be careful not to override the storage allocation to the extent that all the free spacein the region is used <strong>for</strong> sort operations <strong>for</strong> your <strong>COBOL</strong> program.RELATED TASKS“Controlling sort behavior” on page 228DFSORT Installation and CustomizationRELATED REFERENCESDFSORT Application <strong>Programming</strong> <strong>Guide</strong> (OPTION control statement)230 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Allocating space <strong>for</strong> sort filesIf you use NOFASTSRT or an input procedure, DFSORT does not know the size ofthe file that you are sorting. This can lead to an out-of-space condition when yousort large files or to overallocation of resources when you sort small files.If this occurs, you can use the SORT-FILE-SIZE special register to help DFSORTdetermine the amount of resource (<strong>for</strong> example, workspace or hiperspace) needed<strong>for</strong> the sort. Set SORT-FILE-SIZE to a reasonable estimate of the number of inputrecords. This value is passed to DFSORT as its FILSZ=En value.RELATED TASKS“Controlling sort behavior” on page 228“Coding the input procedure” on page 216DFSORT Application <strong>Programming</strong> <strong>Guide</strong>Using checkpoint/restart with DFSORTYou cannot use checkpoints taken while DFSORT is running under z/<strong>OS</strong> to restart,unless the checkpoints are taken by DFSORT. Checkpoints taken by a <strong>COBOL</strong>program while SORT or MERGE statements execute are invalid; such restarts aredetected and canceled.To take a checkpoint during a sort or merge operation, do these steps:1. Add a DD statement <strong>for</strong> SORTCKPT in the JCL.2. Code the RERUN clause in the I-O-CONTROL paragraph:RERUN ON assignment-name3. Code the CKPT (or CHKPT) keyword on an OPTION control statement in the sortcontrol statement data set (default ddname IGZSRTCD).RELATED CONCEPTSChapter 32, “Interrupts and checkpoint/restart,” on page 625Sorting under CICSRELATED TASKS“Changing DFSORT defaults with control statements” on page 229“Setting checkpoints” on page 625There is no IBM sort product that is supported under CICS. However, you can usethe SORT statement with a sort program you write that runs under CICS to sortsmall amounts of data.You must have both an input and an output procedure <strong>for</strong> the SORT statement. Inthe input procedure, use the RELEASE statement to transfer records from the<strong>COBOL</strong> program to the sort program be<strong>for</strong>e the sort is per<strong>for</strong>med. In the outputprocedure, use the RETURN statement to transfer records from the sort program tothe <strong>COBOL</strong> program after the sort is per<strong>for</strong>med.RELATED TASKS“Coding the input procedure” on page 216“Coding the output procedure” on page 218“Coding <strong>COBOL</strong> programs to run under CICS” on page 407Chapter 12. Sorting and merging files 231


RELATED REFERENCES“CICS SORT application restrictions”“CICS reserved-word table” on page 415CICS SORT application restrictionsSeveral restrictions apply to <strong>COBOL</strong> applications that run under CICS and use theSORT statement.The restrictions are:v SORT statements that include the USING or GIVING phrase are not supported.v Sort control data sets are not supported. Data in the SORT-CONTROL specialregister is ignored.v These CICS commands in the input or output procedures can causeunpredictable results:– CICS LINK– CICS XCTL– CICS RETURN– CICS HANDLE– CICS IGNORE– CICS PUSH– CICS POPYou can use CICS commands other than these if you use the NOHANDLE or RESPoption. Unpredictable results can occur if you do not use NOHANDLE or RESP.RELATED REFERENCES“CICS reserved-word table” on page 415232 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 13. Handling errorsPut code in your programs that anticipates possible system or runtime problems. Ifyou do not include such code, output data or files could be corrupted, and theuser might not even be aware that there is a problem.The error-handling code can take actions such as handling the situation, issuing amessage, or halting the program. You might <strong>for</strong> example create error-detectionroutines <strong>for</strong> data-entry errors or <strong>for</strong> errors as your installation defines them. In anyevent, coding a warning message is a good idea.<strong>Enterprise</strong> <strong>COBOL</strong> contains special elements to help you anticipate and correcterror conditions:v User-requested dumpsv ON OVERFLOW in STRING and UNSTRING operationsv ON SIZE ERROR in arithmetic operationsv Elements <strong>for</strong> handling input or output errorsv ON EXCEPTION or ON OVERFLOW in CALL statementsv User-written routines <strong>for</strong> handling errorsRequesting dumpsRELATED TASKS“Handling errors in joining and splitting strings” on page 234“Handling errors in arithmetic operations” on page 234“Handling errors in input and output operations” on page 235“Handling errors when calling programs” on page 244“Writing routines <strong>for</strong> handling errors” on page 244You can cause a <strong>for</strong>matted dump of the Language Environment runtimeenvironment and the member language libraries at any prespecified point in yourprogram by coding a call to the Language Environment callable service CEE3DMP.77 Title-1 Pic x(80) Display.77 Options Pic x(255) Display.01 Feedback-code Pic x(12) Display....Call "CEE3DMP" Using Title-1, Options, Feedback-codeTo have symbolic variables included in the <strong>for</strong>matted dump, compile with the TESTcompiler option and use the VARIABLES subparameter of CEE3DMP. You can alsorequest, through runtime options, that a dump be produced <strong>for</strong> error conditions ofyour choosing.You can cause a system dump at any prespecified point in your program. Requestan abend without cleanup by calling the Language Environment service CEE3ABDwith a cleanup value of zero. This callable service stops the run unit immediately,and a system dump is requested when the abend is issued.RELATED REFERENCES“TEST” on page 349© Copyright IBM Corp. 1991, 2009 233


Language Environment Debugging <strong>Guide</strong>Language Environment <strong>Programming</strong> Reference (CEE3DMP--generate dump)Handling errors in joining and splitting stringsDuring the joining or splitting of strings, the pointer used by STRING or UNSTRINGmight fall outside the range of the receiving field. A potential overflow conditionexists, but <strong>COBOL</strong> does not let the overflow happen.Instead, the STRING or UNSTRING operation is not completed, the receiving fieldremains unchanged, and control passes to the next sequential statement. If you donot code the ON OVERFLOW phrase of the STRING or UNSTRING statement, you are notnotified of the incomplete operation.Consider the following statement:String Item-1 space Item-2 delimited by Item-3into Item-4with pointer String-ptron overflowDisplay "A string overflow occurred"End-StringThese are the data values be<strong>for</strong>e and after the statement is per<strong>for</strong>med:Data item PICTURE Value be<strong>for</strong>e Value afterItem-1 X(5) AAAAA AAAAAItem-2 X(5) EEEAA EEEAAItem-3 X(2) EA EAItem-4 X(8) bbbbbbbb 1 bbbbbbbb 1String-ptr 9(2) 0 01. The symbol b represents a blank space.Because String-ptr has a value (0) that falls short of the receiving field, anoverflow condition occurs and the STRING operation is not completed. (Overflowwould also occur if String-ptr were greater than 9.) If ON OVERFLOW had not beenspecified, you would not be notified that the contents of Item-4 remainedunchanged.Handling errors in arithmetic operationsThe results of arithmetic operations might be larger than the fixed-point field thatis to hold them, or you might have tried dividing by zero. In either case, the ONSIZE ERROR clause after the ADD, SUBTRACT, MULTIPLY, DIVIDE, orCOMPUTE statementcan handle the situation.For ON SIZE ERROR to work correctly <strong>for</strong> fixed-point overflow and decimaloverflow, you must specify the TRAP(ON) runtime option.The imperative statement of the ON SIZE ERROR clause will be per<strong>for</strong>med and theresult field will not change in these cases:v Fixed-point overflowv Division by zero234 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvvZero raised to the zero powerZero raised to a negative numberNegative number raised to a fractional powerFloating-point exponent overflow occurs when the value of a floating-pointcomputation cannot be represented in the zSeries floating-point operand <strong>for</strong>mat.This type of overflow does not cause SIZE ERROR; an abend occurs instead. Youcould code a user-written condition handler to intercept the abend and provideyour own error recovery logic.Example: checking <strong>for</strong> division by zeroThe following example shows how you can code an ON SIZE ERROR imperativestatement so that the program issues an in<strong>for</strong>mative message if division by zerooccurs.DIVIDE-TOTAL-C<strong>OS</strong>T.DIVIDE TOTAL-C<strong>OS</strong>T BY NUMBER-PURCHASEDGIVING ANSWERON SIZE ERRORDISPLAY "ERROR IN DIVIDE-TOTAL-C<strong>OS</strong>T PARAGRAPH"DISPLAY "SPENT " TOTAL-C<strong>OS</strong>T, " FOR " NUMBER-PURCHASEDPERFORM FINISHEND-DIVIDE...FINISH.STOP RUN.If division by zero occurs, the program writes a message and halts programexecution.Handling errors in input and output operationsWhen an input or output operation fails, <strong>COBOL</strong> does not automatically takecorrective action. You choose whether your program will continue running after aless-than-severe input or output error.You can use any of the following techniques <strong>for</strong> intercepting and handling certaininput or output conditions or errors:v End-of-file condition (AT END)v ERROR declarativesv FILE STATUS clause and file status keyv File system status codev Imperative-statement phrases on READ or WRITE statementsFor VSAM files, if you specify a FILE STATUS clause, you can also test the VSAMstatus code to direct your program to error-handling logic.v INVALID KEY phraseTo have your program continue, you must code the appropriate error-recoveryprocedure. You might code, <strong>for</strong> example, a procedure to check the value of the filestatus key. If you do not handle an input or output error in any of these ways, aseverity-3 Language Environment condition is signaled, which causes the run unitto end if the condition is not handled.The following figure shows the flow of logic after a VSAM input or output error:Chapter 13. Handling errors 235


The following figure shows the flow of logic after an input or output error withQSAM or line-sequential files. The error can be from a READ statement, a WRITEstatement, or a CL<strong>OS</strong>E statement with a REEL/UNIT clause (QSAM only).236 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Set status key(if present)Applicable*imperativephrase?YesExecuteimperativestatementNoAssociatedERRORdeclarative?YesExecuteERRORdeclarativeNoFile-statusclausespecified ?YesTest file**status keyNoTerminate the rununit with a messageReturn to <strong>COBOL</strong>***at the end of I/Ostatement*Possible phrases <strong>for</strong> QSAM are AT END, AT END-OF-PAGE, and INVALID KEY; <strong>for</strong> linesequential, AT END.**You need to write the code to test the file status key.***Execution of your <strong>COBOL</strong> program continues after the input or outputstatement that caused the error.RELATED TASKS“Using the end-of-file condition (AT END)” on page 238“Coding ERROR declaratives” on page 238“Using file status keys” on page 239“Handling errors in QSAM files” on page 165“Using VSAM status codes (VSAM files only)” on page 241“Handling errors in line-sequential files” on page 212“Coding INVALID KEY phrases” on page 243RELATED REFERENCESFile status key (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 13. Handling errors 237


Using the end-of-file condition (AT END)You code the AT END phrase of the READ statement to handle errors or normalconditions, according to your program design. At end-of-file, the AT END phrase isper<strong>for</strong>med. If you do not code an AT END phrase, the associated ERROR declarative isper<strong>for</strong>med.In many designs, reading sequentially to the end of a file is done intentionally, andthe AT END condition is expected. For example, suppose you are processing a filethat contains transactions in order to update a master file:PERFORM UNTIL TRANSACTION-EOF = "TRUE"READ UPDATE-TRANSACTION-FILE INTO WS-TRANSACTION-RECORDAT ENDDISPLAY "END OF TRANSACTION UPDATE FILE REACHED"MOVE "TRUE" TO TRANSACTION-EOFEND READ...END-PERFORMAny NOT AT END phrase is per<strong>for</strong>med only if the READ statement completessuccessfully. If the READ operation fails because of a condition other thanend-of-file, neither the AT END nor the NOT AT END phrase is per<strong>for</strong>med. Instead,control passes to the end of the READ statement after any associated declarativeprocedure is per<strong>for</strong>med.You might choose not to code either an AT END phrase or an EXCEPTION declarativeprocedure, but to code a status key clause <strong>for</strong> the file. In that case, control passesto the next sequential instruction after the input or output statement that detectedthe end-of-file condition. At that place, you should have some code that takesappropriate action.RELATED REFERENCESAT END phrases (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Coding ERROR declarativesYou can code one or more ERROR declarative procedures that will be given controlif an input or output error occurs during the execution of your program. If you donot code such procedures, your job could be canceled or abnormally terminatedafter an input or output error occurs.Place each such procedure in the declaratives section of the PROCEDURE DIVISION.You can code:v A single, common procedure <strong>for</strong> the entire programv Procedures <strong>for</strong> each file open mode (whether INPUT, OUTPUT, I-O, orEXTEND)v Individual procedures <strong>for</strong> each fileIn an ERROR declarative procedure, you can code corrective action, retry theoperation, continue, or end execution. (If you continue processing a blocked file,though, you might lose the remaining records in a block after the record thatcaused the error.) You can use the ERROR declaratives procedure in combinationwith the file status key if you want a further analysis of the error.Multithreading: Avoid deadlocks when coding I/O declaratives in multithreadedapplications. When an I/O operation results in a transfer of control to an I/Odeclarative, the automatic serialization lock associated with the file is held during238 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


the execution of the statements within the declarative. If you code I/O operationswithin your declaratives, your logic might result in a deadlock as illustrated by thefollowing sample:Declaratives.D1 section.Use after standard error procedure on F1Read F2....D2 section.Use after standard error procedure on F2Read F1....End declaratives....Rewrite R1.Rewrite R2.When this program is running on two threads, the following sequence of eventscould occur:1. Thread 1: Rewrite R1 acquires lock on F1 and encounters I/O error.2. Thread 1: Enter declarative D1, holding lock on F1.3. Thread 2: Rewrite R2 acquires lock on F2 and encounters I/O error.4. Thread 2: Enter declarative D2.5. Thread 1: Read F2 from declarative D1; wait on F2 lock held by thread 2.6. Thread 2: Read F1 from declarative D2; wait on F1 lock held by thread 1.7. Deadlock.RELATED REFERENCESEXCEPTION/ERROR declarative (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using file status keysAfter each input or output statement is per<strong>for</strong>med on a file, the system updatesvalues in the two digit positions of the file status key. In general, a zero in the firstposition indicates a successful operation, and a zero in both positions means thatnothing abnormal occurred.Establish a file status key by coding:v The FILE STATUS clause in the FILE-CONTROL paragraph:vFILE STATUS IS data-name-1Data definitions in the DATA DIVISION (WORKING-STORAGE, LOCAL-STORAGE, orLINKAGE SECTION), <strong>for</strong> example:WORKING-STORAGE SECTION.01 data-name-1 PIC 9(2) USAGE NATIONAL.Specify the file status key data-name-1 as a two-character category alphanumeric orcategory national item, or as a two-digit zoned decimal or national decimal item.This data-name-1 cannot be variably located.Your program can check the file status key to discover whether an error occurred,and, if so, what type of error occurred. For example, suppose that a FILE STATUSclause is coded like this:FILE STATUS IS FS-CODEFS-CODE is used by <strong>COBOL</strong> to hold status in<strong>for</strong>mation like this:Chapter 13. Handling errors 239


Follow these rules <strong>for</strong> each file:v Define a different file status key <strong>for</strong> each file.Doing so means that you can determine the cause of a file input or outputexception, such as an application logic error or a disk error.v Check the file status key after each input or output request.If the file status key contains a value other than 0, your program can issue anerror message or can take action based on that value.You do not have to reset the file status key code, because it is set after eachinput or output attempt.For VSAM files, you can additionally code a second identifier in the FILE STATUSclause to get more detailed in<strong>for</strong>mation about VSAM input or output requests.You can use the file status key alone or in conjunction with the INVALID KEYoption, or to supplement the EXCEPTION or ERROR declarative. Using the file statuskey in this way gives you precise in<strong>for</strong>mation about the results of each input oroutput operation.“Example: file status key”RELATED TASKS“Using VSAM status codes (VSAM files only)” on page 241RELATED REFERENCESFILE STATUS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)File status key (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: file status keyThe following example shows how you can per<strong>for</strong>m a simple check of the filestatus key after opening a file.IDENTIFICATION DIVISION.PROGRAM-ID. SIMCHK.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT MASTERFILE ASSIGN TO AS-MASTERAFILE STATUS IS MASTER-CHECK-KEY...DATA DIVISION....WORKING-STORAGE SECTION.01 MASTER-CHECK-KEY PIC X(2)....PROCEDURE DIVISION.OPEN INPUT MASTERFILEIF MASTER-CHECK-KEY NOT = "00"DISPLAY "Nonzero file status returned from OPEN " MASTER-CHECK-KEY...240 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Using VSAM status codes (VSAM files only)Often the <strong>COBOL</strong> file status code is too general to pinpoint the disposition of arequest. You can get more detailed in<strong>for</strong>mation about VSAM input or outputrequests by coding a second data item in the FILE STATUS clause.FILE STATUS IS data-name-1 data-name-8The data item data-name-1 shown above specifies the <strong>COBOL</strong> file status key, whichyou define as a two-character alphanumeric or national data item, or as a two-digitzoned decimal or national decimal item.The data item data-name-8 specifies the VSAM status code, which you define as a6-byte alphanumeric group data item that has three subordinate 2-byte binaryfields. The VSAM status code contains meaningful values when the <strong>COBOL</strong> filestatus key is not 0.You can define data-name-8 in the WORKING-STORAGE SECTION, asinVSAM-CODE below.01 RETURN-STATUS.05 FS-CODE PIC X(2).05 VSAM-CODE.10 VSAM-R15-RETURN PIC S9(4) Usage Comp-5.10 VSAM-FUNCTION PIC S9(4) Usage Comp-5.10 VSAM-FEEDBACK PIC S9(4) Usage Comp-5.<strong>Enterprise</strong> <strong>COBOL</strong> uses data-name-8 to pass in<strong>for</strong>mation supplied by VSAM. In thefollowing example, FS-CODE corresponds to data-name-1 and VSAM-CODE correspondsto data-name-8:“Example: checking VSAM status codes”RELATED REFERENCESFILE STATUS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)File status key (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)z/<strong>OS</strong> DFSMS Macro Instructions <strong>for</strong> Data Sets (VSAM macro return andreason codes)Example: checking VSAM status codesThe following example reads an indexed file (starting at the fifth record), checksthe file status key after each input or output request, and displays the VSAMstatus codes when the file status key is not zero.Chapter 13. Handling errors 241


This example also illustrates how output from this program might look if the filebeing processed contained six records.IDENTIFICATION DIVISIONPROGRAM-ID. EXAMPLE.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT VSAMFILE ASSIGN TO VSAMFILEORGANIZATION IS INDEXEDACCESS DYNAMICRECORD KEY IS VSAMFILE-KEYFILE STATUS IS FS-CODE VSAM-CODE.DATA DIVISION.FILE SECTION.FD VSAMFILERECORD 30.01 VSAMFILE-REC.10 VSAMFILE-KEY PIC X(6).10 FILLER PIC X(24).WORKING-STORAGE SECTION.01 RETURN-STATUS.05 FS-CODE PIC XX.05 VSAM-CODE.10 VSAM-RETURN-CODE PIC S9(2) Usage Binary.10 VSAM-COMPONENT-CODE PIC S9(1) Usage Binary.10 VSAM-REASON-CODE PIC S9(3) Usage Binary.PROCEDURE DIVISION.OPEN INPUT VSAMFILE.DISPLAY "OPEN INPUT VSAMFILE FS-CODE: " FS-CODE.IF FS-CODE NOT = "00"PERFORM VSAM-CODE-DISPLAYSTOP RUNEND-IF.MOVE "000005" TO VSAMFILE-KEY.START VSAMFILE KEY IS EQUAL TO VSAMFILE-KEY.DISPLAY "START VSAMFILE KEY=" VSAMFILE-KEY" FS-CODE: " FS-CODE.IF FS-CODE NOT = "00"PERFORM VSAM-CODE-DISPLAYEND-IF.IF FS-CODE = "00"PERFORM READ-NEXT UNTIL FS-CODE NOT = "00"END-IF.CL<strong>OS</strong>E VSAMFILE.STOP RUN.READ-NEXT.READ VSAMFILE NEXT.DISPLAY "READ NEXT VSAMFILE FS-CODE: " FS-CODE.IF FS-CODE NOT = "00"PERFORM VSAM-CODE-DISPLAYEND-IF.DISPLAY VSAMFILE-REC.VSAM-CODE-DISPLAY.DISPLAY "VSAM-CODE ==>"" RETURN: " VSAM-RETURN-CODE," COMPONENT: " VSAM-COMPONENT-CODE," REASON: " VSAM-REASON-CODE.Below is a sample of the output from the example program that checks VSAMstatus-code in<strong>for</strong>mation:242 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


OPEN INPUT VSAMFILE FS-CODE: 00START VSAMFILE KEY=000005 FS-CODE: 00READ NEXT VSAMFILE FS-CODE: 00000005 THIS IS RECORD NUMBER 5READ NEXT VSAMFILE FS-CODE: 00000006 THIS IS RECORD NUMBER 6READ NEXT VSAMFILE FS-CODE: 10VSAM-CODE ==> RETURN: 08 COMPONENT: 2 REASON: 004Coding INVALID KEY phrasesYou can include an INVALID KEY phrase on READ, START, WRITE, REWRITE, and DELETEstatements <strong>for</strong> VSAM indexed and relative files. The INVALID KEY phrase is givencontrol if an input or output error occurs because of a faulty index key.You can also include the INVALID KEY phrase in WRITE requests <strong>for</strong> QSAM files, butthe phrase has limited meaning <strong>for</strong> QSAM files. It is used only if you try to writeto a disk that is full.Use the FILE STATUS clause with the INVALID KEY phrase to evaluate the status keyand determine the specific INVALID KEY condition.INVALID KEY phrases differ from ERROR declaratives in several ways. INVALID KEYphrases:v Operate <strong>for</strong> only limited types of errors. ERROR declaratives encompass all <strong>for</strong>ms.vvAre coded directly in the input or output verb. ERROR declaratives are codedseparately.Are specific <strong>for</strong> a single input or output operation. ERROR declaratives are moregeneral.If you code INVALID KEY in a statement that causes an INVALID KEY condition,control is transferred to the INVALID KEY imperative statement. Any ERRORdeclaratives that you coded are not per<strong>for</strong>med.If you code a NOT INVALID KEY phrase, it is per<strong>for</strong>med only if the statementcompletes successfully. If the operation fails because of a condition other thanINVALID KEY, neither the INVALID KEY nor the NOT INVALID KEY phrase isper<strong>for</strong>med. Instead, after the program per<strong>for</strong>ms any associated ERROR declaratives,control passes to the end of the statement.“Example: FILE STATUS and INVALID KEY”Example: FILE STATUS and INVALID KEYThe following example shows how you can use the file status code and theINVALID KEY phrase to determine more specifically why an input or outputstatement failed.Assume that you have a file that contains master customer records and you needto update some of these records with in<strong>for</strong>mation from a transaction update file.The program reads each transaction record, finds the corresponding record in themaster file, and makes the necessary updates. The records in both files contain afield <strong>for</strong> a customer number, and each record in the master file has a uniquecustomer number.Chapter 13. Handling errors 243


The FILE-CONTROL entry <strong>for</strong> the master file of customer records includes statementsthat define indexed organization, random access, MASTER-CUSTOMER-NUMBER as theprime record key, and CUSTOMER-FILE-STATUS as the file status key... (read the update transaction record).MOVE "TRUE" TO TRANSACTION-MATCHMOVE UPDATE-CUSTOMER-NUMBER TO MASTER-CUSTOMER-NUMBERREAD MASTER-CUSTOMER-FILE INTO WS-CUSTOMER-RECORDINVALID KEYDISPLAY "MASTER CUSTOMER RECORD NOT FOUND"DISPLAY "FILE STATUS CODE IS: " CUSTOMER-FILE-STATUSMOVE "FALSE" TO TRANSACTION-MATCHEND-READHandling errors when calling programsWhen a program dynamically calls a separately compiled program, the calledprogram might be unavailable. For example, the system might be out of storage orunable to locate the load module. If the CALL statement does not have an ONEXCEPTION or ON OVERFLOW phrase, your application might abend.Use the ON EXCEPTION phrase to per<strong>for</strong>m a series of statements and to per<strong>for</strong>m yourown error handling. For example, in the code fragment below, if program REPORTAis unavailable, control passes to the ON EXCEPTION phrase.MOVE "REPORTA" TO REPORT-PROGCALL REPORT-PROGON EXCEPTIONDISPLAY "Program REPORTA not available, using REPORTB."MOVE "REPORTB" TO REPORT-PROGCALL REPORT-PROGEND-CALLEND-CALL|||The ON EXCEPTION phrase applies only to the availability of the called program onits initial load. If the called program is loaded but fails <strong>for</strong> any other reason (suchas initialization), the ON EXCEPTION phrase is not per<strong>for</strong>med.RELATED TASKS<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong>Writing routines <strong>for</strong> handling errorsYou can handle most error conditions that might occur while your program isrunning by using the ON EXCEPTION phrase, ON SIZE ERROR phrase, or otherlanguage constructs. But if an extraordinary condition such as a machine checkoccurs, usually your application is abnormally terminated.<strong>Enterprise</strong> <strong>COBOL</strong> and Language Environment provide a way <strong>for</strong> a user-writtenprogram to gain control when such conditions occur. Using Language Environmentcondition handling, you can write your own error-handling routines in <strong>COBOL</strong>.They can report, analyze, or even fix up a program and enable it to resumerunning.To have Language Environment pass control to a user-written error program, youmust first identify and register its entry point to Language Environment.244 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


PROCEDURE-POINTER data items enable you to pass the entry address of procedureentry points to Language Environment services.RELATED TASKS“Using procedure and function pointers” on page 462Chapter 13. Handling errors 245


246 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 2. Compiling and debugging your programChapter 14. Compiling under z/<strong>OS</strong> . . . . . 249Compiling with JCL . . . . . . . . . . . 249Using a cataloged procedure . . . . . . . 250Compile procedure (IGYWC) . . . . . . 251Compile and link-edit procedure (IGYWCL) 252Compile, link-edit, and run procedure(IGYWCLG). . . . . . . . . . . . 253Compile, load, and run procedure (IGYWCG) 254Compile, prelink, and link-edit procedure(IGYWCPL) . . . . . . . . . . . . 255Compile, prelink, link-edit, and runprocedure (IGYWCPLG). . . . . . . . 256Prelink and link-edit procedure (IGYWPL) 258Compile, prelink, load, and run procedure(IGYWCPG). . . . . . . . . . . . 258Writing JCL to compile programs. . . . . . 259Example: user-written JCL <strong>for</strong> compiling . . 260Compiling under TSO . . . . . . . . . . 261Example: ALLOCATE and CALL <strong>for</strong> compilingunder TSO . . . . . . . . . . . . . 262Example: CLIST <strong>for</strong> compiling under TSO . . . 262Starting the compiler from an assembler program 263Defining compiler input and output . . . . . . 264Data sets used by the compiler under z/<strong>OS</strong> . . 265Logical record length and block size. . . . 266Defining the source code data set (SYSIN) . . . 267Defining a compiler-option data set (SYSOPTF) 267Specifying source libraries (SYSLIB) . . . . . 268Defining the output data set (SYSPRINT) . . . 269Directing compiler messages to your terminal(SYSTERM) . . . . . . . . . . . . . 269Creating object code (SYSLIN or SYSPUNCH) 269Defining an associated-data file (SYSADATA) 270Defining the Java-source output file (SYSJAVA) 270Defining the debug data set (SYSDEBUG) . . . 270Defining the library-processing output file(SYSMDECK) . . . . . . . . . . . . 271Specifying compiler options under z/<strong>OS</strong> . . . . 271Specifying compiler options with the PROCESS(CBL) statement . . . . . . . . . . . 272Example: specifying compiler options using JCL 273Example: specifying compiler options underTSO . . . . . . . . . . . . . . . 273Compiler options and compiler output underz/<strong>OS</strong> . . . . . . . . . . . . . . . 273Compiling multiple programs (batch compilation) 274Example: batch compilation . . . . . . . 275Specifying compiler options in a batchcompilation . . . . . . . . . . . . . 276Example: precedence of options in a batchcompilation . . . . . . . . . . . . . 277Example: LANGUAGE option in a batchcompilation . . . . . . . . . . . . . 278Correcting errors in your source program . . . . 279Generating a list of compiler messages . . . . 279||||Messages and listings <strong>for</strong> compiler-detectederrors . . . . . . . . . . . . . . . 280Format of compiler diagnostic messages . . . 280Severity codes <strong>for</strong> compiler diagnostic messages 281Chapter 15. Compiling under z/<strong>OS</strong> UNIX . . . 283Setting environment variables under z/<strong>OS</strong> UNIX 283Specifying compiler options under z/<strong>OS</strong> UNIX . . 284Compiling and linking with the cob2 command 285Creating a DLL under z/<strong>OS</strong> UNIX . . . . . 286Example: using cob2 to compile and link underz/<strong>OS</strong> UNIX . . . . . . . . . . . . . 287cob2 syntax and options . . . . . . . . . 287cob2 input and output files . . . . . . . . 289Compiling using scripts . . . . . . . . . . 290Chapter 16. Compiling, linking, and running OOapplications . . . . . . . . . . . . . 291Compiling, linking, and running OO applicationsunder z/<strong>OS</strong> UNIX. . . . . . . . . . . . 291Compiling OO applications under z/<strong>OS</strong> UNIX 291Preparing OO applications under z/<strong>OS</strong> UNIX 292Example: compiling and linking a <strong>COBOL</strong> classdefinition under z/<strong>OS</strong> UNIX . . . . . . . 293Running OO applications under z/<strong>OS</strong> UNIX 293Running OO applications that start with amain method . . . . . . . . . . . 294Running OO applications that start with a<strong>COBOL</strong> program . . . . . . . . . . 295Compiling, linking, and running OO applicationsin JCL or TSO/E . . . . . . . . . . . . 295Compiling OO applications in JCL or TSO/E 296Preparing and running OO applications in JCLor TSO/E. . . . . . . . . . . . . . 296Example: compiling, linking, and running anOO application using JCL . . . . . . . . 298JCL <strong>for</strong> program TSTHELLO . . . . . . 298Definition of class HelloJ . . . . . . . 299Environment variable settings file, ENV . . 299Using Java SDKs <strong>for</strong> z/<strong>OS</strong> . . . . . . . . . 299Object-oriented syntax, and Java 5 or Java 6SDKs . . . . . . . . . . . . . . . 300Chapter 17. Compiler options . . . . . . . 301Option settings <strong>for</strong> Standard <strong>COBOL</strong> 85con<strong>for</strong>mance. . . . . . . . . . . . . . 303Conflicting compiler options . . . . . . . . 304ADATA . . . . . . . . . . . . . . . 305ADV . . . . . . . . . . . . . . . . 305ARITH . . . . . . . . . . . . . . . 306AWO . . . . . . . . . . . . . . . . 307BLOCK0 . . . . . . . . . . . . . . . 307BUFSIZE . . . . . . . . . . . . . . . 309CICS . . . . . . . . . . . . . . . . 309CODEPAGE. . . . . . . . . . . . . . 310© Copyright IBM Corp. 1991, 2009 247


COMPILE . . . . . . . . . . . . . . 313CURRENCY. . . . . . . . . . . . . . 313DATA . . . . . . . . . . . . . . . . 314DATEPROC . . . . . . . . . . . . . . 315DBCS . . . . . . . . . . . . . . . . 317DECK . . . . . . . . . . . . . . . . 317DIAGTRUNC . . . . . . . . . . . . . 318DLL . . . . . . . . . . . . . . . . 318DUMP . . . . . . . . . . . . . . . 319DYNAM . . . . . . . . . . . . . . . 320EXIT . . . . . . . . . . . . . . . . 321EXPORTALL . . . . . . . . . . . . . 321FASTSRT . . . . . . . . . . . . . . . 322FLAG . . . . . . . . . . . . . . . . 322FLAGSTD . . . . . . . . . . . . . . 323INTDATE . . . . . . . . . . . . . . 325LANGUAGE . . . . . . . . . . . . . 326LIB. . . . . . . . . . . . . . . . . 327LINECOUNT . . . . . . . . . . . . . 327LIST . . . . . . . . . . . . . . . . 328MAP . . . . . . . . . . . . . . . . 328MDECK . . . . . . . . . . . . . . . 329NAME . . . . . . . . . . . . . . . 331NSYMBOL . . . . . . . . . . . . . . 331NUMBER . . . . . . . . . . . . . . 332NUMPROC . . . . . . . . . . . . . . 333OBJECT . . . . . . . . . . . . . . . 334OFFSET . . . . . . . . . . . . . . . 335OPTFILE . . . . . . . . . . . . . . . 335OPTIMIZE . . . . . . . . . . . . . . 336OUTDD . . . . . . . . . . . . . . . 337PGMNAME . . . . . . . . . . . . . . 338PGMNAME(COMPAT) . . . . . . . . . 339PGMNAME(LONGUPPER). . . . . . . . 339PGMNAME(LONGMIXED) . . . . . . . 340Usage notes . . . . . . . . . . . . . 340QUOTE/AP<strong>OS</strong>T . . . . . . . . . . . . 340RENT . . . . . . . . . . . . . . . . 341RMODE . . . . . . . . . . . . . . . 342SEQUENCE . . . . . . . . . . . . . . 343SIZE . . . . . . . . . . . . . . . . 344SOURCE . . . . . . . . . . . . . . . 344SPACE . . . . . . . . . . . . . . . 345SQL . . . . . . . . . . . . . . . . 345SQLCCSID . . . . . . . . . . . . . . 347SSRANGE . . . . . . . . . . . . . . 347TERMINAL . . . . . . . . . . . . . . 348TEST . . . . . . . . . . . . . . . . 349THREAD. . . . . . . . . . . . . . . 352TRUNC . . . . . . . . . . . . . . . 353TRUNC example 1 . . . . . . . . . . 355TRUNC example 2 . . . . . . . . . . 355VBREF . . . . . . . . . . . . . . . 356WORD . . . . . . . . . . . . . . . 356XMLPARSE . . . . . . . . . . . . . . 357XREF . . . . . . . . . . . . . . . . 358YEARWINDOW . . . . . . . . . . . . 360ZWB . . . . . . . . . . . . . . . . 360Chapter 19. Debugging . . . . . . . . . 367Debugging with source language . . . . . . . 367Tracing program logic . . . . . . . . . 368Finding and handling input-output errors . . . 369Validating data . . . . . . . . . . . . 369Finding uninitialized data . . . . . . . . 370Generating in<strong>for</strong>mation about procedures . . . 370Example: USE FOR DEBUGGING . . . . 371Debugging using compiler options . . . . . . 372Finding coding errors . . . . . . . . . 372Finding line sequence problems . . . . . . 373Checking <strong>for</strong> valid ranges . . . . . . . . 373Selecting the level of error to be diagnosed . . 374Example: embedded messages. . . . . . 375Finding program entity definitions andreferences . . . . . . . . . . . . . 376Listing data items . . . . . . . . . . . 376Using the debugger . . . . . . . . . . . 377Getting listings . . . . . . . . . . . . . 377Example: short listing . . . . . . . . . 379Example: SOURCE and NUMBER output . . . 381Example: MAP output . . . . . . . . . 382Example: embedded map summary . . . . 383Terms used in MAP output. . . . . . . 384Symbols used in LIST and MAP output . . 385Example: nested program map . . . . . 386Reading LIST output . . . . . . . . . . 387Example: program initialization code . . . 388Signature in<strong>for</strong>mation bytes: compileroptions . . . . . . . . . . . . . 389Signature in<strong>for</strong>mation bytes: DATADIVISION . . . . . . . . . . . . 391Signature in<strong>for</strong>mation bytes:ENVIRONMENT DIVISION . . . . . . 392Signature in<strong>for</strong>mation bytes: PROCEDUREDIVISION verbs . . . . . . . . . . 392Signature in<strong>for</strong>mation bytes: morePROCEDURE DIVISION items . . . . . 394Example: assembler code generated fromsource code . . . . . . . . . . . . 395Example: TGT memory map . . . . . . 396Example: DSA memory map . . . . . . 398Example: location and size ofWORKING-STORAGE . . . . . . . . 398Example: XREF output: data-namecross-references. . . . . . . . . . . . 398Example: XREF output: program-namecross-references. . . . . . . . . . . 400Example: XREF output: COPY/BASIScross-references. . . . . . . . . . . 400Example: XREF output: embeddedcross-reference . . . . . . . . . . . 401Example: OFFSET compiler output . . . . . 402Example: VBREF compiler output . . . . . 403Chapter 18. Compiler-directing statements . . 363248 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 14. Compiling under z/<strong>OS</strong>You can compile <strong>Enterprise</strong> <strong>COBOL</strong> programs under z/<strong>OS</strong> using job controllanguage (JCL), TSO commands, CLISTs, or ISPF panels.For compiling with JCL, IBM provides a set of cataloged procedures, which canreduce the amount of JCL coding that you need to write. If the catalogedprocedures do not meet your needs, you can write your own JCL. Using JCL, youcan compile a single program or compile several programs as part of a batch job.When compiling under TSO, you can use TSO commands, CLISTs, or ISPF panels.You can also compile in a z/<strong>OS</strong> UNIX shell by using the cob2 command.You might instead want to start the <strong>Enterprise</strong> <strong>COBOL</strong> compiler from an assemblerprogram, <strong>for</strong> example, if your shop has developed a tool or interface that calls the<strong>Enterprise</strong> <strong>COBOL</strong> compiler.As part of the compilation step, you need to define the data sets needed <strong>for</strong> thecompilation and specify any compiler options necessary <strong>for</strong> your program and thedesired output.The compiler translates your <strong>COBOL</strong> program into language that the computer canprocess (object code). The compiler also lists errors in your source statements andprovides supplementary in<strong>for</strong>mation to help you debug and tune your program.Use compiler-directing statements and compiler options to control yourcompilation.After compiling your program, you need to review the results of the compilationand correct any compiler-detected errors.RELATED TASKS“Compiling with JCL”“Compiling under TSO” on page 261Chapter 15, “Compiling under z/<strong>OS</strong> UNIX,” on page 283“Starting the compiler from an assembler program” on page 263“Defining compiler input and output” on page 264“Specifying compiler options under z/<strong>OS</strong>” on page 271“Compiling multiple programs (batch compilation)” on page 274“Correcting errors in your source program” on page 279Compiling with JCLRELATED REFERENCESChapter 18, “Compiler-directing statements,” on page 363“Data sets used by the compiler under z/<strong>OS</strong>” on page 265“Compiler options and compiler output under z/<strong>OS</strong>” on page 273Include the following in<strong>for</strong>mation in the JCL <strong>for</strong> compilation: job description,statement to invoke the compiler, and definitions of the needed data sets(including the directory paths of HFS files, if any).© Copyright IBM Corp. 1991, 2009 249


The simplest way to compile your program under z/<strong>OS</strong> is to code JCL that uses acataloged procedure. A cataloged procedure is a set of job control statements in apartitioned data set called the procedure library (SYS1.PROCLIB).The following JCL shows the general <strong>for</strong>mat <strong>for</strong> a cataloged procedure.//jobname JOB parameters//stepname EXEC [PROC=]procname[,{PARM=|PARM.stepname=}'options']//SYSIN DD data-set parameters... (source program to be compiled)/*//Additional considerations apply when you use cataloged procedures to compileobject-oriented programs.“Example: sample JCL <strong>for</strong> a procedural DLL application” on page 484RELATED TASKS“Using a cataloged procedure”“Writing JCL to compile programs” on page 259“Specifying compiler options under z/<strong>OS</strong>” on page 271“Specifying compiler options in a batch compilation” on page 276“Compiling programs to create DLLs” on page 482RELATED REFERENCES“Data sets used by the compiler under z/<strong>OS</strong>” on page 265Using a cataloged procedureSpecify a cataloged procedure in an EXEC statement in your JCL.For example, the following JCL calls the IBM-supplied cataloged procedureIGYWC <strong>for</strong> compiling an <strong>Enterprise</strong> <strong>COBOL</strong> program and defining the requireddata sets://JOB1 JOB1//STEPA EXEC PROC=IGYWC//<strong>COBOL</strong>.SYSIN DD *000100 IDENTIFICATION DIVISION* (the source code).../*You can omit /* after the source code. If your source code is stored in a data set,replace SYSIN DD * with appropriate parameters that describe the data set.You can use these procedures with any of the job schedulers that are part of z/<strong>OS</strong>.When a scheduler encounters parameters that it does not require, the schedulereither ignores them or substitutes alternative parameters.If the compiler options are not explicitly supplied with the procedure, defaultoptions established at the installation apply. You can override these default optionsby using an EXEC statement that includes the desired options.You can specify data sets to be in the hierarchical file system by overriding thecorresponding DD statement. However, the compiler utility files (SYSUTx) and copylibraries (SYSLIB) you specify must be MVS data sets.250 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Additional details about invoking cataloged procedures, overriding and adding toEXEC statements, and overriding and adding to DD statements are in the LanguageEnvironment in<strong>for</strong>mation.RELATED TASKSLanguage Environment <strong>Programming</strong> <strong>Guide</strong>RELATED REFERENCES“Compile procedure (IGYWC)”“Compile and link-edit procedure (IGYWCL)” on page 252“Compile, link-edit, and run procedure (IGYWCLG)” on page 253“Compile, load, and run procedure (IGYWCG)” on page 254“Compile, prelink, and link-edit procedure (IGYWCPL)” on page 255“Compile, prelink, link-edit, and run procedure (IGYWCPLG)” on page 256“Prelink and link-edit procedure (IGYWPL)” on page 258“Compile, prelink, load, and run procedure (IGYWCPG)” on page 258MVS Program Management: User’s <strong>Guide</strong> and ReferenceCompile procedure (IGYWC)IGYWC is a single-step cataloged procedure <strong>for</strong> compiling a program. It producesan object module. The compile steps in all other cataloged procedures that invokethe compiler are similar.You must supply the following DD statement, indicating the location of the sourceprogram, in the input stream://<strong>COBOL</strong>.SYSIN DD * (or appropriate parameters)If you use copybooks in the program that you are compiling, you must also supplya DD statement <strong>for</strong> SYSLIB or other libraries that you specify in COPY statements. Forexample://<strong>COBOL</strong>.SYSLIB DD DISP=SHR,DSN=DEPT88.BOBS.COBLIB//IGYWC PROC LNGPRFX='IGY.V4R2M0',SYSLBLK=3200//*//* COMPILE A <strong>COBOL</strong> PROGRAM//*//* PARAMETER DEFAULT VALUE USAGE//* SYSLBLK 3200 BLKSIZE FOR OBJECT DATA SET//* LNGPRFX IGY.V4R2M0 PREFIX FOR LANGUAGE DATA SET NAMES//*//* CALLER MUST SUPPLY //<strong>COBOL</strong>.SYSIN DD ...//*//<strong>COBOL</strong> EXEC PGM=IGYCRCTL,REGION=2048K//STEPLIB DD DSNAME=&LNGPRFX..SIGYCOMP, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,UNIT=SYSDA,// DISP=(MOD,PASS),SPACE=(TRK,(3,3)),// DCB=(BLKSIZE=&SYSLBLK)//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1)) (2)//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))(1) STEPLIB can be installation-dependent.(2) SYSUT5 is needed only if the LIB option is used.Chapter 14. Compiling under z/<strong>OS</strong> 251


“Example: JCL <strong>for</strong> compiling using HFS”Example: JCL <strong>for</strong> compiling using HFS:The following job uses procedure IGYWC to compile a <strong>COBOL</strong> program demo.cblthat is located in the hierarchical file system (HFS). It writes the generatedcompiler listing demo.lst, object file demo.o, and SYSADATA file demo.adt to theHFS.//HFSDEMO JOB ,// TIME=(1),MSGLEVEL=(1,1),MSGCLASS=H,CLASS=A,REGION=50M,// NOTIFY=&SYSUID,USER=&SYSUID//COMPILE EXEC IGYWC,// PARM.<strong>COBOL</strong>='LIST,MAP,RENT,FLAG(I,I),XREF,ADATA'//SYSPRINT DD PATH='/u/userid/cobol/demo.lst', (1)// PATHOPTS=(OWRONLY,OCREAT,OTRUNC), (2)// PATHMODE=SIRWXU, (3)// FILEDATA=TEXT (4)//SYSLIN DD PATH='/u/userid/cobol/demo.o',// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),// PATHMODE=SIRWXU//SYSADATA DD PATH='/u/userid/cobol/demo.adt',// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),// PATHMODE=SIRWXU//SYSIN DD PATH='/u/userid/cobol/demo.cbl',// PATHOPTS=ORDONLY,// FILEDATA=TEXT,// RECFM=F(1) PATH specifies the path name <strong>for</strong> an HFS file.(2) PATHOPTS indicates the access <strong>for</strong> the file (such as read or read-write) andsets the status <strong>for</strong> the file (such as append, create, or truncate).(3) PATHMODE indicates the permissions, or file access attributes, to be set whena file is created.(4) FILEDATA specifies whether the data is to be treated as text or binary.You can use a mixture of HFS (PATH='hfs-directory-path') and MVS data sets(DSN=traditional-data-set-name) on the compilation DD statements shown in thisexample as overrides. However, the compiler utility files (DD statements SYSUTx)and COPY libraries (DD statements SYSLIB) must be MVS data sets.RELATED REFERENCESUNIX System Services Command ReferenceMVS JCL Reference“Data sets used by the compiler under z/<strong>OS</strong>” on page 265Compile and link-edit procedure (IGYWCL)IGYWCL is a two-step cataloged procedure to compile and link-edit a program.The <strong>COBOL</strong> job step produces an object module that is input to the linkage editoror binder. You can add other object modules. You must supply the following DDstatement, indicating the location of the source program, in the input stream://<strong>COBOL</strong>.SYSIN DD * (or appropriate parameters)If the program uses copybooks, you must also supply a DD statement <strong>for</strong> SYSLIB orother libraries that you specify in COPY statements. For example://<strong>COBOL</strong>.SYSLIB DD DISP=SHR,DSN=DEPT88.BOBS.COBLIB252 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


IGYWCL PROC LNGPRFX='IGY.V4R2M0',SYSLBLK=3200,// LIBPRFX='CEE',// PGMLIB='&&G<strong>OS</strong>ET',GOPGM=GO//*//* COMPILE AND LINK EDIT A <strong>COBOL</strong> PROGRAM//*//* PARAMETER DEFAULT VALUE USAGE//* LNGPRFX IGY.V4R2M0 PREFIX FOR LANGUAGE DATA SET NAMES//* SYSLBLK 3200 BLOCK SIZE FOR OBJECT DATA SET//* LIBPRFX CEE PREFIX FOR LIBRARY DATA SET NAMES//* PGMLIB &&G<strong>OS</strong>ET DATA SET NAME FOR LOAD MODULE//* GOPGM GO MEMBER NAME FOR LOAD MODULE//*//* CALLER MUST SUPPLY //<strong>COBOL</strong>.SYSIN DD ...//*//<strong>COBOL</strong> EXEC PGM=IGYCRCTL,REGION=2048K//STEPLIB DD DSNAME=&LNGPRFX..SIGYCOMP, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,UNIT=SYSDA,// DISP=(MOD,PASS),SPACE=(TRK,(3,3)),// DCB=(BLKSIZE=&SYSLBLK)//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1)) (2)//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//LKED EXEC PGM=HEWL,COND=(8,LT,<strong>COBOL</strong>),REGION=1024K//SYSLIB DD DSNAME=&LIBPRFX..SCEELKED, (3)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,DISP=(OLD,DELETE)// DD DDNAME=SYSIN//SYSLMOD DD DSNAME=&PGMLIB(&GOPGM),// SPACE=(TRK,(10,10,1)),// UNIT=SYSDA,DISP=(MOD,PASS)//SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(10,10))(1) STEPLIB can be installation-dependent.(2) SYSUT5 is needed only if the LIB option is used.(3) SYSLIB can be installation-dependent.Compile, link-edit, and run procedure (IGYWCLG)IGYWCLG is a three-step cataloged procedure to compile, link-edit, and run aprogram.The <strong>COBOL</strong> job step produces an object module that is input to the linkage editoror binder. You can add other object modules. If the <strong>COBOL</strong> program refers to anydata sets, you must also supply DD statements that define these data sets. You mustsupply the following DD statement, indicating the location of the source program,in the input stream://<strong>COBOL</strong>.SYSIN DD * (or appropriate parameters)If the program uses copybooks, you must also supply a DD statement <strong>for</strong> SYSLIB orother libraries that you specify in COPY statements. For example://<strong>COBOL</strong>.SYSLIB DD DISP=SHR,DSN=DEPT88.BOBS.COBLIB//IGYWCLG PROC LNGPRFX='IGY.V4R2M0',SYSLBLK=3200,// LIBPRFX='CEE',GOPGM=GO//*Chapter 14. Compiling under z/<strong>OS</strong> 253


* COMPILE, LINK EDIT AND RUN A <strong>COBOL</strong> PROGRAM//*//* PARAMETER DEFAULT VALUE USAGE//* LNGPRFX IGY.V4R2M0 PREFIX FOR LANGUAGE DATA SET NAMES//* SYSLBLK 3200 BLKSIZE FOR OBJECT DATA SET//* LIBPRFX CEE PREFIX FOR LIBRARY DATA SET NAMES//* GOPGM GO MEMBER NAME FOR LOAD MODULE//*//* CALLER MUST SUPPLY //<strong>COBOL</strong>.SYSIN DD ...//*//<strong>COBOL</strong> EXEC PGM=IGYCRCTL,REGION=2048K//STEPLIB DD DSNAME=&LNGPRFX..SIGYCOMP, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,UNIT=SYSDA,// DISP=(MOD,PASS),SPACE=(TRK,(3,3)),// DCB=(BLKSIZE=&SYSLBLK)//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1)) (2)//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//LKED EXEC PGM=HEWL,COND=(8,LT,<strong>COBOL</strong>),REGION=1024K//SYSLIB DD DSNAME=&LIBPRFX..SCEELKED, (3)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,DISP=(OLD,DELETE)// DD DDNAME=SYSIN//SYSLMOD DD DSNAME=&&G<strong>OS</strong>ET(&GOPGM),SPACE=(TRK,(10,10,1)),// UNIT=SYSDA,DISP=(MOD,PASS)//SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(10,10))//GO EXEC PGM=*.LKED.SYSLMOD,COND=((8,LT,<strong>COBOL</strong>),(4,LT,LKED)),// REGION=2048K//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//CEEDUMP DD SYSOUT=*//SYSUDUMP DD SYSOUT=*(1) STEPLIB can be installation-dependent.(2) SYSUT5 is needed only if the LIB option is used.(3) SYSLIB can be installation-dependent.Compile, load, and run procedure (IGYWCG)IGYWCG is a two-step cataloged procedure to compile, load, and run a program.The <strong>COBOL</strong> job step produces an object module that is input to the loader. If the<strong>COBOL</strong> program refers to any data sets, you must supply the DD statements thatdefine these data sets. You must supply the following DD statement, indicating thelocation of the source program, in the input stream://<strong>COBOL</strong>.SYSIN DD * (or appropriate parameters)If the program uses copybooks, you must also supply a DD statement <strong>for</strong> SYSLIB orother libraries that you specify in COPY statements. For example://<strong>COBOL</strong>.SYSLIB DD DISP=SHR,DSN=DEPT88.BOBS.COBLIB//IGYWCG PROC LNGPRFX='IGY.V4R2M0',SYSLBLK=3200,// LIBPRFX='CEE'//*//* COMPILE, LOAD AND RUN A <strong>COBOL</strong> PROGRAM254 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


*//* PARAMETER DEFAULT VALUE USAGE//* LNGPRFX IGY.V4R2M0 PREFIX FOR LANGUAGE DATA SET NAMES//* SYSLBLK 3200 BLKSIZE FOR OBJECT DATA SET//* LIBPRFX CEE PREFIX FOR LIBRARY DATA SET NAMES//*//* CALLER MUST SUPPLY //<strong>COBOL</strong>.SYSIN DD ...//*//<strong>COBOL</strong> EXEC PGM=IGYCRCTL,REGION=2048K//STEPLIB DD DSNAME=&LNGPRFX..SIGYCOMP, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,UNIT=SYSDA, (2)// DISP=(MOD,PASS),SPACE=(TRK,(3,3)),// DCB=(BLKSIZE=&SYSLBLK)//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1)) (3)//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//GO EXEC PGM=LOADER,COND=(8,LT,<strong>COBOL</strong>),REGION=2048K//SYSLIB DD DSNAME=&LIBPRFX..SCEELKED, (4)// DISP=SHR//SYSLOUT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,DISP=(OLD,DELETE)//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//CEEDUMP DD SYSOUT=*//SYSUDUMP DD SYSOUT=*(1) STEPLIB can be installation-dependent.(2) SYSLIN can reside in the HFS.(3) SYSUT5 is needed only if the LIB option is used.(4) SYSLIB can be installation-dependent.Compile, prelink, and link-edit procedure (IGYWCPL)IGYWCPL is a three-step cataloged procedure <strong>for</strong> compiling, prelinking, andlink-editing a program.You must supply the following DD statement, indicating the location of the sourceprogram, in the input stream:SYSIN DD * (or appropriate parameters)If the program uses copybooks, you must also supply a DD statement <strong>for</strong> SYSLIB orother libraries that you specify in COPY statements. For example://<strong>COBOL</strong>.SYSLIB DD DISP=SHR,DSN=DEPT88.BOBS.COBLIB//IGYWCPL PROC LNGPRFX='IGY.V4R2M0',SYSLBLK=3200,// LIBPRFX='CEE',PLANG=EDCPMSGE,// PGMLIB='&&G<strong>OS</strong>ET',GOPGM=GO//*//* COMPILE, PRELINK AND LINK EDIT A <strong>COBOL</strong> PROGRAM//*//* PARAMETER DEFAULT VALUE USAGE//* LNGPRFX IGY.V4R2M0 PREFIX FOR LANGUAGE DATA SET NAMES//* SYSLBLK 3200 BLOCK SIZE FOR OBJECT DATA SET//* LIBPRFX CEE PREFIX FOR LIBRARY DATA SET NAMES//* PLANG EDCPMSGE PRELINKER MESSAGES MODULE//* PGMLIB &&G<strong>OS</strong>ET DATA SET NAME FOR LOAD MODULEChapter 14. Compiling under z/<strong>OS</strong> 255


* GOPGM GO MEMBER NAME FOR LOAD MODULE//*//* CALLER MUST SUPPLY //<strong>COBOL</strong>.SYSIN DD ...//*//<strong>COBOL</strong> EXEC PGM=IGYCRCTL,REGION=2048K//STEPLIB DD DSNAME=&LNGPRFX..SIGYCOMP, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,UNIT=SYSDA,// DISP=(MOD,PASS),SPACE=(TRK,(3,3)),// DCB=(BLKSIZE=&SYSLBLK)//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1)) (2)//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//PLKED EXEC PGM=EDCPRLK,PARM='',COND=(8,LT,<strong>COBOL</strong>),// REGION=2048K//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN,// DISP=SHR//SYSMSGS DD DSNAME=&LIBPRFX..SCEEMSGP(&PLANG),// DISP=SHR//SYSLIB DD DUMMY//SYSIN DD DSN=&&LOADSET,DISP=(OLD,DELETE)//SYSMOD DD DSNAME=&&PLKSET,UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(100,50)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSDEFSD DD DUMMY//SYSOUT DD SYSOUT=*//SYSPRINT DD SYSOUT=*//*//LKED EXEC PGM=HEWL,COND=(8,LT,<strong>COBOL</strong>),REGION=1024K//SYSLIB DD DSNAME=&LIBPRFX..SCEELKED, (3)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&PLKSET,DISP=(OLD,DELETE)// DD DDNAME=SYSIN//SYSLMOD DD DSNAME=&PGMLIB(&GOPGM),// SPACE=(TRK,(10,10,1)),// UNIT=SYSDA,DISP=(MOD,PASS)//SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(10,10))(1) STEPLIB can be installation-dependent.(2) SYSUT5 is needed only if the LIB option is used.(3) SYSLIB can be installation-dependent.Compile, prelink, link-edit, and run procedure (IGYWCPLG)IGYWCPLG is a four-step cataloged procedure <strong>for</strong> compiling, prelinking,link-editing, and running a program.You must supply the following DD statement, indicating the location of the sourceprogram, in the input stream:SYSIN DD * (or appropriate parameters)If the program uses copybooks, you must also supply a DD statement <strong>for</strong> SYSLIB orother libraries that you specify in COPY statements. For example://<strong>COBOL</strong>.SYSLIB DD DISP=SHR,DSN=DEPT88.BOBS.COBLIB//IGYWCPLG PROC LNGPRFX='IGY.V4R2M0',SYSLBLK=3200,// PLANG=EDCPMSGE,// LIBPRFX='CEE',GOPGM=GO256 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


*//* COMPILE, PRELINK, LINK EDIT, AND RUN A <strong>COBOL</strong> PROGRAM//*//* PARAMETER DEFAULT VALUE USAGE//* LNGPRFX IGY.V4R2M0 PREFIX FOR LANGUAGE DATA SET NAMES//* SYSLBLK 3200 BLKSIZE FOR OBJECT DATA SET//* PLANG EDCPMSGE PRELINKER MESSAGES MODULE//* LIBPRFX CEE PREFIX FOR LIBRARY DATA SET NAMES//* GOPGM GO MEMBER NAME FOR LOAD MODULE//*//* CALLER MUST SUPPLY //<strong>COBOL</strong>.SYSIN DD ...//*//<strong>COBOL</strong> EXEC PGM=IGYCRCTL,REGION=2048K//STEPLIB DD DSNAME=&LNGPRFX..SIGYCOMP, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,UNIT=SYSDA,// DISP=(MOD,PASS),SPACE=(TRK,(3,3)),// DCB=(BLKSIZE=&SYSLBLK)//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1)) (2)//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//PLKED EXEC PGM=EDCPRLK,PARM='',COND=(8,LT,<strong>COBOL</strong>),// REGION=2048K//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN,// DISP=SHR//SYSMSGS DD DSNAME=&LIBPRFX..SCEEMSGP(&PLANG),// DISP=SHR//SYSLIB DD DUMMY//SYSIN DD DSN=&&LOADSET,DISP=(OLD,DELETE)//SYSMOD DD DSNAME=&&PLKSET,UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(100,50)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSDEFSD DD DUMMY//SYSOUT DD SYSOUT=*//SYSPRINT DD SYSOUT=*//*//LKED EXEC PGM=HEWL,COND=(8,LT,<strong>COBOL</strong>),REGION=1024K//SYSLIB DD DSNAME=&LIBPRFX..SCEELKED, (3)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&PLKSET,DISP=(OLD,DELETE)// DD DDNAME=SYSIN//SYSLMOD DD DSNAME=&&G<strong>OS</strong>ET(&GOPGM),SPACE=(TRK,(10,10,1)),// UNIT=SYSDA,DISP=(MOD,PASS)//SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(10,10))//GO EXEC PGM=*.LKED.SYSLMOD,COND=((8,LT,<strong>COBOL</strong>),(4,LT,LKED)),// REGION=2048K//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN,// DISP=SHR//SYSPRINT DD SYSOUT=*//CEEDUMP DD SYSOUT=*//SYSUDUMP DD SYSOUT=*(1) STEPLIB can be installation-dependent.(2) SYSUT5 is needed only if the LIB option is used.(3) SYSLIB can be installation-dependent.Chapter 14. Compiling under z/<strong>OS</strong> 257


Prelink and link-edit procedure (IGYWPL)The IGYWPL cataloged procedure is a two-step procedure <strong>for</strong> prelinking andlink-editing a program.//IGYWPL PROC PLANG=EDCPMSGE,SYSLBLK=3200,// LIBPRFX='CEE',// PGMLIB='&&G<strong>OS</strong>ET',GOPGM=GO//*//* PRELINK AND LINK EDIT A <strong>COBOL</strong> PROGRAM//*//* PARAMETER DEFAULT VALUE USAGE//* PLANG EDCPMSGE PRELINK MESSAGES MEMBER NAME//* SYSLBLK 3200 BLKSIZE FOR OBJECT DATA SET//* LIBPRFX CEE PREFIX FOR LIBRARY DATA SET NAMES//* PGMLIB &&G<strong>OS</strong>ET DATA SET NAME FOR LOAD MODULE//* GOPGM GO MEMBER NAME FOR LOAD MODULE//*//* CALLER MUST SUPPLY //PLKED.SYSIN DD ...//*//PLKED EXEC PGM=EDCPRLK,PARM='',// REGION=2048K//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN, (1)// DISP=SHR//SYSMSGS DD DSNAME=&LIBPRFX..SCEEMSGP(&PLANG),// DISP=SHR//SYSLIB DD DUMMY//SYSMOD DD DSNAME=&&PLKSET,UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(32000,(100,50)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=&SYSLBLK)//SYSDEFSD DD DUMMY//SYSOUT DD SYSOUT=*//SYSPRINT DD SYSOUT=*//*//LKED EXEC PGM=HEWL,COND=(4,LT,PLKED),REGION=1024K//SYSLIB DD DSNAME=&LIBPRFX..SCEELKED, (2)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=*.PLKED.SYSMOD,DISP=(OLD,DELETE)// DD DDNAME=SYSIN//SYSLMOD DD DSNAME=&PGMLIB(&GOPGM),SPACE=(TRK,(10,10,1)),// UNIT=SYSDA,DISP=(MOD,PASS)//SYSUT1 DD UNIT=SYSDA,SPACE=(TRK,(10,10))//SYSIN DD DUMMY(1) STEPLIB can be installation-dependent.(2) SYSLIB can be installation-dependent.Compile, prelink, load, and run procedure (IGYWCPG)IGYWCPG is a four-step cataloged procedure <strong>for</strong> compiling, prelinking, loading,and running a program.You must supply the following DD statement, indicating the location of the sourceprogram, in the input stream://<strong>COBOL</strong>.SYSIN DD * (or appropriate parameters)If the program uses copybooks, you must also supply a DD statement <strong>for</strong> SYSLIB orother libraries that you specify in COPY statements. For example://<strong>COBOL</strong>.SYSLIB DD DISP=SHR,DSN=DEPT88.BOBS.COBLIB//IGYWCPG PROC LNGPRFX='IGY.V4R2M0',SYSLBLK=3200,// PLANG=EDCPMSGE,// LIBPRFX='CEE'258 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


*//* COMPILE, PRELINK, LOAD, AND RUN A <strong>COBOL</strong> PROGRAM//*//* PARAMETER DEFAULT VALUE USAGE//* LNGPRFX IGY.V4R2M0 PREFIX FOR LANGUAGE DATA SET NAMES//* SYSLBLK 3200 BLKSIZE FOR OBJECT DATA SET//* PLANG EDCPMSGE PRELINKER MESSAGES MODULE//* LIBPRFX CEE PREFIX FOR LIBRARY DATA SET NAMES//*//* CALLER MUST SUPPLY //<strong>COBOL</strong>.SYSIN DD ...//*//<strong>COBOL</strong> EXEC PGM=IGYCRCTL,REGION=2048K//STEPLIB DD DSNAME=&LNGPRFX..SIGYCOMP, (1)// DISP=SHR//SYSPRINT DD SYSOUT=*//SYSLIN DD DSNAME=&&LOADSET,UNIT=SYSDA,// DISP=(MOD,PASS),SPACE=(TRK,(3,3)),// DCB=(BLKSIZE=&SYSLBLK)//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1)) (2)//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//PLKED EXEC PGM=EDCPRLK,PARM='',COND=(8,LT,<strong>COBOL</strong>),// REGION=2048K//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN,// DISP=SHR//SYSMSGS DD DSNAME=&LIBPRFX..SCEEMSGP(&PLANG),// DISP=SHR//SYSLIB DD DUMMY//SYSIN DD DSN=&&LOADSET,DISP=(OLD,DELETE)//SYSMOD DD DSNAME=&&PLKSET,UNIT=SYSDA,DISP=(NEW,PASS), (3)// SPACE=(32000,(100,50)),// DCB=(RECFM=FB,LRECL=80,BLKSIZE=3200)//SYSDEFSD DD DUMMY//SYSOUT DD SYSOUT=*//SYSPRINT DD SYSOUT=*//*//GO EXEC PGM=LOADER,COND=(8,LT,<strong>COBOL</strong>),REGION=2048K//SYSLIB DD DSNAME=&LIBPRFX..SCEELKED, (4)// DISP=SHR//SYSLOUT DD SYSOUT=*//SYSLIN DD DSNAME=&&PLKSET,DISP=(OLD,DELETE)//STEPLIB DD DSNAME=&LIBPRFX..SCEERUN,// DISP=SHR//SYSPRINT DD SYSOUT=*//CEEDUMP DD SYSOUT=*//SYSUDUMP DD SYSOUT=*(1) STEPLIB can be installation-dependent.(2) SYSUT5 is needed only if the LIB option is used.(3) SYSMOD can reside in the HFS.(4) SYSLIB can be installation-dependent.Writing JCL to compile programsIf the cataloged procedures do not give you the flexibility you need <strong>for</strong> morecomplex programs, write your own job control statements. The following exampleshows the general <strong>for</strong>mat of JCL used to compile a program.Chapter 14. Compiling under z/<strong>OS</strong> 259


jobname JOB acctno,name,MSGCLASS=1 (1)//stepname EXEC PGM=IGYCRCTL,PARM=(options) (2)//STEPLIB DD DSNAME=IGY.V4R2M0.SIGYCOMP,DISP=SHR (3)//SYSUT1 DD UNIT=SYSDA,SPACE=(subparms) (4)//SYSUT2 DD UNIT=SYSDA,SPACE=(subparms)//SYSUT3 DD UNIT=SYSDA,SPACE=(subparms)//SYSUT4 DD UNIT=SYSDA,SPACE=(subparms)//SYSUT5 DD UNIT=SYSDA,SPACE=(subparms)//SYSUT6 DD UNIT=SYSDA,SPACE=(subparms)//SYSUT7 DD UNIT=SYSDA,SPACE=(subparms)//SYSPRINT DD SYSOUT=A (5)//SYSLIN DD DSNAME=MYPROG,UNIT=SYSDA, (6)// DISP=(MOD,PASS),SPACE=(subparms)//SYSIN DD DSNAME=dsname,UNIT=device, (7)VOLUME=(subparms),DISP=SHR(1) The JOB statement indicates the beginning of a job.(2) The EXEC statement specifies that the <strong>Enterprise</strong> <strong>COBOL</strong> compiler(IGYCRCTL) is to be invoked.(3) This DD statement defines the data set where the <strong>Enterprise</strong> <strong>COBOL</strong>compiler resides.(4) The SYSUT DD statements define the utility data sets that the compiler willuse to process the source program. All SYSUT files must be ondirect-access storage devices.(5) The SYSPRINT DD statement defines the data set that receives output fromoptions such as LIST and MAP. SYSOUT=A is the standard designation <strong>for</strong> datasets whose destination is the system output device.(6) The SYSLIN DD statement defines the data set that receives output from theOBJECT option (the object module).(7) The SYSIN DD statement defines the data set to be used as input to the jobstep (source code).You can use a mixture of HFS (PATH='hfs-directory-path') and MVS data sets(DSN=traditional-data-set-name) in the compilation DD statements <strong>for</strong> the followingdata sets:v Sources filesv Object filesv Listingsv ADATA filesv Debug filesv Executable modulesHowever, the compiler utility files (DD statements SYSUTx) and COPY libraries (DDstatement SYSLIB) must be MVS data sets.“Example: user-written JCL <strong>for</strong> compiling”“Example: sample JCL <strong>for</strong> a procedural DLL application” on page 484RELATED REFERENCESMVS Program Management: User’s <strong>Guide</strong> and ReferenceExample: user-written JCL <strong>for</strong> compilingThe following example shows a few possibilities <strong>for</strong> adapting the basic JCL.260 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Compiling under TSO//JOB1 JOB (1)//STEP1 EXEC PGM=IGYCRCTL,PARM='OBJECT' (2)//STEPLIB DD DSNAME=IGY.V4R2M0.SIGYCOMP,DISP=SHR//SYSUT1 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT6 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=SYSDA,SPACE=(CYL,(1,1))//SYSPRINT DD SYSOUT=A//SYSLIN DD DSNAME=MYPROG,UNIT=SYSDA,// DISP=(MOD,PASS),SPACE=(TRK,(3,3))//SYSIN DD * (3)000100 IDENTIFICATION DIVISION..../* (4)(1) JOB1 is the name of the job.(2) STEP1 is the name of the sole job step in the job. The EXEC statement alsospecifies that the generated object code should be placed on disk or tape(to be used as input to the link step).(3) The asterisk indicates that the input data set follows in the input stream.(4) The delimiter statement /* separates data from subsequent controlstatements in the input stream.Under TSO, you can use TSO commands, command lists (CLISTs), REXX execs, orISPF to compile programs using traditional MVS data sets. You can use TSOcommands or REXX execs to compile programs using HFS files.With each method, you need to allocate the data sets and request the compilation:1. Use the ALLOCATE command to allocate data sets.For any compilation, allocate the work data sets (SYSUTn) and the SYSIN andSYSPRINT data sets.If you specify certain compiler options, you must allocate other data sets. Forexample, if you specify the TERMINAL compiler option, you must allocate theSYSTERM data set to receive compiler messages at your terminal.You can allocate data sets in any order. However, you must allocate all neededdata sets be<strong>for</strong>e you start to compile.2. Use the CALL command at the READY prompt to request compilation:CALL 'IGY.V4R2M0.SIGYCOMP(IGYCRCTL)'You can specify the ALLOCATE and CALL commands on the TSO command line, or, ifyou are not using HFS files, you can include them in a CLIST.You can allocate HFS files <strong>for</strong> all the compiler data sets except the SYSUTx utilitydata sets and the SYSLIB libraries. ALLOCATE statements have the following <strong>for</strong>m:Allocate File(SYSIN) Path('/u/myu/myap/std/prog2.cbl')Pathopts(ORDONLY) Filedata(TEXT)“Example: ALLOCATE and CALL <strong>for</strong> compiling under TSO” on page 262“Example: CLIST <strong>for</strong> compiling under TSO” on page 262Chapter 14. Compiling under z/<strong>OS</strong> 261


RELATED REFERENCES“Data sets used by the compiler under z/<strong>OS</strong>” on page 265Example: ALLOCATE and CALL <strong>for</strong> compiling under TSOThe following example shows how to specify ALLOCATE and CALL commands whenyou are compiling under TSO.[READY]ALLOCATE FILE(SYSUT1) CYLINDERS SPACE(1 1)[READY]ALLOCATE FILE(SYSUT2) CYLINDERS SPACE(1 1)[READY]ALLOCATE FILE(SYSUT3) CYLINDERS SPACE(1 1)[READY]ALLOCATE FILE(SYSUT4) CYLINDERS SPACE(1 1)[READY]ALLOCATE FILE(SYSUT5) CYLINDERS SPACE(1 1)[READY]ALLOCATE FILE(SYSUT6) CYLINDERS SPACE(1 1)[READY]ALLOCATE FILE(SYSUT7) CYLINDERS SPACE(1 1)[READY]ALLOCATE FILE(SYSPRINT) SYSOUT[READY]ALLOCATE FILE(SYSTERM) DATASET(*)[READY]ALLOCATE FILE(SYSLIN) DATASET(PROG2.OBJ) NEW TRACKS SPACE(3,3)[READY]ALLOCATE FILE(SYSIN) DATASET(PROG2.<strong>COBOL</strong>) SHR[READY]CALL 'IGY.V4R2M0.SIGYCOMP(IGYCRCTL)' 'LIST,NOCOMPILE(S),OBJECT,FLAG(E,E),TERMINAL'.(<strong>COBOL</strong> listings and messages).[READY]FREE FILE(SYSUT1,SYSUT2,SYSUT3,SYSUT4,SYSUT5,SYSUT6,SYSUT7,SYSPRINT,SYSTERM,+SYSIN,SYSLIN)[READY]Example: CLIST <strong>for</strong> compiling under TSOThe following example shows a CLIST <strong>for</strong> compiling under TSO. The FREEcommands are not required. However, good programming practice dictates thatyou free files be<strong>for</strong>e you allocate them.PROC 1 MEMCONTROL LISTFREE (SYSUT1)FREE (SYSUT2)FREE (SYSUT3)FREE (SYSUT4)FREE (SYSUT5)FREE (SYSUT6)FREE (SYSUT7)FREE (SYSPRINT)FREE (SYSIN)FREE (SYSLIN)ALLOC F(SYSPRINT) SYSOUTALLOC F(SYSIN) DA(<strong>COBOL</strong>.SOURCE(&MEM)) SHR REUSEALLOC F(SYSLIN) DA(<strong>COBOL</strong>.OBJECT(&MEM)) OLD REUSEALLOC F(SYSUT1) NEW SPACE(5,5) TRACKS UNIT(SYSDA)ALLOC F(SYSUT2) NEW SPACE(5,5) TRACKS UNIT(SYSDA)ALLOC F(SYSUT3) NEW SPACE(5,5) TRACKS UNIT(SYSDA)ALLOC F(SYSUT4) NEW SPACE(5,5) TRACKS UNIT(SYSDA)262 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


ALLOC F(SYSUT5) NEW SPACE(5,5) TRACKS UNIT(SYSDA)ALLOC F(SYSUT6) NEW SPACE(5,5) TRACKS UNIT(SYSDA)ALLOC F(SYSUT7) NEW SPACE(5,5) TRACKS UNIT(SYSDA)CALL 'IGY.V4R2M0.SIGYCOMP(IGYCRCTL)'Starting the compiler from an assembler programYou can start the <strong>Enterprise</strong> <strong>COBOL</strong> compiler from within an assembler programby using the ATTACH or the LINK macro by dynamic invocation. You must identifythe compiler options and the ddnames of the data sets to be used duringprocessing.For example:symbol {LINK|ATTACH} EP=IGYCRCTL,PARAM=(optionlist[,ddnamelist]),VL=1EPSpecifies the symbolic name of the compiler. The control program (fromthe library directory entry) determines the entry point at which theprogram should begin running.PARAM Specifies, as a sublist, address parameters to be passed from the assemblerprogram to the compiler.The first fullword in the address parameter list contains the address of the<strong>COBOL</strong> optionlist. The second fullword contains the address of theddnamelist. The third and fourth fullwords contain the addresses of nullparameters, or zero.optionlistSpecifies the address of a variable-length list that contains the <strong>COBOL</strong>options specified <strong>for</strong> compilation. This address must be written even if nolist is provided.The optionlist must begin on a halfword boundary. The 2 high-order bytescontain a count of the number of bytes in the remainder of the list. If nooptions are specified, the count must be zero. The optionlist is free<strong>for</strong>m,with each field separated from the next by a comma. No blanks or zerosshould appear. The compiler recognizes only the first 100 characters.ddnamelistSpecifies the address of a variable-length list that contains alternativeddnames <strong>for</strong> the data sets used during compiler processing. If standardddnames are used, the ddnamelist can be omitted.The ddnamelist must begin on a halfword boundary. The 2 high-order bytescontain a count of the number of bytes in the remainder of the list. Eachname of less than 8 bytes must be left justified and padded with blanks. Ifan alternate ddname is omitted from the list, the standard name isassumed. If the name is omitted, the 8-byte entry must contain binaryzeros. You can omit names from the end by shortening the list.All SYSUTn data sets specified must be on direct-access storage devicesand have physical sequential organization. They must not reside in theHFS.The following table shows the sequence of the 8-byte entries in theddnamelist.Alternative ddname 8-byte entry Name <strong>for</strong> which alternative ddname is substituted1 SYSLINChapter 14. Compiling under z/<strong>OS</strong> 263


Alternative ddname 8-byte entry Name <strong>for</strong> which alternative ddname is substituted2 Not applicable3 Not applicable4 SYSLIB5 SYSIN6 SYSPRINT7 SYSPUNCH8 SYSUT19 SYSUT210 SYSUT311 SYSUT412 SYSTERM13 SYSUT514 SYSUT615 SYSUT716 SYSADATA17 SYSJAVA18 SYSDEBUG19 SYSMDECK20 SYSOPTF21 DBRMLIBVLSpecifies that the sign bit is to be set to 1 in the last fullword of theaddress parameter list.When the compiler completes processing, it puts a return code in register 15.RELATED TASKS“Defining compiler input and output”RELATED REFERENCES“Data sets used by the compiler under z/<strong>OS</strong>” on page 265“Compiler options and compiler output under z/<strong>OS</strong>” on page 273Defining compiler input and outputYou need to define several kinds of data sets that the compiler uses to do its work.The compiler takes input data sets and libraries and produces various types ofoutput, including object code, listings, and messages. The compiler also uses utilitydata sets during compilation.RELATED TASKS“Defining the source code data set (SYSIN)” on page 267“Defining a compiler-option data set (SYSOPTF)” on page 267“Specifying source libraries (SYSLIB)” on page 268“Defining the output data set (SYSPRINT)” on page 269“Directing compiler messages to your terminal (SYSTERM)” on page 269“Creating object code (SYSLIN or SYSPUNCH)” on page 269264 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Defining an associated-data file (SYSADATA)” on page 270“Defining the Java-source output file (SYSJAVA)” on page 270“Defining the debug data set (SYSDEBUG)” on page 270“Defining the library-processing output file (SYSMDECK)” on page 271RELATED REFERENCES“Data sets used by the compiler under z/<strong>OS</strong>”“Compiler options and compiler output under z/<strong>OS</strong>” on page 273Data sets used by the compiler under z/<strong>OS</strong>Table 36. Compiler data setsThe following table lists the function, device requirements, and allowable deviceclasses <strong>for</strong> each data set that the compiler uses.Type ddname Function Required?Input SYSIN 1 Reading source YesprogramUtilitySYSOPTFSYSLIB orother copylibraries 1SYSUT1,SYSUT2,SYSUT3,SYSUT4,SYSUT6 2SYSUT5 2SYSUT7 2Reading compileroptionsReading user sourcelibraries (PDSs orPDSEs)Work data set usedby compiler duringcompilationWork data set usedby compiler duringcompilationWork data set usedby compiler to createlistingIf OPTFILE is in effectIf program has COPY or BASISstatements (LIB is required)DevicerequirementsCard reader;intermediatestorageCard reader;intermediatestorage; directaccessAllowabledeviceclassesAnyAnyCanresidein HFS?YesYesDirect access SYSDA NoYes Direct access SYSDA NoIf program has COPY,REPLACE, orBASIS statements(LIB is required)Direct access SYSDA NoYes Direct access SYSDA NoChapter 14. Compiling under z/<strong>OS</strong> 265


Table 36. Compiler data sets (continued)Type ddname Function Required?Output SYSPRINT 1 Writing storage map, Yeslistings, andmessagesSYSTERMWriting progress anddiagnostic messagesIf TERM is in effectDevicerequirementsPrinter;intermediatestorageOutputdevice; TSOterminalSYSPUNCH Creating object code If DECK is in effect Card punch;direct accessSYSLINSYSADATASYSJAVASYSUDUMP,SYSABEND, orSYSMDUMPSYSDEBUGSYSMDECKCreating objectmodule data set asoutput from compilerand input to linkageeditor or binderWriting associateddata file recordsCreating generatedJava source file <strong>for</strong> aclass definitionWriting dumpWriting symbolicdebug in<strong>for</strong>mationtables to a data setseparate from theobject moduleWriting expansion ofCOPY, BASIS, REPLACE,and EXEC SQLINCLUDE statementsAllowabledeviceclassesSYSSQ, SYSDA,standardoutput classASYSSQ, SYSDACanresidein HFS?YesYesYesIf OBJECT is in effect Direct access SYSSQ, SYSDA YesIf ADATA is in effectIf compiling a classdefinitionIf DUMP is in effect (should berarely used)If TEST(. . .,SEP,. . .) isin effect1. You can use the EXIT option to provide user exits from these data sets.2. These data sets must be single volume.Outputdevice(Must be anHFS file)YesYesDirect access SYSDA YesDirect access SYSDA YesIf MDECK is in effect Direct access SYSDA YesRELATED REFERENCES“Logical record length and block size”“EXIT” on page 321Logical record length and block sizeFor compiler data sets other than the work data sets (SYSUTn) and z/<strong>OS</strong> UNIXfiles, you can set the block size by using the BLKSIZE subparameter of the DCBparameter. The value must be permissible <strong>for</strong> the device on which the data setresides. The values you set depend on whether the data sets are fixed length orvariable length.For fixed-length records (RECFM=F or RECFM=FB), LRECL is the logical record length;and BLKSIZE equals LRECL multiplied by n where n is equal to the blocking factor.266 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The following table shows the defined values <strong>for</strong> the fixed-length data sets. Ingeneral, you should not change these values, but you can change the value <strong>for</strong> thefollowing data sets:v SYSDEBUG: You can specify any LRECL in the listed range, with 1024recommended.vSYSPRINT, SYSDEBUG: You can specify BLKSIZE=0, which results in asystem-determined block size.Table 37. Block size of fixed-length compiler data setsData set RECFM LRECL (bytes) BLKSIZE 1SYSDEBUG 2 F or FB 80 to 1024 3 LRECL x nSYSIN F or FB 80 80 x nSYSLIB or other copy libraries F or FB 80 80 x nSYSLIN F or FB 80 80 x nSYSMDECK F or FB 80 80 x nSYSOPTF F or FB 80 80 x nSYSPRINT 2 F or FB 133 133 x nSYSPUNCH F or FB 80 80 x nSYSTERM F or FB 80 80 x n1. n = blocking factor2. If you specify BLKSIZE=0, the system determines the block size.3. The default LRECL <strong>for</strong> SYSDEBUG is 1024.For variable-length records (RECFM=V), LRECL is the logical record length, andBLKSIZE equals LRECL plus 4.Table 38. Block size of variable-length compiler data setsLRECL BLKSIZE (bytes) minimumData setRECFM (bytes) acceptable valueSYSADATA VB 1020 1024Defining the source code data set (SYSIN)Define the data set that contains your source code by using the SYSIN DD statementas shown below.//SYSIN DD DSNAME=dsname,UNIT=SYSSQ,VOLUME=(subparms),DISP=SHRYou can place your source code or BASIS statement directly in the input stream. Todo so, use this SYSIN DD statement://SYSIN DD *The source code or BASIS statement must follow theDD * statement. If another jobstep follows the compilation, the EXEC statement <strong>for</strong> that step must follow the /*statement or the last source statement.Defining a compiler-option data set (SYSOPTF)Define a data set that contains the compiler options <strong>for</strong> your <strong>COBOL</strong> program bycoding the SYSOPTF DD statement as shown below.Chapter 14. Compiling under z/<strong>OS</strong> 267


SYSOPTF DD DSNAME=dsname,UNIT=SYSDA,VOLUME=(subparms),DISP=SHRTo use a compiler-option data set, specify OPTFILE either as a compiler invocationoption or in a PROCESS or CBL statement in your source program.Within the SYSOPTF data set:v Specify compiler options in free <strong>for</strong>m between columns 2 and 72, using the samesyntax as you use <strong>for</strong> invocation options or <strong>for</strong> compiler options in a PROCESS orCBL statement.v Code an asterisk (*) in column 1 to cause a line to be treated as a comment.v Optionally code sequence numbers in columns 73 through 80; those columns areignored.You can optionally place the compiler options directly in the input stream after theSYSOPTF DD statement if you compile using the OPTFILE option://COB EXEC PGM=IGYCRCTL,PARM='OPTFILE'//SYSOPTF DD DATA,DLM=@@SSRANGE ARITH(COMPAT)OPTIMIZE...@@//SYSIN DD ...You can concatenate multiple SYSOPTF DD statements if you have multiplecompiler-option data sets://SYSOPTF DD DSNAME=dsname1, ...// DD DSNAME=dsname2, ...Compiler options that are in later data sets in the concatenation take precedenceover options in earlier data sets in the concatenation.RELATED REFERENCES“Logical record length and block size” on page 266“OPTFILE” on page 335Specifying source libraries (SYSLIB)Use SYSLIB DD statements if your program contains COPY or BASIS statements.These DD statements define the libraries (partitioned data sets) that contain the datarequested by COPY statements in the source code or by BASIS statements in theinput stream.//SYSLIB DD DSNAME=copylibname,DISP=SHRConcatenate multiple DD statements if you have multiple copy or basis libraries://SYSLIB DD DSNAME=PROJECT.USERLIB,DISP=SHR// DD DSNAME=SYSTEM.COPYX,DISP=SHRLibraries are on direct-access storage devices. They cannot be in the HFS when youcompile with JCL or under TSO.You do not need the SYSLIB DD statement if the NOLIB option is in effect.268 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Defining the output data set (SYSPRINT)You can use ddname SYSPRINT to produce a listing. The listing includes the resultsof the default or requested options of the PARM parameter (that is, diagnosticmessages and the object-code listing).You can direct the output to a SYSOUT data set, a printer, a direct-access storagedevice, or a magnetic-tape device. For example://SYSPRINT DD SYSOUT=AThe SYSPRINT data set can be a sequential data set, a PDS or PDSE member, or anHFS file. For details about how to specify the record <strong>for</strong>mat, record length, andblock size of the SYSPRINT data set, see the related reference below.RELATED REFERENCES“Logical record length and block size” on page 266Directing compiler messages to your terminal (SYSTERM)If you are compiling under TSO, you can define the SYSTERM data set to sendcompiler messages to your terminal.ALLOC F(SYSTERM) DA(*)You can define SYSTERM in various other ways, <strong>for</strong> example to a SYSOUT data set,a data set on disk, a file in the HFS, or to another print class.Creating object code (SYSLIN or SYSPUNCH)When using the OBJECT compiler option, you can store the object code on disk as atraditional MVS data set or an HFS file, or on tape. The compiler uses the file thatyou define in the SYSLIN or SYSPUNCH DD statement.//SYSLIN DD DSNAME=dsname,UNIT=SYSDA,// SPACE=(subparms),DISP=(MOD,PASS)Use the DISP parameter of the SYSLIN DD statement to indicate whether the objectcode data set is to be:v Passed to the linkage editor or binderv Catalogedv Keptv Added to an existing cataloged libraryIn the example above, the data is created and passed to another job step, thelinkage editor or binder job step.Your installation might use the DECK option and the SYSPUNCH DD statement. B is thestandard output class <strong>for</strong> punch data sets://SYSPUNCH DD SYSOUT=BYou do not need the SYSLIN DD statement if the NOOBJECT option is in effect. You donot need the SYSPUNCH DD statement if the NODECK option is in effect.Chapter 14. Compiling under z/<strong>OS</strong> 269


RELATED REFERENCES“OBJECT” on page 334“DECK” on page 317Defining an associated-data file (SYSADATA)Define a SYSADATA file if you use the ADATA compiler option.//SYSADATA DD DSNAME=dsname,UNIT=SYSDAThe SYSADATA file will be a sequential file that contains specific record types thathave in<strong>for</strong>mation about the program that is collected during compilation. The filecan be a traditional MVS data set or an HFS file.RELATED REFERENCES“ADATA” on page 305Defining the Java-source output file (SYSJAVA)Add the SYSJAVA DD statement if you are compiling an OO program. The generatedJava source file is written to the SYSJAVA ddname.//SYSJAVA DD PATH='/u/userid/java/Classname.java',// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),// PATHMODE=SIRWXU,// FILEDATA=TEXTThe SYSJAVA file must be in the HFS.RELATED TASKS“Compiling OO applications in JCL or TSO/E” on page 296Defining the debug data set (SYSDEBUG)When you compile from JCL or from TSO and specify the TEST(. . .,SEP,. . .)compiler option, the symbolic debug in<strong>for</strong>mation tables are written to the data setthat you specify in the SYSDEBUG DD statement.//SYSDEBUG DDDSNAME=dsname,UNIT=SYSDAThe SYSDEBUG data set can be a sequential data set, a PDS or PDSE member, or anHFS file. For details about how to specify the record <strong>for</strong>mat, record length, andblock size of the SYSDEBUG data set, see the related reference below about logicalrecord length and block size.Language Environment uses SYSDEBUG <strong>for</strong> its dump services, and you can changethe name of that data set at run time by using the SYSDEBUG <strong>COBOL</strong> debug fileuser exit, IGZIUXB. You can direct Debug Tool to a renamed data set using the SETDEFAULT LISTINGS command, user exit EQAUEDAT, or the EQADEBUG DD statement.The data-set name that you specify in ddname SYSDEBUG might be used by severalIBM products, including Language Environment, Debug Tool, Fault Analyzer, andApplication Per<strong>for</strong>mance Analyzer. For details, see the documentation of thoseindividual products.270 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKSLanguage Environment Customization (Modifying the <strong>COBOL</strong> debug file name)Debug Tool User’s <strong>Guide</strong> (How does Debug Tool locate <strong>COBOL</strong> and PL/Iseparate debug files)RELATED REFERENCES“Logical record length and block size” on page 266“TEST” on page 349Defining the library-processing output file (SYSMDECK)Define a SYSMDECK file if you use the MDECK compiler option.//SYSMDECK DD DSNAME=dsname,UNIT=SYSDAThe SYSMDECK file will contain the output from library processing, that is, theexpansion of COPY, BASIS, REPLACE, and EXEC SQL INCLUDE statements. The file canbe a traditional MVS data set or an HFS file.RELATED REFERENCES“MDECK” on page 329Specifying compiler options under z/<strong>OS</strong>The compiler is installed with default compiler options. While installing thecompiler, the system programmer can fix compiler option settings to, <strong>for</strong> example,ensure better per<strong>for</strong>mance or maintain certain standards. You cannot override anycompiler options that are fixed.For options that are not fixed, you can override the default settings by specifyingcompiler options in any of these ways:v Code them on the PROCESS or CBL statement in <strong>COBOL</strong> source.vvInclude them when you start the compiler, either on the PARM parameter on theEXEC statement in the JCL or on the command line under TSO.Include them in a SYSOPTF data set, and specify the OPTFILE compiler option ineither of the above ways.The compiler recognizes the options in the following order of precedence fromhighest to lowest:1. Installation defaults that are fixed by your site2. Values of the BUFSIZE, LIB, OUTDD, SIZE, and SQL compiler options in effect <strong>for</strong>the first program in a batch3. Options specified on PROCESS (or CBL) statements, preceding the IDENTIFICATIONDIVISION4. Options specified on the compiler invocation (JCL PARM parameter or the TSOCALL command)5. Installation defaults that are not fixedThis order of precedence also determines which options are in effect whenconflicting or mutually exclusive options are specified.The precedence of options in a SYSOPTF data set depends on where you specify theOPTFILE compiler option. For example, if you specify OPTFILE in a PROCESSChapter 14. Compiling under z/<strong>OS</strong> 271


statement, the SYSOPTF options supersede the options that you specify in thecompiler invocation. For further details, see the related reference below about theOPTFILE option.Most of the options come in pairs; you select one or the other. For example, theoption pair <strong>for</strong> a cross-reference listing is XREF|NOXREF. If you want across-reference listing, specify XREF; if you do not, specify NOXREF.Some options have subparameters. For example, if you want 44 lines per page onyour listings, specify LINECOUNT(44).“Example: specifying compiler options using JCL” on page 273“Example: specifying compiler options under TSO” on page 273RELATED TASKS“Defining a compiler-option data set (SYSOPTF)” on page 267“Specifying compiler options with the PROCESS (CBL) statement”“Specifying compiler options in a batch compilation” on page 276RELATED REFERENCES“Compiler options and compiler output under z/<strong>OS</strong>” on page 273Chapter 17, “Compiler options,” on page 301“Conflicting compiler options” on page 304“OPTFILE” on page 335Specifying compiler options with the PROCESS (CBL)statementYou can code compiler options in the PROCESS statement in <strong>COBOL</strong> programs.Code it be<strong>for</strong>e the IDENTIFICATION DIVISION header and be<strong>for</strong>e any comment linesor compiler-directing statements.CBL/PROCESS statement syntax►►CBLPROCESSoptions-list►◄You can start the PROCESS statement in column 1 through 66 if you do not code asequence field. A sequence field is allowed in columns 1 through 6; if used, thesequence field must contain six characters, and the first character must be numeric.When used with a sequence field, PROCESS can start in column 8 through 66.You can use CBL as a synonym <strong>for</strong> PROCESS. CBL can start in column 1 through 70.When used with a sequence field, CBL can start in column 8 through 70.Use one or more blanks to separate PROCESS from the first option in options-list.Separate options with a comma or a blank. Do not insert spaces betweenindividual options and their suboptions.272 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


You can use more than one PROCESS statement. If you do so, the PROCESS statementsmust follow each another with no intervening statements. You cannot continueoptions across multiple PROCESS statements.Your programming organization can inhibit the use of PROCESS statements by usingthe default options module of the <strong>COBOL</strong> compiler. When PROCESS statements arefound in a <strong>COBOL</strong> program but are not allowed by the organization, the <strong>COBOL</strong>compiler generates error diagnostics.RELATED REFERENCESCBL (PROCESS) statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: specifying compiler options using JCLThe following example shows how to specify compiler options under z/<strong>OS</strong> usingJCL....//STEP1 EXEC PGM=IGYCRCTL,// PARM='LIST,NOCOMPILE(S),OBJECT,FLAG(E,E)'Example: specifying compiler options under TSOThe following example shows how to specify compiler options under TSO....[READY]CALL 'SYS1.LINKLIB(IGYCRCTL)' 'LIST,NOCOMPILE(S),OBJECT,FLAG(E,E)'Compiler options and compiler output under z/<strong>OS</strong>When the compiler finishes processing your source program, it will have producedone or more outputs, depending on the compiler options that were in effect.Table 39. Types of compiler output under z/<strong>OS</strong>Compiler option Compiler output Type of outputADATA In<strong>for</strong>mation about the program being compiled Associated-data fileDLL Object module that is enabled <strong>for</strong> DLL support ObjectDUMPSystem dump, if compilation ended with abnormaltermination (requires SYSUDUMP, SYSABEND, orSYSMDUMPDD statement); should be used rarelyListingEXPORTALL Exported symbols <strong>for</strong> a DLL ObjectFLAG List of errors that the compiler found in your program ListingLISTListing of object code in machine and assembler ListinglanguageMAP Map of the data items in your program ListingMDECKExpansion of library-processing statements in your Library-processing side fileprogramNUMBER User-supplied line numbers shown in listing ListingOBJECT or DECK with COMPILE Your object codeObjectOFFSET Map of the relative addresses in your object code ListingOPTIMIZE Optimized object code if OBJECT in effect ObjectRENT Reentrant object code if OBJECT in effect ObjectChapter 14. Compiling under z/<strong>OS</strong> 273


Table 39. Types of compiler output under z/<strong>OS</strong> (continued)Compiler option Compiler output Type of outputSOURCE Listing of your source program ListingSQLSQL statements and host variable in<strong>for</strong>mation <strong>for</strong> DB2bind processDatabase request module(DBRM)SSRANGE Extra code <strong>for</strong> checking references within tables In objectTERMINAL Progress and diagnostic messages sent to terminal TerminalTEST(HOOK) Compiled-in hooks <strong>for</strong> Debug Tool Extra code in objectTEST(N<strong>OS</strong>EP)In<strong>for</strong>mation tables <strong>for</strong> Debug Tool and <strong>for</strong> <strong>for</strong>matteddumpsObjectTEST(SEP)In<strong>for</strong>mation tables <strong>for</strong> Debug Tool and <strong>for</strong> <strong>for</strong>matted Separate debug filedumpsVBREF Cross-reference listing of verbs in your source program ListingXREFSorted cross-reference listing of names of procedures,programs, and dataListingListing output from compilation will be in the data set defined by SYSPRINT; objectoutput will be in SYSLIN or SYSPUNCH. Progress and diagnostic messages can bedirected to the SYSTERM data set and included in the SYSPRINT data set. Thedatabase request module (DBRM) is the data set defined in DBRMLIB. The separatedebug file is the data set defined in SYSDEBUG.Save the listings you produced during compilation. You can use them during thetesting of your work if you need to debug or tune.After compilation, fix any errors that the compiler found in your program. If noerrors were detected, you can go to the next step in the process: link-editing orbinding your program. (If you used compiler options to suppress object codegeneration, you must recompile to obtain object code.)RELATED TASKSLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (Preparing to link-edit and run)RELATED REFERENCES“Messages and listings <strong>for</strong> compiler-detected errors” on page 280Chapter 17, “Compiler options,” on page 301Compiling multiple programs (batch compilation)You can compile a sequence of separate <strong>COBOL</strong> programs by using a singleinvocation of the compiler. You can link the object program produced from thiscompilation into one load module or separate load modules, controlled by the NAMEcompiler option.When you compile several programs as part of a batch job, you need to:v Determine whether you want to create one or more load modules.v Terminate each program in the sequence.v Specify compiler options, with an awareness of the effect of compiler optionsspecified in programs within the batch job.274 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


To create separate load modules, precede each set of modules with the NAMEcompiler option. When the compiler encounters the NAME option, the first programin the sequence and all subsequent programs until the next NAME compiler option isencountered are link-edited into a single load module. Then each successiveprogram that is compiled with the NAME option is included in a separate loadmodule.Use the END PROGRAM marker to terminate each program in the sequence except thelast program in the batch (<strong>for</strong> which the END PROGRAM marker is optional).Alternatively, you can precede each program in the sequence with a CBL or PROCESSstatement.If you omit the END PROGRAM marker from a program (other than the last programin a sequence of separate programs), the next program in the sequence will benested in the preceding program. An error can occur in either of the followingsituations:v A PROCESS statement is in a program that is now nested.v A CBL statement is not coded entirely in the sequence number area (columns 1through 6).If a CBL statement is coded entirely in the sequence number area (columns 1through 6), no error message is issued <strong>for</strong> the CBL statement because it isconsidered a label <strong>for</strong> the source statement line.“Example: batch compilation”RELATED TASKS“Specifying compiler options in a batch compilation” on page 276RELATED REFERENCES“NAME” on page 331Example: batch compilationThe following example shows a batch compilation <strong>for</strong> three programs (PROG1,PROG2, and PROG3) and the creation of two load modules using one invocation ofthe IGYWCL cataloged procedure.The following steps occur:v PROG1 and PROG2 are link-edited together to <strong>for</strong>m one load module that has thename PROG2. The entry point of this load module defaults to the first program inthe load module, PROG1.v PROG3 is link-edited by itself into a load module that has the name PROG3.Because it is the only program in the load module, the entry point is also PROG3.//jobname JOB acctno,name,MSGLEVEL=1//stepname EXEC IGYWCL//<strong>COBOL</strong>.SYSIN DD *010100 IDENTIFICATION DIVISION.010200 PROGRAM-ID PROG1....019000 END PROGRAM PROG1.020100 IDENTIFICATION DIVISION.020200 PROGRAM-ID PROG2....029000 END PROGRAM PROG2.CBL NAME030100 IDENTIFICATION DIVISION.Chapter 14. Compiling under z/<strong>OS</strong> 275


030200 PROGRAM-ID PROG3....039000 END PROGRAM PROG3./*//LKED.SYSLMOD DD DSN=&&G<strong>OS</strong>ET (1)/*//P2 EXEC PGM=PROG2//STEPLIB DD DSN=&&G<strong>OS</strong>ET,DISP=(SHR,PASS) (2)... (3)/*//P3 EXEC PGM=PROG3//STEPLIB DD DSN=&&G<strong>OS</strong>ET,DISP=(SHR,PASS) (2)... (4)/*//(1) The data-set name <strong>for</strong> the LKED step SYSLMOD is changed to the temporaryname &&G<strong>OS</strong>ET, without any member name.(2) The temporary data set &&G<strong>OS</strong>ET is used as the STEPLIB <strong>for</strong> steps P2 and P3to run the compiled programs. If the Language Environment library doesnot reside in shared storage, you must also add the library data set as a DDstatement <strong>for</strong> STEPLIB.(3) Other DD statements and input that are required to run PROG1 and PROG2must be added.(4) Other DD statements and input that are required to run PROG3 must beadded.RELATED REFERENCESLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (IBM-supplied cataloged procedures)Specifying compiler options in a batch compilationYou can specify compiler options <strong>for</strong> each program in the batch sequence eitherwith a CBL or PROCESS statement that precedes the program, or upon invocation ofthe compiler.If a CBL or PROCESS statement is specified in the current program, the compilerresolves the CBL or PROCESS statements together with the options in effect be<strong>for</strong>ethe first program. If the current program does not contain CBL or PROCESSstatements, the compiler uses the settings of options in effect <strong>for</strong> the previousprogram.You should be aware of the effect of certain compiler options on the precedence ofcompiler option settings <strong>for</strong> each program in the batch sequence. Compiler optionsare recognized in the following order of precedence, from highest to lowest:1. Installation defaults that are fixed at your site2. Values of the BUFSIZE, LIB, OUTDD, SIZE, and SQL compiler options in effect <strong>for</strong>the first program in the batch3. Options on CBL or PROCESS statements, if any, <strong>for</strong> the current program4. Options specified in the compiler invocation (JCL PARM or TSO CALL)5. Installation defaults that are not fixedIf any program in the batch sequence requires the BUF, LIB, OUTDD, SIZE, orSQLoption, that option must be in effect <strong>for</strong> the first program in the batch sequence.(When processing BASIS, COPY, orREPLACE statements, the compiler handles allprograms in the batch as a single input file.)276 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If you specify the LIB option <strong>for</strong> the batch, you cannot change the NUMBER andSEQUENCE options during the batch compilation. The compiler treats all programs inthe batch as a single input file during NUMBER and SEQUENCE processing under theLIB option; there<strong>for</strong>e, the sequence numbers of the entire input file must be inascending order.If the compiler diagnoses the LANGUAGE option on the CBL or PROCESS statement asan error, the language selection reverts to what was in effect be<strong>for</strong>e the compilerencountered the first CBL or PROCESS statement. The language in effect during abatch compilation con<strong>for</strong>ms to the rules of processing CBL or PROCESS statements inthat environment.“Example: precedence of options in a batch compilation”“Example: LANGUAGE option in a batch compilation” on page 278Example: precedence of options in a batch compilation||The following example listing shows the precedence of compiler options <strong>for</strong> batchcompilation.PP 5655-S71 IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> 4.2.0 Date 08/30/2009. . .Invocation parameters:NOTERMPROCESS(CBL) statements:CBL CURRENCY,FLAG(I,I)Options in effect: All options are installation defaults unless otherwise noted:NOADATAADVQUOTEARITH(COMPAT)NOAWONOBLOCK0BUFSIZE(4096)...CURRENCY Process option PROGRAM 1...FLAG(I,I) Process option PROGRAM 1...NOTERM INVOCATION option...End of compilation <strong>for</strong> program 1...PP 5655-S71 IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> 4.2.0 Date 08/30/2009. . .PROCESS(CBL) statements:CBL AP<strong>OS</strong>TOptions in effect:NOADATAADVAP<strong>OS</strong>T Process option PROGRAM 2ARITH(COMPAT)NOAWONOBLOCK0BUFSIZE(4096)...NOCURRENCY Installation default option <strong>for</strong> PROGRAM 2...FLAG(I) Installation default option...NOTERM INVOCATION option remains in effect...End of compilation <strong>for</strong> program 2Chapter 14. Compiling under z/<strong>OS</strong> 277


Example: LANGUAGE option in a batch compilationThe following example shows the behavior of the LANGUAGE compiler option in abatch environment. The default installation option is ENGLISH (abbreviated EN), andthe invocation option is XX, a nonexistent language.CBL LANG(JP),FLAG(I,I),AP<strong>OS</strong>T,SIZE(MAX) (1)IDENTIFICATION DIVISION. (2)PROGRAM-ID. COMPILE1.. . .END PROGRAM COMPILE1.CBL LANGUAGE(YY) (3)CBL SIZE(2048K),LANGUAGE(JP),LANG(!!) (4)IDENTIFICATION DIVISION. (2)PROGRAM-ID. COMPILE2.. . .END PROGRAM COMPILE2.IDENTIFICATION DIVISION.PROGRAM-ID. COMPILE3.. . .END PROGRAM COMPILE3.CBL LANGUAGE(JP),LANGUAGE(YY) (5). . .(1) The installation default is EN. The invocation option was XX, a nonexistentlanguage. EN is the language in effect.(2) After the CBL statement is scanned, JP is the language in effect.(3) CBL resets the language to EN. YY is ignored because it is superseded by JP.(4) !! is not alphanumeric and is discarded.(5) CBL resets the language to EN. YY supersedes JP but is nonexistent.For the program COMPILE1, the default language English (EN) is in effect when thecompiler scans the invocation options. A diagnostic message is issued inmixed-case English because XX is a nonexistent language identifier. The default ENremains in effect when the compiler scans the CBL statement. The unrecognizedoption AP<strong>OS</strong>T in the CBL statement is diagnosed in mixed-case English because theCBL statement has not completed processing and EN was the last valid languageoption. After the compiler processes the CBL options, the language in effectbecomes Japanese (JP).In the program COMPILE2, the compiler diagnoses CBL statement errors inmixed-case English because English is the language in effect be<strong>for</strong>e the firstprogram is used. If more than one LANGUAGE option is specified, only the last validlanguage specified is used. In this example, the last valid language is Japanese (JP).There<strong>for</strong>e Japanese becomes the language in effect when the compiler finishesprocessing the CBL options. If you want diagnostics in Japanese <strong>for</strong> the options inthe CBL and PROCESS statements, the language in effect be<strong>for</strong>e COMPILE1 must beJapanese.The program COMPILE3 has no CBL statement. It inherits the language in effect,Japanese (JP), from the previous compilation.After compiling COMPILE3, the compiler resets the language in effect to English (EN)because of the CBL statement. The language option in the CBL statement resolvesthe last-specified two-character alphanumeric language identifier, YY. Because YY isnonexistent, the language in effect remains English.278 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Correcting errors in your source programMessages about source-code errors indicate where the error occurred (LINEID). Thetext of a message tells you what the problem is. With this in<strong>for</strong>mation, you cancorrect the source program.Although you should try to correct errors, it is not always necessary to correctsource code <strong>for</strong> every diagnostic message. You can leave a warning-level orin<strong>for</strong>mational-level message in a program without much risk, and you mightdecide that the recoding and compilation that are needed to remove the messageare not worth the ef<strong>for</strong>t. Severe-level and error-level errors, however, indicateprobable program failure and should be corrected.In contrast with the four lower levels of severities, an unrecoverable (U-level) errormight not result from a mistake in your source program. It could come from a flawin the compiler itself or in the operating system. In such cases, the problem mustbe resolved, because the compiler is <strong>for</strong>ced to end early and does not producecomplete object code or listing. If the message occurs <strong>for</strong> a program that has manyS-level syntax errors, correct those errors and compile the program again. You canalso resolve job set-up problems (problems such as missing data-set definitions orinsufficient storage <strong>for</strong> compiler processing) by making changes to the compile job.If your compile job setup is correct and you have corrected the S-level syntaxerrors, you need to contact IBM to investigate other U-level errors.After correcting the errors in your source program, recompile the program. If thissecond compilation is successful, proceed to the link-editing step. If the compilerstill finds problems, repeat the above procedure until only in<strong>for</strong>mational messagesare returned.RELATED TASKS“Generating a list of compiler messages”RELATED REFERENCES“Messages and listings <strong>for</strong> compiler-detected errors” on page 280Generating a list of compiler messages|You can generate a complete listing of compiler diagnostic messages with theirmessage numbers, severities, and text by compiling a program that hasprogram-name ERRMSG.You can code just the PROGRAM-ID paragraph, as shown below, and omit the rest ofthe program.Identification Division.Program-ID. ErrMsg.RELATED TASKS“Customizing compiler-message severities” on page 730RELATED REFERENCES“Messages and listings <strong>for</strong> compiler-detected errors” on page 280“Format of compiler diagnostic messages” on page 280Chapter 14. Compiling under z/<strong>OS</strong> 279


Messages and listings <strong>for</strong> compiler-detected errorsAs the compiler processes your source program, it checks <strong>for</strong> <strong>COBOL</strong> languageerrors, and issues diagnostic messages. These messages are collated in the compilerlisting (subject to the FLAG option).Each message in the listing provides in<strong>for</strong>mation about the nature of the problem,its severity, and the compiler phase that detected it. Wherever possible, themessage provides specific instructions <strong>for</strong> correcting an error.The messages <strong>for</strong> errors found during processing of compiler options, CBL andPROCESS statements, and BASIS, COPY, orREPLACE statements are displayed near thetop of the listing.The messages <strong>for</strong> compilation errors (ordered by line number) are displayed nearthe end of the listing <strong>for</strong> each program.A summary of all problems found during compilation is displayed near the bottomof the listing.RELATED TASKS“Correcting errors in your source program” on page 279“Generating a list of compiler messages” on page 279RELATED REFERENCES“Format of compiler diagnostic messages”“Severity codes <strong>for</strong> compiler diagnostic messages” on page 281“FLAG” on page 322Format of compiler diagnostic messagesEach message issued by the compiler has a source line number, a messageidentifier, and message text.Each message has the following <strong>for</strong>m:nnnnnn IGYppxxxx-l message-textnnnnnnThe number of the source statement of the last line that the compiler wasprocessing. Source statement numbers are listed on the source printout ofyour program. If you specified the NUMBER option at compile time, thenumbers are the original source program numbers. If you specifiedNONUMBER, the numbers are those generated by the compiler.IGY A prefix that identifies that the message was issued by the <strong>COBOL</strong>compiler.pp Two characters that identify which phase or subphase of the compilerdetected the condition that resulted in a message. As an applicationprogrammer, you can ignore this in<strong>for</strong>mation. If you are diagnosing asuspected compiler error, contact IBM <strong>for</strong> support.xxxx A four-digit number that identifies the message.l A character that indicates the severity level of the message: I, W, E, S, or U.280 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


message-textThe message text; <strong>for</strong> an error message, a short explanation of thecondition that caused the error.Tip: If you used the FLAG option to suppress messages, there might be additionalerrors in your program.RELATED REFERENCES“Severity codes <strong>for</strong> compiler diagnostic messages”“FLAG” on page 322Severity codes <strong>for</strong> compiler diagnostic messagesConditions that the compiler can detect fall into five levels or categories of severity.Table 40. Severity codes <strong>for</strong> compiler diagnostic messagesLevel or categoryof messageReturncodePurposeIn<strong>for</strong>mational (I) 0 To in<strong>for</strong>m you. No action is required, and the programruns correctly.Warning (W) 4 To indicate a possible error. The program probably runscorrectly as written.Error (E) 8 To indicate a condition that is definitely an error. Thecompiler attempted to correct the error, but the results ofprogram execution might not be what you expect. Youshould correct the error.Severe (S) 12 To indicate a condition that is a serious error. Thecompiler was unable to correct the error. The programdoes not run correctly, and execution should not beattempted. Object code might not be created.Unrecoverable (U) 16 To indicate an error condition of such magnitude that thecompilation was terminated.|||||The final return code at the end of compilation is generally the highest return codethat occurred <strong>for</strong> any message during the compilation.You can suppress compiler diagnostic messages or change their severities, however,which can have an effect upon the final compilation return code. For details, seethe related in<strong>for</strong>mation.RELATED TASKS“Customizing compiler-message severities” on page 730RELATED REFERENCES“Processing of MSGEXIT” on page 729Chapter 14. Compiling under z/<strong>OS</strong> 281


282 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 15. Compiling under z/<strong>OS</strong> UNIXCompile <strong>Enterprise</strong> <strong>COBOL</strong> programs under z/<strong>OS</strong> UNIX by using the cob2command. Under z/<strong>OS</strong> UNIX, you can compile any <strong>COBOL</strong> program that you cancompile under z/<strong>OS</strong>. The object code generated by the <strong>COBOL</strong> compiler can rununder z/<strong>OS</strong>.As part of the compilation step, you define the files needed <strong>for</strong> the compilation,and specify any compiler options or compiler-directing statements that arenecessary <strong>for</strong> your program and <strong>for</strong> the output that you want.The main job of the compiler is to translate <strong>COBOL</strong> programs into language thatthe computer can process (object code). The compiler also lists errors in sourcestatements and provides supplementary in<strong>for</strong>mation to help you debug and tuneprograms.RELATED TASKS“Setting environment variables under z/<strong>OS</strong> UNIX”“Specifying compiler options under z/<strong>OS</strong> UNIX” on page 284“Compiling and linking with the cob2 command” on page 285“Compiling using scripts” on page 290“Compiling, linking, and running OO applications under z/<strong>OS</strong> UNIX” on page 291RELATED REFERENCES“Data sets used by the compiler under z/<strong>OS</strong>” on page 265“Compiler options and compiler output under z/<strong>OS</strong>” on page 273Setting environment variables under z/<strong>OS</strong> UNIXAn environment variable is a name that is associated with a string of characters andthat defines some variable aspect of the program environment. You useenvironment variables to set values that programs, including the compiler, need.Set the environment variables <strong>for</strong> the compiler by using the export command. Forexample, to set the SYSLIB variable, issue the export command from the shell orfrom a script file:export SYSLIB=/u/mystuff/copybooksThe value that you assign to an environment variable can include otherenvironment variables or the variable itself. The values of these variables applyonly when you compile from the shell where you issue the export command. Ifyou do not set an environment variable, either a default value is applied or thevariable is not defined. The environment-variable names must be uppercase.The environment variables that you can set <strong>for</strong> use by the compiler are as follows:COBOPTSpecify compiler options separated by blanks or commas. Separatesuboptions with commas. Blanks at the beginning or the end of thevariable value are ignored. Delimit the list of options with quotation marksif it contains blanks or characters that are significant to the z/<strong>OS</strong> UNIXshell. For example:export COBOPT="TRUNC(OPT) XREF"© Copyright IBM Corp. 1991, 2009 283


SYSLIBSpecify paths to directories to be used in searching <strong>for</strong> <strong>COBOL</strong> copybooksif you do not specify an explicit library-name in the COPY statement.Separate multiple paths with a colon. Paths are evaluated in order from thefirst path to the last in the export command. If you set the variable withmultiple files of the same name, the first located copy of the file is used.For COPY statements in which you have not coded an explicit library-name,the compiler searches <strong>for</strong> copybooks in this order:1. In the current directory2. In the paths you specify with the -I cob2 option3. In the paths you specify in the SYSLIB environment variablelibrary-nameSpecify the directory path from which to copy when you specify an explicitlibrary-name in the COPY statement. The environment-variable name isidentical to the library-name in your program. You must set an environmentvariable <strong>for</strong> each library; an error will occur otherwise. Theenvironment-variable name library-name must be uppercase.text-nameSpecify the name of the file from which to copy text. Theenvironment-variable name is identical to the text-name in your program.The environment-variable name text-name must be uppercase.RELATED TASKS“Specifying compiler options under z/<strong>OS</strong> UNIX”“Compiling and linking with the cob2 command” on page 285“Setting and accessing environment variables” on page 438RELATED REFERENCESChapter 18, “Compiler-directing statements,” on page 363Chapter 17, “Compiler options,” on page 301COPY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Specifying compiler options under z/<strong>OS</strong> UNIXThe compiler is installed and set up with default compiler options. While installingthe compiler, a system programmer can fix compiler option settings to ensurebetter per<strong>for</strong>mance or maintain certain standards. You cannot override anycompiler options that your site has fixed.For options that are not fixed, you can override the default settings by specifyingcompiler options in any of three ways:v Code them on the PROCESS or CBL statement in your <strong>COBOL</strong> source.v Specify the -q option of the cob2 command.v Set the COBOPT environment variable.The compiler recognizes the options in the above order of precedence, from highestto lowest. The order of precedence also determines which options are in effectwhen conflicting or mutually exclusive options are specified. When you compileusing the cob2 command, compiler options are recognized in the following orderof precedence, from highest to lowest:1. Installation defaults fixed as nonoverridable284 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


2. The values of BUFSIZE, LIB, SQL, OUTDD, and SIZE options in effect <strong>for</strong> the firstprogram in a batch compilation3. The values that you specify on PROCESS or CBL statements in <strong>COBOL</strong> sourceprograms4. The values that you specify in the cob2 command’s -q option string5. The values that you specify in the COBOPT environment variable6. Installation defaults that are not fixedRestrictions:v Do not use the SQL compiler option under z/<strong>OS</strong> UNIX.Neither the separate SQL precompiler nor the integrated SQL coprocessor rununder z/<strong>OS</strong> UNIX.v The OPTFILE option is ignored when you compile using the cob2 commandunder z/<strong>OS</strong> UNIX.You can use the COBOPT environment variable, which provides a capability thatis comparable to OPTFILE, instead.RELATED TASKS“Specifying compiler options with the PROCESS (CBL) statement” on page 272“Setting environment variables under z/<strong>OS</strong> UNIX” on page 283“Compiling and linking with the cob2 command”RELATED REFERENCES“Conflicting compiler options” on page 304Chapter 17, “Compiler options,” on page 301Compiling and linking with the cob2 commandUse the cob2 command to compile and link <strong>COBOL</strong> programs from the z/<strong>OS</strong>UNIX shell. You can specify the options and input file-names in any order, usingspaces to separate options and names. Any options that you specify apply to allfiles on the command line.To compile multiple files (batch compilation), specify multiple source-file names.When you compile <strong>COBOL</strong> programs <strong>for</strong> z/<strong>OS</strong> UNIX, the RENT option is required.The cob2 command automatically includes the <strong>COBOL</strong> compiler options RENT andTERM.The cob2 command invokes the <strong>COBOL</strong> compiler that is found through thestandard MVS search order. If the <strong>COBOL</strong> compiler is not installed in the LNKLST,or if more than one level of IBM <strong>COBOL</strong> compiler is installed on your system, youcan specify in the STEPLIB environment variable the compiler PDS that you wantto use. For example, the following statement specifies IGY.V4R2M0 as the compilerPDS:export STEPLIB=IGY.V4R2M0.SIGYCOMPThe cob2 command implicitly uses the z/<strong>OS</strong> UNIX shell command c89 <strong>for</strong> the linkstep. c89 is the shell interface to the linker (the z/<strong>OS</strong> program managementbinder).The default location <strong>for</strong> compiler input and output is the current directory.Chapter 15. Compiling under z/<strong>OS</strong> UNIX 285


Only files with the suffix .cbl are passed to the compiler; cob2 passes all other filesto the linker.The listing output that you request from the compilation of a <strong>COBOL</strong> sourceprogram file.cbl is written to file.lst. The listing output that you request from thelinker is written to stdout.The linker causes execution to begin at the first main program.RELATED TASKS“Creating a DLL under z/<strong>OS</strong> UNIX”“Preparing OO applications under z/<strong>OS</strong> UNIX” on page 292UNIX System Services User’s <strong>Guide</strong>RELATED REFERENCES“cob2 syntax and options” on page 287“cob2 input and output files” on page 289UNIX System Services Command ReferenceCreating a DLL under z/<strong>OS</strong> UNIXTo create a DLL from the z/<strong>OS</strong> UNIX shell, you must specify the cob2 option-bdll.cob2 -o mydll -bdll mysub.cblWhen you specify cob2 -bdll:v The <strong>COBOL</strong> compiler uses the compiler options DLL, EXPORTALL, and RENT, whichare required <strong>for</strong> DLLs.v The link step produces a DLL definition side file that contains IMPORT controlstatements <strong>for</strong> each of the names exported by the DLL.The name of the DLL definition side file is based on the output file-name. If theoutput name has a suffix, that suffix is replaced with x to <strong>for</strong>m the side-file name.For example, if the output file-name is foo.dll, the side-file name is foo.x.To use the DLL definition side file later when you create a module that calls thatDLL, specify the side file with any other object files (file.o) that you need to link.For example, the following command compiles myappl.cbl, uses the DLL option toenable myappl.o to reference DLLs, and links to produce the module myappl:cob2 -o myappl -qdll myappl.cbl mydll.x“Example: using cob2 to compile and link under z/<strong>OS</strong> UNIX” on page 287RELATED TASKSChapter 26, “Creating a DLL or a DLL application,” on page 481“Compiling programs to create DLLs” on page 482RELATED REFERENCES“cob2 syntax and options” on page 287“cob2 input and output files” on page 289286 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Example: using cob2 to compile and link under z/<strong>OS</strong> UNIXThe following examples illustrate the use of cob2.v To compile one file called alpha.cbl, enter:cob2 -c alpha.cblThe compiled file is named alpha.o.v To compile two files called alpha.cbl and beta.cbl, enter:cob2 -c alpha.cbl beta.cblThe compiled files are named alpha.o and beta.o.v To link two files, compile them without the -c option. For example, to compileand link alpha.cbl and beta.cbl and generate gamma, enter:cob2 alpha.cbl beta.cbl -o gammaThis command creates alpha.o and beta.o, then links alpha.o, beta.o, and the<strong>COBOL</strong> libraries. If the link step is successful, it produces an executable programnamed gamma.v To compile alpha.cbl with the LIST and NODATA options, enter:cob2 -qlist,noadata alpha.cblcob2 syntax and optionscob2 command syntax►► cob2 filenamesoptions►◄You can use the options listed below with the cob2 command. (Do not capitalizecob2.)-bxxxPasses the string xxx to the linker as parameters. xxx is a list of linkeroptions in name=value <strong>for</strong>mat, separated by commas. You must spell outboth the name and the value in full (except <strong>for</strong> the special cases notedbelow). The name and value are case insensitive. Do not use any spacesbetween -b and xxx.If you do not specify a value <strong>for</strong> an option, a default value of YES is usedexcept <strong>for</strong> the following options, which have the indicated default values:v LIST=NOIMPORTv ALIASES=ALLv COMPAT=CURRENTv DYNAM=DLLOne special value <strong>for</strong> xxx is dll, which specifies that the executablemodule is to be a DLL. This string is not passed to the linker.-c Compiles programs but does not link them.-comprc_ok=nControls cob2 behavior on the return code from the compiler. If the returncode is less than or equal to n, cob2 continues to the link step or, in thecompile-only case, exits with a zero return code. If the return codeChapter 15. Compiling under z/<strong>OS</strong> UNIX 287


eturned by the compiler is greater than n, cob2 exits with the same returncode. When the c89 command is implicitly invoked by cob2 <strong>for</strong> the linkstep, the exit value from the c89 command is used as the return code fromthe cob2 command.The default is -comprc_ok=4.-e xxx Specifies the name of a program to be used as the entry point of themodule. If you do not specify -e, the default entry point is the firstprogram (file.cbl) or object file (file.o) that you specify as a file name on thecob2 command invocation.-g Prepares the program <strong>for</strong> debugging. Equivalent to specifying the TESToption with no suboptions.-Ixxx Adds a path xxx to the directories to be searched <strong>for</strong> copybooks <strong>for</strong> whichyou do not specify a library-name.To specify multiple paths, either use multiple -I options, or use a colon toseparate multiple path names within a single -I option value.For COPY statements in which you have not coded an explicit library-name,the compiler searches <strong>for</strong> copybooks in the following order:1. In the current directory2. In the paths you specify with the -I cob2 option3. In the paths you specify in the SYSLIB environment variableIf you use the COPY statement, you must ensure that the LIB compileroption is in effect.-L xxx Specifies the directory paths to be used to search <strong>for</strong> archive librariesspecified by the -l operand.-l xxx Specifies the name of an archive library <strong>for</strong> the linker. The cob2 commandsearches <strong>for</strong> the name libxxx.a in the directories specified in the -L option,then in the usual search order. (This option is lowercase l, not uppercase I.)-o xxx Names the object module xxx. Ifthe-o option is not used, the name of theobject module is a.out.-qxxx Passes xxx to the compiler, where xxx is a list of compiler optionsseparated by blanks or commas.Enclose xxx in quotation marks if a parenthesis is part of the option orsuboption, or if you use blanks to separate options. Do not insert spacesbetween -q and xxx.-v Displays the generated commands that are issued by cob2 <strong>for</strong> the compileand link steps, including the options being passed, and executes them.Here is sample output:cob2 -v -o mini -qssrange mini.cblcompiler: ATTCRCTL PARM=RENT,TERM,SSRANGE /u/userid/cobol/mini.cblPP 5655-S71 IBM <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> 4.2.0 in progress ...End of compilation 1, program mini, no statements flagged.linker: /bin/c89 -o mini -e // mini.o-# Displays compile and link steps, but does not execute them.RELATED TASKS“Compiling and linking with the cob2 command” on page 285“Creating a DLL under z/<strong>OS</strong> UNIX” on page 286“Setting environment variables under z/<strong>OS</strong> UNIX” on page 283288 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


cob2 input and output filesYou can specify the following files as input file-names when you use the cob2command.Table 41. Input files to the cob2 commandFile name Description Commentsfile.cbl <strong>COBOL</strong> source file to be compiledand linkedWill not be linked if you specify thecob2 option -cfile.a Archive file Produced by the ar command, to beused during the link-edit phasefile.o Object file to be link-edited Can be produced by the <strong>COBOL</strong>compiler, the C/C++ compiler, or theassemblerfile.x DLL definition side file Used during the link-edit phase of anapplication that references the dynamiclink library (DLL)When you use the cob2 command, the following files are created in the currentdirectory.Table 42. Output files from the cob2 commandFile name Description Commentsfile Executable module or DLL Created by the linker if you specify thecob2 option -o filea.out Executable module or DLL Created by the linker if you do notspecify the cob2 option -ofile.adt Associated data (ADATA) filecorresponding to input <strong>COBOL</strong>source program file.cblCreated by the compiler if you specifycompiler option ADATAfile.dbgfile.dekfile.lstSymbolic in<strong>for</strong>mation tables <strong>for</strong>Debug Tool corresponding to input<strong>COBOL</strong> source program file.cblExtended <strong>COBOL</strong> source outputfrom library processingListing file corresponding to input<strong>COBOL</strong> source program file.cblCreated by the compiler if you specifycompiler option TEST(. . .,SEP,. . .)Created by the compiler if you specifycompiler option MDECKCreated by the compilerfile.o Object file corresponding to input Created by the compiler<strong>COBOL</strong> source program file.cblfile.x DLL definition side file Created during the cob2 linking phasewhen creating a DLL named file.dllclass.java Java class definition (source) Created when you compile a classdefinitionRELATED TASKS“Compiling and linking with the cob2 command” on page 285RELATED REFERENCES“ADATA” on page 305Chapter 15. Compiling under z/<strong>OS</strong> UNIX 289


Compiling using scripts“MDECK” on page 329“TEST” on page 349UNIX System Services Command ReferenceIf you use a shell script to automate cob2 tasks, you must code option syntaxcarefully to prevent the shell from passing invalid strings to cob2.Code option strings in scripts as follows:v Use an equal sign and colon rather than a left and right parenthesis, respectively,to specify compiler suboptions. For example, code -qOPT=FULL:,XREF instead of-qOPT(FULL),XREF.v Use an underscore rather than a single quotation mark where a compiler optionrequires single quotation marks <strong>for</strong> delimiting a suboption.v Do not use blanks in the option string.290 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 16. Compiling, linking, and running OO applicationsIt is recommended that you compile, link, and run object-oriented (OO)applications in the z/<strong>OS</strong> UNIX environment. However, with certain limitationsexplained in the related tasks, it is possible to compile, link, and run OO <strong>COBOL</strong>applications by using standard batch JCL or TSO/E commands.|RELATED TASKS“Compiling, linking, and running OO applications under z/<strong>OS</strong> UNIX”“Compiling, linking, and running OO applications in JCL or TSO/E” on page 295“Using Java SDKs <strong>for</strong> z/<strong>OS</strong>” on page 299Compiling, linking, and running OO applications under z/<strong>OS</strong> UNIXWhen you compile, link, and run object-oriented applications in a z/<strong>OS</strong> UNIXenvironment, application components reside in the z/<strong>OS</strong> UNIX file system. Youcompile and link them by using shell commands, and run them at a shellcommand prompt or with the BPXBATCH utility from JCL or TSO/E.RELATED TASKS“Compiling OO applications under z/<strong>OS</strong> UNIX”“Preparing OO applications under z/<strong>OS</strong> UNIX” on page 292“Running OO applications under z/<strong>OS</strong> UNIX” on page 293Compiling OO applications under z/<strong>OS</strong> UNIXWhen you compile OO applications in a z/<strong>OS</strong> UNIX shell, use the cob2 commandto compile <strong>COBOL</strong> client programs and class definitions, and the javac commandto compile Java class definitions to produce bytecode (suffix .class).To compile <strong>COBOL</strong> source code that contains OO syntax such as INVOKE statementsor class definitions, or that uses Java services, you must use these compileroptions: RENT, DLL, THREAD, and DBCS. (The RENT and DBCS options are defaults.)A <strong>COBOL</strong> source file that contains a class definition must not contain any otherclass or program definitions.When you compile a <strong>COBOL</strong> class definition, two output files are generated:v The object file (.o) <strong>for</strong> the class definition.v A Java source program (.java) that contains a class definition that corresponds tothe <strong>COBOL</strong> class definition. Do not edit this generated Java class definition inany way. If you change the <strong>COBOL</strong> class definition, you must regenerate boththe object file and the Java class definition by recompiling the updated <strong>COBOL</strong>class definition.If a <strong>COBOL</strong> client program or class definition includes the file JNI.cpy by using aCOPY statement, specify the include subdirectory of the <strong>COBOL</strong> install directory(typically /usr/lpp/cobol/include) in the search order <strong>for</strong> copybooks. You canspecify the include subdirectory by using the -I option of the cob2 command orby setting the SYSLIB environment variable.© Copyright IBM Corp. 1991, 2009 291


RELATED TASKSChapter 15, “Compiling under z/<strong>OS</strong> UNIX,” on page 283“Preparing OO applications under z/<strong>OS</strong> UNIX”“Running OO applications under z/<strong>OS</strong> UNIX” on page 293“Setting and accessing environment variables” on page 438“Accessing JNI services” on page 607RELATED REFERENCES“cob2 syntax and options” on page 287“DBCS” on page 317“DLL” on page 318“RENT” on page 341“THREAD” on page 352Preparing OO applications under z/<strong>OS</strong> UNIXUse the cob2 command to link OO <strong>COBOL</strong> applications.To prepare an OO <strong>COBOL</strong> client program <strong>for</strong> execution, link the object file withthe following two DLL side files to create an executable module:v libjvm.x, which is provided with your IBM Java Software Development Kit.vigzcjava.x, which is provided in the lib subdirectory of the cobol directory inthe z/<strong>OS</strong> UNIX file system. The typical complete path is /usr/lpp/cobol/lib/igzcjava.x. This DLL side file is also available as the member IGZCJAVA in theSCEELIB PDS (part of Language Environment).To prepare a <strong>COBOL</strong> class definition <strong>for</strong> execution:1. Link the object file using the two DLL side files mentioned above to create anexecutable DLL module.You must name the resulting DLL module libClassname.so, where Classname isthe external class-name. If the class is part of a package and thus there areperiods in the external class-name, you must change the periods to underscoresin the DLL module name. For example, if class Account is part of the com.acmepackage, the external class-name (as defined in the REP<strong>OS</strong>ITORY paragraph entry<strong>for</strong> the class) must be com.acme.Account, and the DLL module <strong>for</strong> the classmust be libcom_acme_Account.so.2. Compile the generated Java source with the Java compiler to create a class file(.class).For a <strong>COBOL</strong> source file Classname.cbl that contains the class definition <strong>for</strong>Classname, you would use the following commands to compile and link thecomponents of the application:Table 43. Commands <strong>for</strong> compiling and linking a class definitionCommand Input Outputcob2 -c -qdll,thread Classname.cbl Classname.cbl Classname.o,Classname.java|cob2 -bdll -o libClassname.so Classname.o/usr/lpp/java/J5.0/bin/j9vm/libjvm.x/usr/lpp/cobol/lib/igzcjava.xClassname.olibClassname.sojavac Classname.java Classname.java Classname.class292 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


After you issue the cob2 and javac commands successfully, you have theexecutable components <strong>for</strong> the program: the executable DLL modulelibClassname.so and the class file Classname.class. All files from these commands aregenerated in the current working directory.“Example: compiling and linking a <strong>COBOL</strong> class definition under z/<strong>OS</strong> UNIX”RELATED TASKSChapter 15, “Compiling under z/<strong>OS</strong> UNIX,” on page 283“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class” on page 566RELATED REFERENCES“cob2 syntax and options” on page 287“Object-oriented syntax, and Java 5 or Java 6 SDKs” on page 300Example: compiling and linking a <strong>COBOL</strong> class definitionunder z/<strong>OS</strong> UNIXThis example illustrates the commands that you use and the files that are producedwhen you compile and link a <strong>COBOL</strong> class definition, Manager.cbl, using z/<strong>OS</strong>UNIX shell commands.Manager.cblIdentification division.Class-id Manager inherits Employee.Environment division.Configuration section.Repository.Class Manager is "Manager"...End class Manager.cob2 -c -qdll,thread Manager.cblManager.javaManager.ojavac Manager.javacob2 -bdll -o libManager.so Manager.o/usr/lpp/java/J5.0/bin/j9vm/libjvm.x/usr/lpp/cobol/lib/igzcjava.xManager.classlibManager.soThe class file Manager.class and the DLL module libManager.so are the executablecomponents of the application, and are generated in the current working directory.Running OO applications under z/<strong>OS</strong> UNIXIt is recommended that you run object-oriented <strong>COBOL</strong> applications as z/<strong>OS</strong>UNIX applications. You must do so if an application begins with a Java program orthe main factory method of a <strong>COBOL</strong> class.Chapter 16. Compiling, linking, and running OO applications 293


Specify the directory that contains the DLLs <strong>for</strong> the <strong>COBOL</strong> classes in the LIBPATHenvironment variable. Specify the directory paths <strong>for</strong> the Java class files that areassociated with the <strong>COBOL</strong> classes in the CLASSPATH environment variable asfollows:vvvFor classes that are not part of a package, end the class path with the directorythat contains the .class files.For classes that are part of a package, end the class path with the directory thatcontains the ″root″ package (the first package in the full package name).For a .jar file that contains .class files, end the class path with the name of the.jar file.Separate multiple path entries with colons.RELATED TASKS“Running OO applications that start with a main method”“Running OO applications that start with a <strong>COBOL</strong> program” on page 295“Running J2EE <strong>COBOL</strong> clients” on page 295Chapter 23, “Running <strong>COBOL</strong> programs under z/<strong>OS</strong> UNIX,” on page 437“Setting and accessing environment variables” on page 438Chapter 30, “Writing object-oriented programs,” on page 561“Structuring OO applications” on page 603Running OO applications that start with a main methodIf the first routine of a mixed <strong>COBOL</strong> and Java application is the main method of aJava class or the main factory method of a <strong>COBOL</strong> class, run the application byusing the java command and by specifying the name of the class that contains themain method.The java command initializes the Java virtual machine (JVM). To customize theinitialization of the JVM, specify options on the java command as in the followingexamples:Table 44. java command options <strong>for</strong> customizing the JVMPurposeTo set a system propertyTo request that the JVM generate verbose messages aboutgarbage collectionTo request that the JVM generate verbose messages about classloadingTo request that the JVM generate verbose messages aboutnative methods and other Java Native Interface activityTo set the initial Java heap size to value bytesTo set the maximum Java heap size to value bytesOption-Dname=value-verbose:gc-verbose:class-verbose:jni-Xmsvalue-XmxvalueSee the output from the java -h command or the related references <strong>for</strong> detailsabout the options that the JVM supports.RELATED REFERENCESIBM SDK <strong>for</strong> Java - Tools DocumentationWebSphere <strong>for</strong> z/<strong>OS</strong>: Applications (Java Naming and Directory Interface (JNDI))294 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Running OO applications that start with a <strong>COBOL</strong> programIf the first routine of a mixed <strong>COBOL</strong> and Java application is a <strong>COBOL</strong> program,run the application by specifying the program name at the command prompt. If aJVM is not already running in the process of the <strong>COBOL</strong> program, the <strong>COBOL</strong> runtime automatically initializes a JVM.To customize the initialization of the JVM, specify options by setting theCOBJVMINITOPTIONS environment variable. Use blanks to separate options. Forexample:export COBJVMINITOPTIONS="-Xms10000000 -Xmx20000000 -verbose:gc"|RELATED TASKS“Using Java SDKs <strong>for</strong> z/<strong>OS</strong>” on page 299Chapter 23, “Running <strong>COBOL</strong> programs under z/<strong>OS</strong> UNIX,” on page 437“Setting and accessing environment variables” on page 438RELATED REFERENCESIBM SDK <strong>for</strong> Java - Tools DocumentationWebSphere <strong>for</strong> z/<strong>OS</strong>: Applications (Java Naming and Directory Interface (JNDI))Running J2EE <strong>COBOL</strong> clients:You can use OO syntax in a <strong>COBOL</strong> program to implement a Java 2 Plat<strong>for</strong>m,<strong>Enterprise</strong> Edition (J2EE) client. You can, <strong>for</strong> example, invoke methods onenterprise beans that run in the WebSphere ® <strong>for</strong> z/<strong>OS</strong> environment.Be<strong>for</strong>e you run a <strong>COBOL</strong> J2EE client, you must set the Java system propertyjava.naming.factory.initial to access WebSphere naming services. For example:export COBJVMINITOPTIONS="-Djava.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory"“Example: J2EE client written in <strong>COBOL</strong>” on page 619Compiling, linking, and running OO applications in JCL or TSO/EIt is recommended that you compile, link, and run applications that use OO syntaxin the z/<strong>OS</strong> UNIX environment.However, in limited circumstances it is possible to compile, prepare, and run OOapplications by using standard batch JCL or TSO/E commands. To do so, youmust follow the guidelines that are in the related tasks. For example, you mightfollow this approach <strong>for</strong> applications that consist of a <strong>COBOL</strong> main program andsubprograms that:v Access objects that are all implemented in Javav Access enterprise beans that run in a WebSphere serverRELATED TASKS“Compiling OO applications in JCL or TSO/E” on page 296“Preparing and running OO applications in JCL or TSO/E” on page 296“Compiling, linking, and running OO applications under z/<strong>OS</strong> UNIX” on page 291Chapter 16. Compiling, linking, and running OO applications 295


Compiling OO applications in JCL or TSO/EIf you use batch JCL or TSO/E to compile an OO <strong>COBOL</strong> program or classdefinition, the generated object file is written, as usual, to the data set that hasddname SYSLIN or SYSPUNCH. You must use compiler options RENT, DLL, THREAD, andDBCS. (RENT and DBCS are defaults.)If the <strong>COBOL</strong> program or class definition uses the JNI environment structure toaccess JNI callable services, copy the file JNI.cpy from the HFS to a PDS or PDSEmember called JNI, identify that library with a SYSLIB DD statement, and use aCOPY statement of the <strong>for</strong>m COPY JNI in the <strong>COBOL</strong> source.A <strong>COBOL</strong> source file that contains a class definition must not contain any otherclass or program definitions.When you compile a <strong>COBOL</strong> class definition, a Java source program that containsa class definition that corresponds to the <strong>COBOL</strong> class definition is generated inaddition to the object file. Use the SYSJAVA ddname to write the generated Javasource file to a file in the HFS. For example://SYSJAVA DD PATH='/u/userid/java/Classname.java',// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),// PATHMODE=SIRWXU,// FILEDATA=TEXTDo not edit this generated Java class definition in any way. If you change the<strong>COBOL</strong> class definition, you must regenerate both the object file and the Java classdefinition by recompiling the updated <strong>COBOL</strong> class definition.Compile Java class definitions by using the javac command from a z/<strong>OS</strong> UNIXshell command prompt, or by using the BPXBATCH utility.“Example: compiling, linking, and running an OO application using JCL” on page298RELATED TASKS“Compiling with JCL” on page 249“Compiling under TSO” on page 261“Specifying source libraries (SYSLIB)” on page 268“Defining the Java-source output file (SYSJAVA)” on page 270“Accessing JNI services” on page 607“Compiling OO applications under z/<strong>OS</strong> UNIX” on page 291“Preparing OO applications under z/<strong>OS</strong> UNIX” on page 292RELATED REFERENCES“DBCS” on page 317“DLL” on page 318“RENT” on page 341“THREAD” on page 352Appendix F, “JNI.cpy,” on page 741UNIX System Services User’s <strong>Guide</strong> (The BPXBATCH utility)Preparing and running OO applications in JCL or TSO/EIt is recommended that you run OO applications in a z/<strong>OS</strong> UNIX environment. Torun OO applications from batch JCL or TSO/E, you should there<strong>for</strong>e use theBPXBATCH utility.296 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||In limited circumstances, however, you can run an OO application by usingstandard batch JCL (EXEC PGM=COBPROG) or the TSO/E CALL command. To do so,follow these requirements when preparing the application:vvvvvStructure the application to start with a <strong>COBOL</strong> program. (If an applicationstarts with a Java program or with the main factory method of a <strong>COBOL</strong> class,you must run the application under z/<strong>OS</strong> UNIX, and the applicationcomponents must reside in the z/<strong>OS</strong> UNIX file system.)Link-edit considerations: Link the load module <strong>for</strong> the <strong>COBOL</strong> program into aPDSE. <strong>COBOL</strong> programs that contain object-oriented syntax must be link-editedwith AMODE 31.Ensure that the class files and DLLs associated with the <strong>COBOL</strong> or Java classesthat are used by the application reside in the z/<strong>OS</strong> UNIX file system. You mustname the class files and DLLs as described in the related task about preparingOO applications.Specify INCLUDE control statements <strong>for</strong> the DLL side files libjvm.x and igzcjava.xwhen you bind the object deck <strong>for</strong> the main program. For example:INCLUDE '/usr/lpp/java/J5.0/bin/j9vm/libjvm.x'INCLUDE '/usr/lpp/cobol/lib/igzcjava.x'Create a file that contains the environment variable settings that are required <strong>for</strong>Java. For example, a file /u/userid/javaenv might contain the three lines shownbelow to set the PATH, LIBPATH, and CLASSPATH environment variables.PATH=/bin:/usr/lpp/java/J5.0/binLIBPATH=/lib:/usr/lib:/usr/lpp/java/J5.0/bin:/usr/lpp/java/J5.0/bin/j9vmCLASSPATH=/u/userid/applicationsTo customize the initialization of the JVM that will be used by the application,you can set the COBJVMINITOPTIONS environment variable in the same file.For example, to access enterprise beans that run in a WebSphere server, youmust set the Java system property java.naming.factory.initial. For details, see therelated task about running OO applications.When you run an OO application that starts with a <strong>COBOL</strong> program by usingstandard batch JCL or the TSO/E CALL command, follow these guidelines:vvvvUse the _CEE_ENVFILE environment variable to indicate the location of the filethat contains the environment variable settings required by Java. Set_CEE_ENVFILE by using the ENVAR runtime option.Specify the P<strong>OS</strong>IX(ON) runtime option.Use DD statements to specify files in the z/<strong>OS</strong> UNIX file system <strong>for</strong> the standardinput, output, and error streams <strong>for</strong> Java:– JAVAIN DD <strong>for</strong> the input from statements such as c=System.in.read();– JAVAOUT DD <strong>for</strong> the output from statements such asSystem.out.println(string);– JAVAERR DD <strong>for</strong> the output from statements such asSystem.err.println(string);Ensure that the SCEERUN2 and SCEERUN load libraries are available in thesystem library search order, <strong>for</strong> example, by using a STEPLIB DD statement.“Example: compiling, linking, and running an OO application using JCL” on page298RELATED TASKS“Preparing OO applications under z/<strong>OS</strong> UNIX” on page 292“Running OO applications under z/<strong>OS</strong> UNIX” on page 293“Structuring OO applications” on page 603Chapter 16. Compiling, linking, and running OO applications 297


UNIX System Services User’s <strong>Guide</strong> (The BPXBATCH utility)Language Environment <strong>Programming</strong> <strong>Guide</strong> (Running an application under batch)RELATED REFERENCESXL C/C++ <strong>Programming</strong> <strong>Guide</strong> (_CEE_ENVFILE)Language Environment <strong>Programming</strong> Reference (ENVAR)Example: compiling, linking, and running an OO applicationusing JCLThis example shows sample JCL that you could use to compile, link, and run a<strong>COBOL</strong> client that invokes a Java method.The example shows:v JCL to compile, link, and run an OO <strong>COBOL</strong> program, TSTHELLOv A Java class definition, HelloJ, that contains a method that the <strong>COBOL</strong> programinvokesv A z/<strong>OS</strong> UNIX file, ENV, that contains the environment variable settings thatJava requiresJCL <strong>for</strong> program TSTHELLO//TSTHELLO JOB ,// TIME=(1),MSGLEVEL=(1,1),MSGCLASS=H,CLASS=A,REGION=100M,// NOTIFY=&SYSUID,USER=&SYSUID//*// SET COBPRFX='IGY.V4R2M0'// SET LIBPRFX='CEE'//*//COMPILE EXEC PGM=IGYCRCTL,// PARM='SIZE(5000K)'//SYSLIN DD DSNAME=&&OBJECT(TSTHELLO),UNIT=VIO,DISP=(NEW,PASS),// SPACE=(CYL,(1,1,1))//SYSPRINT DD SYSOUT=*//STEPLIB DD DSN=&COBPRFX..SIGYCOMP,DISP=SHR// DD DSN=&LIBPRFX..SCEERUN,DISP=SHR//SYSUT1 DD UNIT=VIO,SPACE=(CYL,(1,1))//SYSUT2 DD UNIT=VIO,SPACE=(CYL,(1,1))//SYSUT3 DD UNIT=VIO,SPACE=(CYL,(1,1))//SYSUT4 DD UNIT=VIO,SPACE=(CYL,(1,1))//SYSUT5 DD UNIT=VIO,SPACE=(CYL,(1,1))//SYSUT6 DD UNIT=VIO,SPACE=(CYL,(1,1))//SYSUT7 DD UNIT=VIO,SPACE=(CYL,(1,1))//SYSIN DD *cbl dll,threadIdentification division.Program-id. "TSTHELLO" recursive.Environment division.Configuration section.Repository.Class HelloJ is "HelloJ".Data Division.Procedure division.Display "<strong>COBOL</strong> program TSTHELLO entered"Invoke HelloJ "sayHello"Display "Returned from java sayHello to TSTHELLO"Goback.End program "TSTHELLO"./*//LKED EXEC PGM=IEWL,PARM='RENT,LIST,LET,DYNAM(DLL),CASE(MIXED)'//SYSLIB DD DSN=&LIBPRFX..SCEELKED,DISP=SHR// DD DSN=&LIBPRFX..SCEELKEX,DISP=SHR298 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|//SYSPRINT DD SYSOUT=*//SYSTERM DD SYSOUT=*//SYSLMOD DD DSN=&&G<strong>OS</strong>ET(TSTHELLO),DISP=(MOD,PASS),UNIT=VIO,// SPACE=(CYL,(1,1,1)),DSNTYPE=LIBRARY//SYSDEFSD DD DUMMY//OBJMOD DD DSN=&&OBJECT,DISP=(OLD,DELETE)//SYSLIN DD *INCLUDE OBJMOD(TSTHELLO)INCLUDE '/usr/lpp/java/J5.0/bin/j9vm/libjvm.x'INCLUDE '/usr/lpp/cobol/lib/igzcjava.x'/*//GO EXEC PGM=TSTHELLO,COND=(4,LT,LKED),// PARM='/ENVAR("_CEE_ENVFILE=/u/userid/ootest/tsthello/ENV")// P<strong>OS</strong>IX(ON)'//STEPLIB DD DSN=*.LKED.SYSLMOD,DISP=SHR// DD DSN=&LIBPRFX..SCEERUN2,DISP=SHR// DD DSN=&LIBPRFX..SCEERUN,DISP=SHR//SYSOUT DD SYSOUT=*//CEEDUMP DD SYSOUT=*//SYSUDUMP DD DUMMY//JAVAOUT DD PATH='/u/userid/ootest/tsthello/javaout',// PATHOPTS=(OWRONLY,OCREAT,OTRUNC),// PATHMODE=(SIRUSR,SIWUSR,SIRGRP)Definition of class HelloJclass HelloJ {public static void sayHello() {System.out.println("Hello World, from Java!");}}HelloJ.java is compiled with the javac command. The resulting .class file resides inthe z/<strong>OS</strong> UNIX file system directory u/userid/ootest/tsthello, which is specifiedin the CLASSPATH environment variable in the environment variable settings file.||Environment variable settings file, ENVPATH=/bin:/usr/lpp/java/J5.0/bin.LIBPATH=/lib:/usr/lib:/usr/lpp/java/J5.0/bin:/usr/lpp/java/J5.0/bin/j9vmCLASSPATH=/u/userid/ootest/tsthelloThe environment variable settings file also resides in directoryu/userid/ootest/tsthello, as specified in the _CEE_ENVFILE environmentvariable in the JCL.||Using Java SDKs <strong>for</strong> z/<strong>OS</strong>The Java SDKs <strong>for</strong> z/<strong>OS</strong> are based on the XPLINK linkage convention defined byLanguage Environment.If the application starts with a Java program or the main factory method of a<strong>COBOL</strong> class, the XPLINK environment is automatically started by the javacommand that starts the JVM and runs the application.If an application starts with a <strong>COBOL</strong> program that invokes methods on <strong>COBOL</strong>or Java classes, you must specify the XPLINK(ON) runtime option so that theXPLINK environment is initialized. XPLINK(ON) is not recommended as a defaultsetting, however; you should use XPLINK(ON) only <strong>for</strong> applications that specificallyrequire it.Chapter 16. Compiling, linking, and running OO applications 299


When you are running an application under z/<strong>OS</strong> UNIX, you can set theXPLINK(ON) option by using the _CEE_RUNOPTS environment variable as follows:_CEE_RUNOPTS="XPLINK(ON)"Exporting _CEE_RUNOPTS="XPLINK(ON)" so that it is in effect <strong>for</strong> the entire z/<strong>OS</strong>UNIX shell session is not recommended, however. Suppose <strong>for</strong> example that anOO <strong>COBOL</strong> application starts with a <strong>COBOL</strong> program called App1Driver. One wayto limit the effect of the XPLINK option to the execution of the App1Driverapplication is to set the _CEE_RUNOPTS variable on the command-line invocationof App1Driver as follows:_CEE_RUNOPTS="XPLINK(ON)" App1DriverRELATED TASKS“Running OO applications under z/<strong>OS</strong> UNIX” on page 293“Setting and accessing environment variables” on page 438RELATED REFERENCES“Object-oriented syntax, and Java 5 or Java 6 SDKs”“Runtime environment variables” on page 439Language Environment <strong>Programming</strong> Reference (XPLINK)XL C/C++ <strong>Programming</strong> <strong>Guide</strong> (_CEE_RUNOPTS)||||||||||Object-oriented syntax, and Java 5 or Java 6 SDKs<strong>Enterprise</strong> <strong>COBOL</strong> applications that use object-oriented syntax <strong>for</strong> Javainteroperability are supported with Java SDK 1.4.2.To run these existing applications using Java 5 or Java 6, do these steps:1. Recompile and relink the applications using the current version of <strong>Enterprise</strong><strong>COBOL</strong>.2. Recompile the generated Java class that is associated with each object-oriented<strong>COBOL</strong> class using the javac command from Java 5 or Java 6.RELATED TASKS“Preparing OO applications under z/<strong>OS</strong> UNIX” on page 292|300 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 17. Compiler optionsYou can direct and control your compilation by using compiler options or by usingcompiler-directing statements (compiler directives).Compiler options affect the aspects of your program that are listed in the tablebelow. The linked-to in<strong>for</strong>mation <strong>for</strong> each option provides the syntax <strong>for</strong> specifyingthe option and describes the option, its parameters, and its interaction with otherparameters.Table 45. Compiler optionsAspect of yourprogram Compiler option Default Option abbreviationsSource language “ARITH” on page 306 ARITH(COMPAT) AR(C|E)“CICS” on page 309 NOCICS None“CODEPAGE” on page 310 CODEPAGE(01140) CP(ccsid)“CURRENCY” on page 313 NOCURRENCY CURR|NOCURR“DBCS” on page 317 DBCS None“LIB” on page 327 LIB None“NSYMBOL” on page 331 NSYMBOL(NATIONAL) NS(DBCS|NAT)“NUMBER” on page 332 NONUMBER NUM|NONUM“QUOTE/AP<strong>OS</strong>T” on page 340 QUOTE Q|AP<strong>OS</strong>T“SEQUENCE” on page 343 SEQUENCE SEQ|N<strong>OS</strong>EQ“SQL” on page 345 N<strong>OS</strong>QL None“SQLCCSID” on page 347 SQLCCSID SQLC|N<strong>OS</strong>QLC“WORD” on page 356 NOWORD WD|NOWD“XMLPARSE” on page 357 XMLPARSE(XMLSS) XP(X)|XP(C)Date processing “DATEPROC” on page 315 NODATEPROC, orDATEPROC(FLAG,NOTRIG) ifonly DATEPROC is specifiedDP|NODP“INTDATE” on page 325 INTDATE(ANSI) None“YEARWINDOW” on page 360 YEARWINDOW(1900) YWMaps and listings “LANGUAGE” on page 326 LANGUAGE(ENGLISH) LANG(EN|UE|JA|JP)“LINECOUNT” on page 327 LINECOUNT(60) LC“LIST” on page 328 NOLIST None“MAP” on page 328 NOMAP None“OFFSET” on page 335 NOOFFSET OFF|NOOFF“SOURCE” on page 344 SOURCE S|N<strong>OS</strong>“SPACE” on page 345 SPACE(1) None“TERMINAL” on page 348 NOTERMINAL TERM|NOTERM“VBREF” on page 356 NOVBREF None“XREF” on page 358 XREF(FULL) X|NOX© Copyright IBM Corp. 1991, 2009 301


|Table 45. Compiler options (continued)Aspect of yourprogram Compiler option Default Option abbreviationsObject deck “COMPILE” on page 313 NOCOMPILE(S) C|NOCgeneration“DECK” on page 317 NODECK D|NOD“NAME” on page 331NONAME, orNAME(NOALIAS) if Noneonly NAME is specified“OBJECT” on page 334 OBJECT OBJ|NOOBJ“PGMNAME” on page 338 PGMNAME(COMPAT) PGMN(CO|LU|LM)Object code control “ADV” on page 305 ADV None“AWO” on page 307 NOAWO None“BLOCK0” on page 307 NOBLOCK0 None“DLL” on page 318 NODLL None“EXPORTALL” on page 321 NOEXPORTALL EXP|NOEXP“FASTSRT” on page 322 NOFASTSRT FSRT|NOFSRT“NUMPROC” on page 333 NUMPROC(NOPFD) None“OPTIMIZE” on page 336 NOOPTIMIZE OPT|NOOPT“OUTDD” on page 337 OUTDD(SYSOUT) OUT“TRUNC” on page 353 TRUNC(STD) None“ZWB” on page 360 ZWB NoneVirtual storage “BUFSIZE” on page 309 4096 BUFusage“DATA” on page 314 DATA(31) None“DYNAM” on page 320 NODYNAM DYN|NODYN“RENT” on page 341 RENT None“RMODE” on page 342 AUTO None“SIZE” on page 344 SIZE(MAX) SZDebugging and “DIAGTRUNC” on page 318 NODIAGTRUNC DTR|NODTRdiagnostics“DUMP” on page 319 NODUMP DU|NODU“FLAG” on page 322 FLAG(I,I) F|NOF“FLAGSTD” on page 323 NOFLAGSTD None“SSRANGE” on page 347 N<strong>OS</strong>SRANGE SSR|N<strong>OS</strong>SR“TEST” on page 349 NOTEST NoneOther “ADATA” on page 305 NOADATA None“EXIT” on page 321 NOEXIT EX(INX,LIBX,PRTX,ADX)“MDECK” on page 329 NOMDECK NOMD|MD|MD(C)|MD(NOC)“OPTFILE” on page 335 None None“THREAD” on page 352 NOTHREAD NoneInstallation defaults: The default compiler options that were set up when yourcompiler was installed are in effect <strong>for</strong> your program unless you override thoseoptions. (In some installations, certain compiler options are fixed so that youcannot override them. If you have problems with the default options, contact your302 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


system administrator.) To determine which are the default options, run a testcompilation without specifying any compiler options. The output listing lists thedefault options in effect at your site.Nonoverridable options: In some installations, certain compiler options are fixedso that you cannot override them. If you have problems with those options, contactyour system administrator.|Per<strong>for</strong>mance considerations: The ARITH, AWO, BLOCK0, DYNAM, FASTSRT, NUMPROC,OPTIMIZE, RENT, SQLCCSID, SSRANGE, TEST, THREAD, and TRUNC compiler options canaffect runtime per<strong>for</strong>mance.RELATED TASKSChapter 14, “Compiling under z/<strong>OS</strong>,” on page 249“Compiling under TSO” on page 261Chapter 15, “Compiling under z/<strong>OS</strong> UNIX,” on page 283Chapter 34, “Tuning your program,” on page 661RELATED REFERENCES“Conflicting compiler options” on page 304Chapter 18, “Compiler-directing statements,” on page 363“Option settings <strong>for</strong> Standard <strong>COBOL</strong> 85 con<strong>for</strong>mance”“Per<strong>for</strong>mance-related compiler options” on page 672Option settings <strong>for</strong> Standard <strong>COBOL</strong> 85 con<strong>for</strong>manceCompiler options and runtime options are required <strong>for</strong> con<strong>for</strong>mance with Standard<strong>COBOL</strong> 85.The following compiler options are required:v ADVv NOCICSv NODATEPROCv NODLLv DYNAMv NOEXPORTALLv NOFASTSRTv LIBv NAME(ALIAS) or NAME(NOALIAS)v NUMPROC(NOPFD) or NUMPROC(MIG)v PGMNAME(COMPAT) or PGMNAME(LONGUPPER)v QUOTEv NOTHREADv TRUNC(STD)v NOWORDv ZWBThe following runtime options are required:v AIXBLDv CBLQDA(ON)v TRAP(ON)Chapter 17. Compiler options 303


Conflicting compiler optionsRELATED REFERENCESLanguage Environment <strong>Programming</strong> ReferenceThe <strong>Enterprise</strong> <strong>COBOL</strong> compiler can encounter conflicting compiler options ineither of two ways: both the positive and negative <strong>for</strong>m of an option are specifiedat the same level in the hierarchy of precedence, or mutually exclusive options arespecified at the same level in the hierarchy.When conflicting options are specified at the same level in the hierarchy (such asspecifying both DECK and NODECK in a PROCESS or CBL statement), the optionspecified last takes effect.If you specify mutually exclusive compiler options at the same level, the compilergenerates an error message and <strong>for</strong>ces one of the options to a nonconflicting value.For example, if you specify both OFFSET and LIST in a PROCESS statement in anyorder, OFFSET takes effect and LIST is ignored.However, options coded at a higher level of precedence override any optionsspecified at a lower level of precedence. For example, if you code OFFSET in a JCLstatement but LIST in a PROCESS statement, LIST takes effect because the optionscoded in the PROCESS statement and any options <strong>for</strong>ced on by an option coded inthe PROCESS statement have higher precedence.Table 46. Mutually exclusive compiler optionsSpecified Ignored 1 Forced on 1CICS NOLIB LIBDYNAMNODYNAMNORENTRENTDLL DYNAM NODYNAMNORENTRENTEXIT DUMP NODUMPEXPORTALL NODLL DLLDYNAMNODYNAMNORENTRENTMDECK NOLIB LIBNSYMBOL(NATIONAL) NODBCS DBCSOFFSET LIST NOLISTSQL NOLIB LIBTESTNOOBJECTOBJECTTEST(HOOK)OPT(STD) or OPT(FULL)NOOPTIMIZETHREAD NORENT RENTWORD FLAGSTD NOFLAGSTD1. Unless in conflict with a fixed installation default option.RELATED TASKS“Specifying compiler options under z/<strong>OS</strong>” on page 271304 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Specifying compiler options in a batch compilation” on page 276“Specifying compiler options under z/<strong>OS</strong> UNIX” on page 284RELATED REFERENCES“OPTFILE” on page 335ADATAUse ADATA when you want the compiler to create a SYSADATA file that containsrecords of additional compilation in<strong>for</strong>mation.ADATA option syntax►►NOADATAADATA►◄Default is: NOADATAAbbreviations are: NoneADATA is required <strong>for</strong> remote compilation using an IBM Windows <strong>COBOL</strong> compiler.On z/<strong>OS</strong>, the SYSADATA file is written to ddname SYSADATA.The size of the SYSADATA file generally grows with the size of the associatedprogram.Option specification: You cannot specify the ADATA option in a PROCESS (or CBL)statement. You can specify it only in one of the following ways:v In the PARM parameter of JCLv As a cob2 command optionv As an installation defaultv In the COBOPT environment variableRELATED REFERENCESAppendix G, “<strong>COBOL</strong> SYSADATA file contents,” on page 747“Setting environment variables under z/<strong>OS</strong> UNIX” on page 283“cob2 syntax and options” on page 287ADVADV has meaning only if you use WRITE ...ADVANCING in your source code. WithADV in effect, the compiler adds 1 byte to the record length to account <strong>for</strong> theprinter control character.Chapter 17. Compiler options 305


ADV option syntax►►ADVNOADV►◄Default is: ADVAbbreviations are: NoneUse NOADV if you already adjusted record length to include 1 byte <strong>for</strong> the printercontrol character.ARITHARITH affects the maximum number of digits that you can code <strong>for</strong> integers, andthe number of digits used in fixed-point intermediate results.ARITH option syntax►►COMPATARITH( EXTEND ) ►◄Default is: ARITH(COMPAT)Abbreviations are: AR(C), AR(E)When you specify ARITH(EXTEND):v The maximum number of digit positions that you can specify in the PICTUREclause <strong>for</strong> packed-decimal, external-decimal, and numeric-edited data items israised from 18 to 31.v The maximum number of digits that you can specify in a fixed-point numericliteral is raised from 18 to 31. You can use numeric literals with large precisionanywhere that numeric literals are currently allowed, including:– Operands of PROCEDURE DIVISION statements– VALUE clauses (<strong>for</strong> numeric data items with large-precision PICTURE)– Condition-name values (on numeric data items with large-precision PICTURE)v The maximum number of digits that you can specify in the arguments to NUMVALand NUMVAL-C is raised from 18 to 31.v The maximum value of the integer argument to the FACTORIAL function is 29.v Intermediate results in arithmetic statements use extended mode.When you specify ARITH(COMPAT):v The maximum number of digit positions in the PICTURE clause <strong>for</strong>packed-decimal, external-decimal, and numeric-edited data items is 18.v The maximum number of digits in a fixed-point numeric literal is 18.306 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


v The maximum number of digits in the arguments to NUMVAL and NUMVAL-C is 18.v The maximum value of the integer argument to the FACTORIAL function is 28.v Intermediate results in arithmetic statements use compatibility mode.RELATED CONCEPTSAppendix A, “Intermediate results and arithmetic precision,” on page 687AWO|If you specify AWO, an implicit APPLY WRITE-ONLY clause is activated <strong>for</strong> all QSAMfiles in the program that have blocked variable-length records.AWO option syntax►►NOAWOAWO►◄Default is: NOAWOAbbreviations are: NoneRELATED TASKS“Optimizing buffer and device space” on page 12RELATED REFERENCES“BLOCK0”APPLY WRITE-ONLY clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)|BLOCK0|||Use BLOCK0 to change the compiler default <strong>for</strong> QSAM files from unblocked toblocked (as if BLOCK CONTAINS 0 were specified) and thus gain the benefit ofsystem-determined blocking <strong>for</strong> output files.||BLOCK0 option syntax|||►►NOBLOCK0BLOCK0►◄||Default is: NOBLOCK0Abbreviations are: NoneChapter 17. Compiler options 307


||||||||||||||||||||||||||||||||||||||||Specifying BLOCK0 activates an implicit BLOCK CONTAINS 0 clause <strong>for</strong> each file in theprogram that meets the following three criteria:v The FILE-CONTROL paragraph either specifies ORGANIZATION SEQUENTIAL or omitsthe ORGANIZATION clause.v The FD entry does not specify RECORDING MODE U.v The FD entry does not specify a BLOCK CONTAINS clause.Files <strong>for</strong> which the resulting BLOCK CONTAINS 0 clause is in effect have a blockingfactor that is determined at run time from the data definition or from the data-setcharacteristics.Interaction of the APPLY WRITE-ONLY clause and the AWO compiler option withBLOCK0:vvIf NOBLOCK0 is in effect, and the file description of a file that meets the threecriteria listed above specifies APPLY WRITE-ONLY, the compiler issues an errormessage because APPLY WRITE-ONLY applies only to blocked files. But if BLOCK0 isin effect, the result is that the file is blocked, and the APPLY WRITE-ONLY clause isthere<strong>for</strong>e accepted.AWO applies to any QSAM files that have blocked variable-length records. IfBLOCK0 is in effect, the result is that more files might be blocked than if NOBLOCK0were in effect; thus AWO might apply to more files than it otherwise would.Specifying BLOCK0 <strong>for</strong> existing programs might result in a change of behavior, andin some cases produce undesirable results <strong>for</strong> files opened as INPUT. For example:vvThe OPEN INPUT statement fails <strong>for</strong> files <strong>for</strong> which no block size can bedetermined.Programs that continue after handling nonzero FILE STATUS codes <strong>for</strong> filesopened as INPUT might abnormally terminate when executing subsequent I/Ostatements on those files.For these reasons, after compiling with BLOCK0 you should investigate and test theeffects on your program.For recommendations about blocking, see the related reference from the <strong>Enterprise</strong><strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong> (in the in<strong>for</strong>mation about migratingfrom CMPR2 to NOCMPR2).RELATED TASKS“Optimizing buffer and device space” on page 12“Setting block sizes” on page 159RELATED REFERENCES“AWO” on page 307APPLY WRITE-ONLY clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)BLOCK CONTAINS clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Recommendation <strong>for</strong> DCB= parameters of JCL(<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong>)308 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|BUFSIZEUse BUFSIZE to allocate an amount of main storage to the buffer <strong>for</strong> each compilerwork data set. Usually, a large buffer size improves the per<strong>for</strong>mance of thecompiler.BUFSIZE option syntax►►nnnnnBUFSIZE( nnnK ) ►◄Default is: 4096Abbreviations are: BUFnnnnn specifies a decimal number that must be at least 256.nnnK specifies a decimal number in 1-KB increments, where 1 KB = 1024 bytes.If you use both BUFSIZE and SIZE, the amount allocated to buffers is included inthe amount of main storage available <strong>for</strong> compilation via the SIZE option.BUFSIZE cannot exceed the track capacity <strong>for</strong> the device used, nor can it exceed themaximum allowed by data management services.CICSThe CICS compiler option enables the integrated CICS translator and lets youspecify CICS suboptions. You must use the CICS option if your <strong>COBOL</strong> sourceprogram contains EXEC CICS or EXEC DLI statements and the program has not beenprocessed by the separate CICS translator.CICS option syntax►►NOCICSCICS(″CICS-suboption-string″)►◄Default is: NOCICSAbbreviations are: NoneUse the CICS option only to compile CICS programs. Programs compiled with theCICS option will not run in a non-CICS environment.Chapter 17. Compiler options 309


If you specify the NOCICS option, any CICS statements found in the source programare diagnosed and discarded.Use either quotation marks or single quotation marks to delimit the string of CICSsuboptions.You can partition a long CICS suboption string into multiple suboption strings inmultiple CBL or PROCESS statements. The CICS suboptions are concatenated in theorder of their appearance. For example://STEP1 EXEC IGYWC, ...// PARM.<strong>COBOL</strong>='CICS("string1")'//<strong>COBOL</strong>.SYSIN DD *CBL CICS('string2')CBL CICS("string3")IDENTIFICATION DIVISION.PROGRAM-ID. DRIVER1....The compiler passes the following suboption string to the integrated CICStranslator:"string1 string2 string3"The concatenated strings are delimited with single spaces as shown. If multipleinstances of the same CICS suboption are found, the last specification of thatsuboption in the concatenated string prevails. The compiler limits the size of theconcatenated suboption string to 4 KB.RELATED CONCEPTS“Integrated CICS translator” on page 413RELATED TASKS“Compiling with the CICS option” on page 411“Separating CICS suboptions” on page 413CICS Application <strong>Programming</strong> <strong>Guide</strong> (Specifying CICS translator options)RELATED REFERENCES“Conflicting compiler options” on page 304CODEPAGEUse CODEPAGE to specify the coded character set identifier (CCSID) <strong>for</strong> an EBCDICcode page <strong>for</strong> processing compile-time and runtime <strong>COBOL</strong> operations that aresensitive to character encoding.CODEPAGE option syntax►► CODEPAGE(ccsid) ►◄Default is: CODEPAGE(1140)Abbreviations are: CP(ccsid)310 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


ccsid must be an integer that represents a valid CCSID <strong>for</strong> an EBCDIC code page.The default CCSID 1140 is the equivalent of CCSID 37 (EBCDIC Latin-1, USA), butadditionally includes the euro symbol.ccsid specifies these encodings:v The encoding <strong>for</strong> alphanumeric, national, and DBCS literals in a <strong>COBOL</strong> sourceprogramv The default encoding of the content of alphanumeric and DBCS data items atrun timev The encoding <strong>for</strong> DBCS user-defined words when processed by an XML GENERATEstatement to create XML element and attribute namesv The default encoding of an XML document created by an XML GENERATEstatement if the receiving data item <strong>for</strong> the document is alphanumericv The default encoding assumed <strong>for</strong> an XML document in an alphanumeric dataitem when the document is processed by an XML PARSE statementThe CODEPAGE ccsid is used when code-page-sensitive operations are per<strong>for</strong>med atcompile time or run time, and an explicit CCSID that overrides the default codepage is not specified. Such operations include:v Conversion of literal values to UnicodevvvvvvvConversion of alphanumeric data to and from national (Unicode) data as part ofmove operations, comparison, or the intrinsic functions DISPLAY-OF andNATIONAL-OFObject-oriented language such as INVOKE statements or class definitions andmethod definitionsXML parsingXML generationProcessing of DBCS names as part of XML generation at run timeProcessing of SQL string host variables if the SQLCCSID option is in effectProcessing of source code <strong>for</strong> EXEC SQL statementsHowever, the encoding of the following items in a <strong>COBOL</strong> source program is notaffected by the CODEPAGE compiler option:v Data items that have USAGE NATIONALThese items are always encoded in UTF-16 in big-endian <strong>for</strong>mat, CCSID 1200.vCharacters from the basic <strong>COBOL</strong> character set (see the table of these charactersin the related reference below about characters)Though the encoding of the basic <strong>COBOL</strong> characters default currency sign ($),quotation mark (″), and the lowercase Latin letters varies in different EBCDICcode pages, the compiler always interprets these characters using the EBCDICcode page 1140 encoding. In particular, the default currency sign is always thecharacter with value X'5B' (unless changed by the CURRENCY compiler option orthe CURRENCY SIGN clause in the SPECIAL-NAMES paragraph), and the quotationmark is always the character with value X'7F'.Some <strong>COBOL</strong> operations can override the CODEPAGE ccsid by using an explicitencoding specification, <strong>for</strong> example:vvDISPLAY-OF and NATIONAL-OF intrinsic functions that specify a code page as thesecond argumentXML PARSE statements that specify the WITH ENCODING phraseChapter 17. Compiler options 311


vXML GENERATE statements that specify the WITH ENCODING phraseAdditionally, you can use the CURRENCY compiler option or the CURRENCY SIGNclause in the SPECIAL-NAMES paragraph to override:vvThe default currency symbol used in the PICTURE character-strings <strong>for</strong>numeric-edited data items in your source programThe currency sign value used in the content of numeric-edited data items at runtimeDBCS code pages:Compile your <strong>COBOL</strong> program using the CODEPAGE option with the ccsid set to oneof the EBCDIC multibyte character set (MBCS) CCSIDs shown in the table below ifthe program contains any of the following items:v User-defined words <strong>for</strong>med with DBCS charactersv DBCS (USAGE DISPLAY-1) data itemsv DBCS literalsAll of the CCSIDs in the table below identify mixed code pages that refer to acombination of SBCS and DBCS coded character sets. These are also the CCSIDsthat are supported <strong>for</strong> mixed data by DB2.Table 47. EBCDIC multibyte coded character set identifiersNational languageMBCS CCSIDSBCS CCSIDcomponentDBCS CCSIDcomponentJapanese (Katakana-Kanji) 930 290 300Japanese (Katakana-Kanji with euro) 1390 8482 16684Japanese (Katakana-Kanji) 5026 290 4396Japanese (Latin-Kanji) 939 1027 300Japanese (Latin-Kanji with euro) 1399 5123 16684Japanese (Latin-Kanji) 5035 1027 4396Korean 933 833 834Korean 1364 13121 4930Simplified Chinese 935 836 837Simplified Chinese 1388 13124 4933Traditional Chinese 937 28709 835RELATED CONCEPTS“<strong>COBOL</strong> and DB2 CCSID determination” on page 425RELATED TASKS“Using currency signs” on page 67Chapter 28, “Processing XML input,” on page 503Chapter 29, “Producing XML output,” on page 543RELATED REFERENCES“CURRENCY” on page 313“SQLCCSID” on page 347“The encoding of XML documents” on page 520Characters (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)312 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


COMPILEUse the COMPILE option only if you want to <strong>for</strong>ce full compilation even in thepresence of serious errors. All diagnostics and object code will be generated. Donot try to run the object code if the compilation resulted in serious errors: theresults could be unpredictable or an abnormal termination could occur.COMPILE option syntax►►SNOCOMPILE( E )WCOMPILENOCOMPILE►◄Default is: NOCOMPILE(S)Abbreviations are: C|NOCUse NOCOMPILE without any suboption to request a syntax check (only diagnosticsproduced, no object code). If you use NOCOMPILE without any suboption, severalcompiler options will have no effect because no object code will be produced, <strong>for</strong>example: DECK, LIST, OBJECT, OFFSET, OPTIMIZE, SSRANGE, and TEST.Use NOCOMPILE with suboption W, E, orS <strong>for</strong> conditional full compilation. Fullcompilation (diagnosis and object code) will stop when the compiler finds an errorof the level you specify (or higher), and only syntax checking will continue.RELATED TASKS“Finding coding errors” on page 372RELATED REFERENCES“Messages and listings <strong>for</strong> compiler-detected errors” on page 280CURRENCYYou can use the CURRENCY option to provide an alternate default currency symbolto be used <strong>for</strong> a <strong>COBOL</strong> program. (The default currency symbol is the dollar sign($).)CURRENCY option syntax►►NOCURRENCYCURRENCY(literal)►◄Chapter 17. Compiler options 313


Default is: NOCURRENCYAbbreviations are: CURR|NOCURRNOCURRENCY specifies that no alternate default currency symbol will be used.|To change the default currency symbol, specify CURRENCY(literal), where literal is avalid <strong>COBOL</strong> alphanumeric literal (optionally a hexadecimal literal) that representsa single character. The literal must not be from the following list:v Digits zero (0) through nine (9)v Uppercase alphabetic characters A BCDEGNPRSVXZortheir lowercaseequivalentsv The spacev Special characters *+-/,.;()″ =v A figurative constantv A null-terminated literalv A DBCS literalv A national literalIf your program processes only one currency type, you can use the CURRENCYoption as an alternative to the CURRENCY SIGN clause <strong>for</strong> indicating the currencysymbol you will use in the PICTURE clause of your program. If your programprocesses more than one currency type, you should use the CURRENCY SIGN clausewith the WITH PICTURE SYMBOL phrase to specify the different currency sign types.If you use both the CURRENCY option and the CURRENCY SIGN clause in a program,the CURRENCY option is ignored. Currency symbols specified in the CURRENCY SIGNclause or clauses can be used in PICTURE clauses.When the NOCURRENCY option is in effect and you omit the CURRENCY SIGN clause,the dollar sign ($) is used as the PICTURE symbol <strong>for</strong> the currency sign.Delimiter: You can delimit the CURRENCY option literal with either quotation marksor single quotation marks, regardless of the QUOTE|AP<strong>OS</strong>T compiler option setting.RELATED TASKS“Using currency signs” on page 67DATAThe DATA option affects whether storage <strong>for</strong> dynamic data areas and other dynamicruntime storage is obtained from above or below the 16-MB line.DATA option syntax►►31DATA( 24 ) ►◄Default is: DATA(31)314 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Abbreviations are: NoneFor reentrant programs, the DATA compiler option and the HEAP runtime optioncontrol whether storage <strong>for</strong> dynamic data areas (such as WORKING-STORAGE and FDrecord areas) is obtained from below the 16-MB line (DATA(24)) orfromunrestricted storage (DATA(31)). (DATA does not affect the location of LOCAL-STORAGEdata; the STACK runtime option controls that location instead, along with the AMODEof the program.)When you specify the runtime option HEAP(,,BELOW), the DATA compiler option hasno effect; the storage <strong>for</strong> all dynamic data areas is allocated from below the 16-MBline. However, if HEAP(,,ANYWHERE) is in effect, storage <strong>for</strong> dynamic data areas isallocated from below the line if you compiled the program with DATA(24) or fromunrestricted storage if you compiled with DATA(31).Specify DATA(24) <strong>for</strong> programs that run in 31-bit addressing mode and that passdata arguments to programs in 24-bit addressing mode. Doing so ensures that thedata will be addressable by the called program.External data and QSAM buffers: The DATA option interacts with other compileroptions and runtime options that affect storage and its addressability. See therelated in<strong>for</strong>mation <strong>for</strong> details.RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKSLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (Using runtime options)RELATED REFERENCES“Allocation of buffers <strong>for</strong> QSAM files” on page 173DATEPROCUse the DATEPROC option to enable the millennium language extensions of the<strong>COBOL</strong> compiler.DATEPROC option syntax►►NODATEPROCDATEPROCFLAG ,NOTRIG( )NOFLAG ,TRIG►◄Default is: NODATEPROC, orDATEPROC(FLAG,NOTRIG) if only DATEPROC is specifiedAbbreviations are: DP|NODPDATEPROC(FLAG)With DATEPROC(FLAG), the millennium language extensions are enabled, andChapter 17. Compiler options 315


the compiler produces a diagnostic message wherever a language elementuses or is affected by the extensions. The message is usually anin<strong>for</strong>mation-level or warning-level message that identifies statements thatinvolve date-sensitive processing. Additional messages that identify errorsor possible inconsistencies in the date constructs might be generated.Production of diagnostic messages, and their appearance in or after thesource listing, is subject to the setting of the FLAG compiler option.DATEPROC(NOFLAG)With DATEPROC(NOFLAG), the millennium language extensions are in effect,but the compiler does not produce any related messages unless there areerrors or inconsistencies in the <strong>COBOL</strong> source.DATEPROC(TRIG)With DATEPROC(TRIG), the millennium language extensions are enabled, andthe automatic windowing that the compiler applies to operations onwindowed date fields is sensitive to specific trigger or limit values in thedate fields and in other nondate fields that are stored into or comparedwith the windowed date fields. These special values represent invalid datesthat can be tested <strong>for</strong> or used as upper or lower limits.Per<strong>for</strong>mance considerations: The DATEPROC(TRIG) option results inslower-per<strong>for</strong>ming code <strong>for</strong> windowed date comparisons.DATEPROC(NOTRIG)With DATEPROC(NOTRIG), the millennium language extensions are enabled,and the automatic windowing that the compiler applies to operations onwindowed dates does not recognize any special trigger values in theoperands. Only the value of the year part of dates is relevant to automaticwindowing.Per<strong>for</strong>mance considerations: The DATEPROC(NOTRIG) option is aper<strong>for</strong>mance option that assumes valid date values in windowed datefields.NODATEPROCNODATEPROC indicates that the extensions are not enabled <strong>for</strong> thiscompilation unit. This option affects date-related program constructs asfollows:vvvThe DATE FORMAT clause is syntax-checked, but has no effect on theexecution of the program.The DATEVAL and UNDATE intrinsic functions have no effect. That is, thevalue returned by the intrinsic function is exactly the same as the valueof the argument.The YEARWINDOW intrinsic function returns a value of zero.Usage note: You can specify the FLAG|NOFLAG and TRIG|NOTRIG suboptions in anyorder. If you omit either suboption, it defaults to the current setting. If you code aleft parenthesis after DATEPROC, however, you must code at least one suboption.RELATED REFERENCES“FLAG” on page 322“YEARWINDOW” on page 360316 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


DBCSUsing DBCS causes the compiler to recognize X'0E' (SO) and X'0F' (SI) as shiftcodes <strong>for</strong> the double-byte portion of an alphanumeric literal.DBCS option syntax►►DBCSNODBCS►◄Default is: DBCSAbbreviations are: NoneWith DBCS in effect, the double-byte portion of the literal is syntax-checked and theliteral remains category alphanumeric.RELATED REFERENCES“Conflicting compiler options” on page 304DECKUse DECK to produce object code in the <strong>for</strong>m of 80-column records. If you use theDECK option, be certain that SYSPUNCH is defined in your JCL <strong>for</strong> compilation.DECK option syntax►►NODECKDECK►◄Default is: NODECKAbbreviations are: D|NODRELATED TASKS“Creating object code (SYSLIN or SYSPUNCH)” on page 269Chapter 17. Compiler options 317


DIAGTRUNCDIAGTRUNC causes the compiler to issue a severity-4 (Warning) diagnostic message<strong>for</strong> MOVE statements with numeric receivers when the receiving data item has fewerinteger positions than the sending data item or literal. In statements with multiplereceivers, the message is issued separately <strong>for</strong> each receiver that could betruncated.DIAGTRUNC option syntax►►NODIAGTRUNCDIAGTRUNC►◄Default is: NODIAGTRUNCAbbreviations are: DTR, NODTRThe diagnostic message is also issued <strong>for</strong> implicit moves associated withstatements such as these:v INITIALIZEv READ...INTOv RELEASE ...FROMv RETURN ...INTOv REWRITE ...FROMv WRITE ...FROMThe diagnostic is also issued <strong>for</strong> moves to numeric receivers from alphanumericdata-names or literal senders, except when the sending field is reference modified.There is no diagnostic <strong>for</strong> COMP-5 receivers, nor <strong>for</strong> binary receivers when youspecify the TRUNC(BIN) option.RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49“Reference modifiers” on page 109RELATED REFERENCES“TRUNC” on page 353DLLUse DLL to instruct the compiler to generate an object module that is enabled <strong>for</strong>dynamic link library (DLL) support. DLL enablement is required if the programwill be part of a DLL, will reference DLLs, or if the program containsobject-oriented <strong>COBOL</strong> syntax such as INVOKE statements or class definitions.318 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


DLL option syntax►►NODLLDLL►◄Default is: NODLLAbbreviations are: NoneLink-edit considerations: <strong>COBOL</strong> programs that are compiled with the DLL optionmust be link-edited with the RENT and AMODE(31) link-edit options.NODLL instructs the compiler to generate an object module that is not enabled <strong>for</strong>DLL usage.RELATED TASKS“Making dynamic calls” on page 451RELATED REFERENCES“Conflicting compiler options” on page 304DUMPUse DUMP to produce a system dump at compile time <strong>for</strong> an internal compiler error.DUMP option syntax►►NODUMPDUMP►◄Default is: NODUMPAbbreviations are: DU|NODUNot <strong>for</strong> general use: The DUMP option should be used only at the request of an IBMrepresentative.The dump, which consists of a listing of the compiler’s registers and a storagedump, is intended primarily <strong>for</strong> diagnostic personnel <strong>for</strong> determining errors in thecompiler.If you use the DUMP option, include a DD statement at compile time to defineSYSABEND, SYSUDUMP, orSYSMDUMP.With DUMP, the compiler will not issue a diagnostic message be<strong>for</strong>e abnormaltermination processing. Instead, a user abend will be issued with an IGYppnnnnChapter 17. Compiler options 319


message. In general, a message IGYppnnnn corresponds to a compile-time userabend nnnn. However, both IGYpp5nnn and IGYpp1nnn messages produce a userabend of 1nnn. You can usually distinguish whether the message is really a 5nnn ora1nnn by recompiling with the NODUMP option.Use NODUMP if you want normal termination processing, including:v Diagnostic messages produced so far in compilation.v A description of the error.v The name of the compiler phase currently executing.v The line number of the <strong>COBOL</strong> statement being processed when the error wasfound. (If you compiled with OPTIMIZE, the line number might not always becorrect; <strong>for</strong> some errors, it will be the last line in the program.)v The contents of the general purpose registers.Using the DUMP and OPTIMIZE compiler options together could cause the compiler toproduce a system dump instead of the following optimizer message:"IGYOP3124-W This statement may cause a program exception atexecution time."This situation does not represent a compiler error. Using the NODUMP option willallow the compiler to issue message IGYOP3124-W and continue processing.RELATED TASKSLanguage Environment Debugging <strong>Guide</strong> (Understanding abend codes)RELATED REFERENCES“Conflicting compiler options” on page 304DYNAMUse DYNAM to cause nonnested, separately compiled programs invoked through theCALL literal statement to be loaded <strong>for</strong> CALL, and deleted <strong>for</strong> CANCEL, dynamically atrun time. (CALL identifier statements always result in a runtime load of the targetprogram and are not affected by this option.)DYNAM option syntax►►NODYNAMDYNAM►◄Default is: NODYNAMAbbreviations are: DYN|NODYNRestriction: The DYNAM compiler option must not be used in the following cases:v <strong>COBOL</strong> programs that are processed by the CICS translator or the CICS compileroption320 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


v<strong>COBOL</strong> programs that have EXEC SQL statements and are run under CICS orDB2 call attach facility (CAF)If your <strong>COBOL</strong> program calls programs that have been linked as dynamic linklibraries (DLLs), you must not use the DYNAM option. You must instead compile theprogram with the NODYNAM and DLL options.RELATED TASKS“Making both static and dynamic calls” on page 455“Choosing the DYNAM or NODYNAM compiler option” on page 429RELATED REFERENCES“Conflicting compiler options” on page 304EXITFor in<strong>for</strong>mation about the EXIT compiler option, see the first related referencebelow.RELATED REFERENCESAppendix E, “EXIT compiler option,” on page 719“Conflicting compiler options” on page 304EXPORTALLUse EXPORTALL to instruct the compiler to automatically export the PROGRAM-IDname and each alternate entry-point name from each program definition when theobject deck is link-edited to <strong>for</strong>m a DLL.EXPORTALL option syntax►►NOEXPORTALLEXPORTALL►◄Default is: NOEXPORTALLAbbreviations are: EXP|NOEXPWith these symbols exported from the DLL, the exported program and entry-pointnames can be called from programs in the root load module or in other DLL loadmodules in the application, as well as from programs that are linked into the sameDLL.Specification of the EXPORTALL option requires that the RENT linker option also beused.NOEXPORTALL instructs the compiler to not export any symbols. In this case theprograms are accessible only from other routines that are link-edited into the sameload module together with this <strong>COBOL</strong> program definition.Chapter 17. Compiler options 321


RELATED REFERENCES“Conflicting compiler options” on page 304FASTSRTUse FASTSRT to let IBM DFSORT, or an equivalent product, per<strong>for</strong>m sort input andoutput instead of <strong>Enterprise</strong> <strong>COBOL</strong>.FASTSRT option syntax►►NOFASTSRTFASTSRT►◄Default is: NOFASTSRTAbbreviations are: FSRT|NOFSRTRELATED TASKS“Improving sort per<strong>for</strong>mance with FASTSRT” on page 225FLAGUse FLAG(x) to produce diagnostic messages at the end of the source listing <strong>for</strong>errors of a severity level x or above.FLAG option syntax►►FLAG(x ),yNOFLAG►◄Default is: FLAG(I,I)Abbreviations are: F|NOFx and y can be either I, W, E, S, orU.Use FLAG(x,y) to produce diagnostic messages <strong>for</strong> errors of severity level x orabove at the end of the source listing, with error messages of severity y and aboveto be embedded directly in the source listing. The severity coded <strong>for</strong> y must not belower than the severity coded <strong>for</strong> x. TouseFLAG(x,y), you must also specify theSOURCE compiler option.322 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Error messages in the source listing are set off by the embedding of the statementnumber in an arrow that points to the message code. The message code is followedby the message text. For example:000413 MOVE CORR WS-DATE TO HEADER-DATE==000413==> IGYPS2121-S " WS-DATE " was not defined as a data-name. . . .When FLAG(x,y) is in effect, messages of severity y and above are embedded in thelisting after the line that caused the message. (See the related reference below <strong>for</strong>in<strong>for</strong>mation about messages <strong>for</strong> exceptions.)Use NOFLAG to suppress error flagging. NOFLAG does not suppress error messages <strong>for</strong>compiler options.Embedded messagesv Embedding level-U messages is not recommended. The specification ofembedded level-U messages is accepted, but does not produce any messages inthe source.v The FLAG option does not affect diagnostic messages that are produced be<strong>for</strong>ethe compiler options are processed.v Diagnostic messages that are produced during processing of compiler options,CBL or PROCESS statements, or BASIS, COPY, orREPLACE statements are notembedded in the source listing. All such messages appear at the beginning ofthe compiler output.v Messages that are produced during processing of the *CONTROL or *CBL statementare not embedded in the source listing.RELATED REFERENCES“Messages and listings <strong>for</strong> compiler-detected errors” on page 280FLAGSTDUse FLAGSTD to specify the level or subset of Standard <strong>COBOL</strong> 85 to be regarded ascon<strong>for</strong>ming, and to get in<strong>for</strong>mational messages about Standard <strong>COBOL</strong> 85elements that are included in your program.You can specify any of the following items <strong>for</strong> flagging:v A selected Federal In<strong>for</strong>mation Processing Standard (FIPS) <strong>COBOL</strong> subsetv Any of the optional modulesv Obsolete language elementsv Any combination of subset and optional modulesv Any combination of subset and obsolete elementsv IBM extensions (these are flagged any time that FLAGSTD is specified, andidentified as ″noncon<strong>for</strong>ming nonstandard″)Chapter 17. Compiler options 323


FLAGSTD option syntax►►NOFLAGSTDFLAGSTD(x )yy ,O►◄Default is: NOFLAGSTDAbbreviations are: Nonex specifies the subset of Standard <strong>COBOL</strong> 85 to be regarded as con<strong>for</strong>ming:MIHLanguage elements that are not from the minimum subset are to beflagged as ″noncon<strong>for</strong>ming standard.″Language elements that are not from the minimum or the intermediatesubset are to be flagged as ″noncon<strong>for</strong>ming standard.″The high subset is being used and elements will not be flagged by subset.Elements that are IBM extensions will be flagged as ″noncon<strong>for</strong>mingStandard, IBM extension.″yy specifies, by a single character or combination of any two, the optional modulesto be included in the subset:DNSElements from debug module level 1 are not flagged as ″noncon<strong>for</strong>mingstandard.″Elements from segmentation module level 1 are not flagged as″noncon<strong>for</strong>ming standard.″Elements from segmentation module level 2 are not flagged as″noncon<strong>for</strong>ming standard.″If S is specified, N is included (N is a subset of S).O (the letter) specifies that obsolete language elements are flagged as ″obsolete.″The in<strong>for</strong>mational messages appear in the source program listing, and identify:v The element as ″obsolete,″ ″noncon<strong>for</strong>ming standard,″ or ″noncon<strong>for</strong>mingnonstandard″ (a language element that is both obsolete and noncon<strong>for</strong>ming isflagged as obsolete only)v The clause, statement, or header that contains the elementv The source program line and beginning location of the clause, statement, orheader that contains the elementv The subset or optional module to which the element belongsFLAGSTD requires the standard set of reserved words.In the following example, the line number and column where a flagged clause,statement, or header occurred are shown with the associated message code andtext. After that is a summary of the total number of flagged items and their type.324 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


LINE.COL CODEIGYDS8211FIPS MESSAGE TEXTComment lines be<strong>for</strong>e "IDENTIFICATION DIVISION":noncon<strong>for</strong>ming nonstandard, IBM extension toANS/ISO 1985.11.14 IGYDS8111 "GLOBAL clause": noncon<strong>for</strong>ming standard, ANS/ISO1985 high subset.59.12 IGYPS8169 "USE FOR DEBUGGING statement": obsolete elementin ANS/ISO 1985.FIPS MESSAGES TOTAL STANDARD NONSTANDARD OBSOLETE3 1 1 1||||You can convert FIPS in<strong>for</strong>mational messages into diagnostic messages, and cansuppress FIPS messages, by using the MSGEXIT suboption of the EXIT compileroption. For details, see the related reference about the processing of MSGEXIT, andsee the related task.RELATED TASKS“Customizing compiler-message severities” on page 730RELATED REFERENCES“Conflicting compiler options” on page 304“Processing of MSGEXIT” on page 729INTDATEINTDATE(ANSI) instructs the compiler to use the Standard <strong>COBOL</strong> 85 starting date<strong>for</strong> integer dates used with date intrinsic functions. Day 1 is Jan 1, 1601.INTDATE(LILIAN) instructs the compiler to use the Language Environment Lilianstarting date <strong>for</strong> integer dates used with date intrinsic functions. Day 1 is Oct 15,1582.INTDATE option syntax►►ANSIINTDATE( LILIAN ) ►◄Default is: INTDATE(ANSI)Abbreviations are: NoneWith INTDATE(LILIAN), the date intrinsic functions return results that arecompatible with the Language Environment date callable services.Usage note: When INTDATE(LILIAN) is in effect, CEECBLDY is not usable becauseyou have no way to turn an ANSI integer into a meaningful date by using eitherintrinsic functions or callable services. If you code a CALL literal statement withChapter 17. Compiler options 325


CEECBLDY as the target of the call when INTDATE(LILIAN) in effect, the compilerdiagnoses this and converts the call target to CEEDAYS.RELATED TASKS“Using date callable services” on page 62LANGUAGEUse the LANGUAGE option to select the language in which compiler output will beprinted. The in<strong>for</strong>mation that will be printed in the selected language includesdiagnostic messages, source listing page and scale headers, FIPS message headers,message summary headers, compilation summary, and headers and notations thatresult from the selection of certain compiler options (MAP, XREF, VBREF, andFLAGSTD).LANGUAGE option syntax►► LANGUAGE(name) ►◄Default is: LANGUAGE(ENGLISH)Abbreviations are: LANG(EN|UE|JA|JP)name specifies the language <strong>for</strong> compiler output messages. Possible values <strong>for</strong> theLANGUAGE option are shown in the table below.Table 48. Values of the LANGUAGE compiler optionName Abbreviation 1 Output languageENGLISH EN Mixed-case English (the default)JAPANESE JA, JP Japanese, using the Japanese character setUENGLISH 2 UE Uppercase English1. If your installation’s system programmer has provided a language other than thosedescribed, you must specify at least the first two characters of this other language’sname.2. To specify a language other than UENGLISH, the appropriate language feature must beinstalled.If the LANGUAGE option is changed at compile time (using CBL or PROCESSstatements), some initial text will be printed using the language that was in effectat the time the compiler was started.NATLANG: The NATLANG runtime option allows you to control the national languageto be used <strong>for</strong> the runtime environment, including error messages, month names,and day-of-the-week names. The LANGUAGE compiler option and the NATLANGruntime option act independently of each other. You can use them together withneither taking precedence over the other.326 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


LIBIf your program uses COPY, BASIS, orREPLACE statements, the LIB compiler optionmust be in effect.LIB option syntax►►NOLIBLIB►◄Default is: NOLIBAbbreviations are: NoneFor COPY and BASIS statements, you need additionally to define the library orlibraries from which the compiler can take the copied code. Define the libraries byusing DD statements, ALLOCATE commands, or environment variables, as appropriate<strong>for</strong> your environment. When using JCL, also include a DD statement to allocateSYSUT5.RELATED REFERENCESChapter 18, “Compiler-directing statements,” on page 363“Conflicting compiler options” on page 304LINECOUNTUse LINECOUNT(nnn) to specify the number of lines to be printed on each page ofthe compilation listing, or use LINECOUNT(0) to suppress pagination.LINECOUNT option syntax►► LINECOUNT(nnn) ►◄Default is: LINECOUNT(60)Abbreviations are: LCnnn must be an integer between 10 and 255, or 0.If you specify LINECOUNT(0), no page ejects are generated in the compilation listing.The compiler uses three lines of nnn <strong>for</strong> titles. For example, if you specifyLINECOUNT(60), 57 lines of source code are printed on each page of the outputlisting.Chapter 17. Compiler options 327


LISTUse the LIST compiler option to produce a listing of the assembler-languageexpansion of your source code.LIST option syntax►►NOLISTLIST►◄Default is: NOLISTAbbreviations are: NoneThese items will also be written to the output listing:v Global tablesv Literal poolsv In<strong>for</strong>mation about WORKING-STORAGE and LOCAL-STORAGEv Size of the program’s WORKING-STORAGE and LOCAL-STORAGE and their location inthe object code if the program is compiled with the NORENT optionThe output is generated if:v You specify the COMPILE option, or the NOCOMPILE(x) option is in effect and anerror of level x or higher does not occur.v You do not specify the OFFSET option.If you want to limit the assembler listing output, use *CONTROL (or *CBL) LIST orNOLIST statements in the PROCEDURE DIVISION. Source statements that follow a*CONTROL NOLIST statement are not included in the listing until a subsequent*CONTROL LIST statement switches the output back to normal LIST <strong>for</strong>mat.RELATED TASKS“Getting listings” on page 377RELATED REFERENCES“Conflicting compiler options” on page 304*CONTROL (*CBL) statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MAPUse MAP to produce a listing of the items defined in the DATA DIVISION.328 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


MAP option syntax►►NOMAPMAP►◄Default is: NOMAPAbbreviations are: NoneThe output includes the following items:v DATA DIVISION mapv Global tablesv Literal poolsv Nested program structure map, and program attributesv Size of the program’s WORKING-STORAGE and LOCAL-STORAGE and its location in theobject code if the program is compiled with the NORENT optionIf you want to limit the MAP output, use *CONTROL MAP or NOMAP statements in theDATA DIVISION. Source statements that follow *CONTROL NOMAP are not included inthe listing until a *CONTROL MAP statement switches the output back to normal MAP<strong>for</strong>mat. For example:*CONTROL NOMAP*CBL NOMAP01 A 01 A02 B 02 B*CONTROL MAP*CBL MAPBy selecting the MAP option, you can also print an embedded MAP report in thesource code listing. The condensed MAP in<strong>for</strong>mation is printed to the right ofdata-name definitions in the FILE SECTION, LOCAL-STORAGE SECTION, and LINKAGESECTION of the DATA DIVISION. When both XREF data and an embedded MAPsummary are on the same line, the embedded summary is printed first.“Example: MAP output” on page 382RELATED CONCEPTSChapter 19, “Debugging,” on page 367RELATED TASKS“Getting listings” on page 377RELATED REFERENCES*CONTROL (*CBL) statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MDECK|The MDECK compiler option specifies that output from library processing (that is, theresult of COPY, BASIS, REPLACE, and EXEC SQL INCLUDE statements) is written to afile.When <strong>Enterprise</strong> <strong>COBOL</strong> is running under z/<strong>OS</strong> UNIX, the MDECK output is writtenin the current directory to a file that has the same name as the <strong>COBOL</strong> source fileChapter 17. Compiler options 329


and a suffix of .dek. For <strong>Enterprise</strong> <strong>COBOL</strong> running under TSO or batch, the MDECKoutput is written to the data set defined by the SYSMDECK DD statement, which mustspecify an MVS data set that has RECFM F or FB and an LRECL of 80 bytes.MDECK option syntax►►NOMDECKMDECKCOMPILE( NOCOMPILE )►◄Default is: NOMDECKAbbreviations are: NOMD, MD, MD(C), MD(NOC)Option specification:You cannot specify the MDECK option in a PROCESS (or CBL) statement. You canspecify it only in one of the following ways:v In the PARM parameter of JCLv As a cob2 command optionv As an installation defaultv In the COBOPT environment variableSuboptions:v When MDECK(COMPILE) is in effect, compilation continues normally after libraryprocessing and generation of the MDECK output file have completed, subject to thesettings of the COMPILE|NOCOMPILE, DECK|NODECK, and OBJECT|NOOBJECT compileroptions.v When MDECK(NOCOMPILE) is in effect, compilation is terminated after libraryprocessing has completed and the expanded source program file has beenwritten. The compiler does no further syntax checking or code generationregardless of the settings of the COMPILE, DECK, and OBJECT compiler options.When you specify MDECK with no suboption, MDECK(COMPILE) is implied.Contents of the MDECK output file:When you use the MDECK option with the CICS compiler option (integrated CICStranslator) or the SQL compiler option (DB2 coprocessor), in general, EXEC CICS andEXEC SQL statements in the <strong>COBOL</strong> source program are included in the MDECKoutput as is. However, EXEC SQL INCLUDE statements are expanded in the MDECKoutput in the same manner as COPY statements.CBL, PROCESS, *CONTROL, and *CBL card images are passed to the MDECK output file inthe proper locations.For a batch compilation (multiple <strong>COBOL</strong> source programs in a single input file), asingle MDECK output file that contains the complete expanded source is created.330 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Any SEQUENCE compiler-option processing is reflected in the MDECK file.COPY statements are included in the MDECK file as comments.RELATED TASKS“Starting the compiler from an assembler program” on page 263“Defining the library-processing output file (SYSMDECK)” on page 271RELATED REFERENCES“Conflicting compiler options” on page 304Chapter 18, “Compiler-directing statements,” on page 363NAMEUse NAME to generate a link-edit NAME card <strong>for</strong> each object module. You can also useNAME to generate names <strong>for</strong> each load module when you are doing batchcompilations.When NAME is specified, a NAME card is appended to each object module that iscreated. Load module names are <strong>for</strong>med using the rules <strong>for</strong> <strong>for</strong>ming module namesfrom PROGRAM-ID statements.NAME option syntax►►NONAMENAMENOALIAS( ALIAS )►◄Default is: NONAME, orNAME(NOALIAS) if only NAME is specifiedAbbreviations are: NoneIf you specify NAME(ALIAS), and your program contains ENTRY statements, alink-edit ALIAS card is generated <strong>for</strong> each ENTRY statement.The NAME or NAME(ALIAS) option cannot be used <strong>for</strong> compiling programs that willbe prelinked with the Language Environment prelinker.RELATED REFERENCESPROGRAM-ID paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)NSYMBOLThe NSYMBOL option controls the interpretation of the N symbol used in literals andPICTURE clauses, indicating whether national or DBCS processing is assumed.Chapter 17. Compiler options 331


NSYMBOL option syntax►►NATIONALNSYMBOL( DBCS ) ►◄Default is: NSYMBOL(NATIONAL)Abbreviations are: NS(NAT|DBCS)With NSYMBOL(NATIONAL):v Data items defined with a PICTURE clause that consists only of the symbol Nwithout the USAGE clause are treated as if the USAGE NATIONAL clause is specified.v Literals of the <strong>for</strong>m N"..."or N'. . .' are treated as national literals.With NSYMBOL(DBCS):v Data items defined with a PICTURE clause that consists only of the symbol Nwithout the USAGE clause are treated as if the USAGE DISPLAY-1 clause is specified.v Literals of the <strong>for</strong>m N"..."or N'. . .' are treated as DBCS literals.The NSYMBOL(DBCS) option provides compatibility with previous releases of IBM<strong>COBOL</strong>, and the NSYMBOL(NATIONAL) option makes the handling of the abovelanguage elements consistent with Standard <strong>COBOL</strong> 2002 in this regard.NSYMBOL(NATIONAL) is recommended <strong>for</strong> applications that use Unicode data orobject-oriented syntax <strong>for</strong> Java interoperability.RELATED REFERENCES“Conflicting compiler options” on page 304NUMBERUse the NUMBER compiler option if you have line numbers in your source code andwant those numbers to be used in error messages and SOURCE, MAP, LIST, and XREFlistings.NUMBER option syntax►►NONUMBERNUMBER►◄Default is: NONUMBERAbbreviations are: NUM|NONUMIf you request NUMBER, the compiler checks columns 1 through 6 to make sure thatthey contain only numbers and that the numbers are in numeric collating332 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


sequence. (In contrast, SEQUENCE checks the characters in these columns accordingto EBCDIC collating sequence.) When a line number is found to be out ofsequence, the compiler assigns to it a line number with a value one higher than theline number of the preceding statement. The compiler flags the new value withtwo asterisks and includes in the listing a message indicating an out-of-sequenceerror. Sequence-checking continues with the next statement, based on the newlyassigned value of the previous line.If you use COPY statements and NUMBER is in effect, be sure that your sourceprogram line numbers and the copybook line numbers are coordinated.If you are doing a batch compilation and LIB and NUMBER are in effect, all programsin the batch compile will be treated as a single input file. The sequence numbers ofthe entire input file must be in ascending order.Use NONUMBER if you do not have line numbers in your source code, or if you wantthe compiler to ignore the line numbers you do have in your source code. WithNONUMBER in effect, the compiler generates line numbers <strong>for</strong> your source statementsand uses those numbers as references in listings.NUMPROCUse NUMPROC(NOPFD) whenever your numeric internal decimal and zoned decimaldata might use nonpreferred signs.NUMPROC option syntax►►NOPFDNUMPROC( PFD )MIG►◄Default is: NUMPROC(NOPFD)Abbreviations are: NoneThe compiler accepts any valid sign configuration: X’A’, X’B’, X’C’, X’D’, X’E’, orX’F’. NUMPROC(NOPFD) is the recommended option in most cases.NUMPROC(PFD) improves the per<strong>for</strong>mance of processing numeric internal decimaland zoned decimal data. Use this option only if your program data agrees exactlywith the following IBM system standards:Zoned decimal, unsigned: High-order 4 bits of the sign byte contain X’F’.Zoned decimal, signed overpunch: High-order 4 bits of the sign byte contain X’C’if the number is positive or 0, and X’D’ if it is not.Zoned decimal, separate sign: Separate sign contains the character ’+’ if thenumber is positive or 0, and ’-’ if it is not.Internal decimal, unsigned: Low-order 4 bits of the low-order byte contain X’F’.Chapter 17. Compiler options 333


Internal decimal, signed: Low-order 4 bits of the low-order byte contain X’C’ if thenumber is positive or 0, and X’D’ if it is not.Data produced by <strong>COBOL</strong> arithmetic statements con<strong>for</strong>ms to the above IBMsystem standards. However, using REDEFINES and group moves could change dataso that it no longer con<strong>for</strong>ms. If you use NUMPROC(PFD), use the INITIALIZEstatement to initialize data fields, rather than using group moves.Using NUMPROC(PFD) can affect class tests <strong>for</strong> numeric data. You should useNUMPROC(NOPFD) or NUMPROC(MIG) if a <strong>COBOL</strong> program calls programs written inPL/I or FORTRAN.Sign representation is affected not only by the NUMPROC option, but also by theinstallation-time option NUMCLS.Use NUMPROC(MIG) to aid in migrating <strong>OS</strong>/VS <strong>COBOL</strong> programs to <strong>Enterprise</strong><strong>COBOL</strong>. When NUMPROC(MIG) is in effect, the following processing occurs:vvvvPreferred signs are created only on the output of MOVE statements and arithmeticoperations.No explicit sign repair is done on input.Some implicit sign repair might occur during conversion.Numeric comparisons are per<strong>for</strong>med by a decimal comparison, not a logicalcomparison.RELATED TASKS“Checking <strong>for</strong> incompatible data (numeric class test)” on page 56RELATED REFERENCES“Sign representation of zoned and packed-decimal data” on page 55OBJECTUse OBJECT to place the generated object code on disk or tape to be later used asinput <strong>for</strong> the linkage editor or binder.OBJECT option syntax►►OBJECTNOOBJECT►◄Default is: OBJECTAbbreviations are: OBJ|NOOBJIf you specify OBJECT, include a SYSLIN DD statement in your JCL <strong>for</strong> compilation.The only difference between DECK and OBJECT is in the routing of the data sets:v DECK output goes to the data set associated with ddname SYSPUNCH.334 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vOBJECT output goes to the data set associated with ddname SYSLIN.Use the option that your installation guidelines recommend.RELATED REFERENCES“Conflicting compiler options” on page 304OFFSETUse OFFSET to produce a condensed PROCEDURE DIVISION listing.OFFSET option syntax►►NOOFFSETOFFSET►◄Default is: NOOFFSETAbbreviations are: OFF|NOOFFWith OFFSET, the condensed PROCEDURE DIVISION listing will contain line numbers,statement references, and the location of the first instruction generated <strong>for</strong> eachstatement. In addition, the listing also shows:v Global tablesv Literal poolsvSize of the program’s WORKING-STORAGE, and its location in the object code if theprogram is compiled with the NORENT optionRELATED REFERENCES“Conflicting compiler options” on page 304OPTFILEUse OPTFILE to enable the specifying of <strong>COBOL</strong> compiler options in a data set.Using a compiler-option data set circumvents the 100-character limit on optionsspecified in a JCL PARM string.OPTFILE option syntax►► OPTFILE ►◄Default is: NoneAbbreviations are: NoneChapter 17. Compiler options 335


You can specify OPTFILE as a compiler invocation option or in the PROCESS or CBLstatement in your <strong>COBOL</strong> source program. OPTFILE cannot be specified as aninstallation default.OPTFILE is ignored if you compile using the cob2 command in the z/<strong>OS</strong> UNIXenvironment. (In that environment, the COBOPT environment variable provides acapability that is comparable to OPTFILE.)If OPTFILE is in effect, compiler options are read from the data set that you identifyin a SYSOPTF DD statement. A SYSOPTF data set must have RECFM F or FB and anLRECL of 80 bytes. For further details about the <strong>for</strong>mat of a SYSOPTF data set, see therelated task below about defining a compiler-option data set.The precedence of options in the SYSOPTF data set is determined by where youspecify the OPTFILE option. For example, if you specify OPTFILE in the invocationPARM string, an option specified later in the PARM string supersedes any optionspecified in the SYSOPTF data set that conflicts with it.|(Conceptually, OPTFILE in an options specification is replaced with the options thatare in the SYSOPTF data set; then the usual rules about precedence of compileroptions and conflicting compiler options apply.)If you start the <strong>COBOL</strong> compiler from within an assembler program, you can usethe alternate ddname list to specify a ddname to be used instead of SYSOPTF toidentify the compiler-option data set.RELATED TASKS“Starting the compiler from an assembler program” on page 263“Defining a compiler-option data set (SYSOPTF)” on page 267“Specifying compiler options under z/<strong>OS</strong>” on page 271Chapter 15, “Compiling under z/<strong>OS</strong> UNIX,” on page 283RELATED REFERENCES“Conflicting compiler options” on page 304OPTIMIZEUse OPTIMIZE to reduce the run time of your object program. Optimization mightalso reduce the amount of storage your object program uses.OPTIMIZE option syntax►►NOOPTIMIZEOPTIMIZESTD( FULL )►◄Default is: NOOPTIMIZEAbbreviations are: OPT|NOOPT336 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If OPTIMIZE is specified without any suboptions, OPTIMIZE(STD) will be in effect.The FULL suboption requests that, in addition to the optimizations per<strong>for</strong>med withOPT(STD), the compiler discard unreferenced data items from the DATA DIVISIONand suppress generation of code to initialize these data items to the values in theirVALUE clauses. When OPT(FULL) is in effect, all unreferenced level-77 items andelementary level-01 items are discarded. In addition, level-01 group items arediscarded if none of their subordinate items are referenced. The deleted items areshown in the listing. If the MAP option is in effect, a BL number of XXXXX in the datamap in<strong>for</strong>mation indicates that the data item was discarded.Unused data items: Do not use OPT(FULL) if your programs depend on making useof unused data items. In the past, this was commonly done in two ways:vvA technique sometimes used in old <strong>OS</strong>/VS <strong>COBOL</strong> programs was to place anunreferenced table after a referenced table and use out-of-range subscripts on thefirst table to access the second table. To determine whether your programs usethis technique, use the SSRANGE compiler option with the CHECK(ON) runtimeoption. To work around this problem, use the ability of newer <strong>COBOL</strong> to codelarge tables and use just one table.Place eye-catcher data items in the WORKING-STORAGE SECTION to identify thebeginning and end of the program data or to mark a copy of a program <strong>for</strong> alibrary tool that uses the data to identify the version of a program. To solve thisproblem, initialize these items with PROCEDURE DIVISION statements rather thanVALUE clauses. With this method, the compiler will consider these items used andwill not delete them.The OPTIMIZE option is turned off in the case of a severe-level error or higher.RELATED CONCEPTS“Optimization” on page 669RELATED REFERENCES“Conflicting compiler options” on page 304“TEST” on page 349OUTDDUse OUTDD to specify that you want DISPLAY output that is directed to the systemlogical output device to go to a specific ddname.You can specify a file in the z/<strong>OS</strong> UNIX file system with the ddname named inOUTDD. To understand where output is directed when this ddname is not allocated,see the related task about displaying data.OUTDD option syntax►► OUTDD(ddname) ►◄Default is: OUTDD(SYSOUT)Chapter 17. Compiler options 337


Abbreviations are: OUTThe MSGFILE runtime option lets you specify the ddname of the file to which allruntime diagnostics and reports generated by the RPTOPTS and RPTSTG runtimeoptions are to be written. The IBM-supplied default is MSGFILE(SYSOUT). IftheOUTDD compiler option and the MSGFILE runtime option both specify the sameddname, the error message in<strong>for</strong>mation and DISPLAY output directed to the systemlogical output device are routed to the same destination.Restriction: The OUTDD option has no effect under CICS.RELATED TASKS“Displaying data on the system logical output device” on page 39“Coding <strong>COBOL</strong> programs to run under CICS” on page 407RELATED REFERENCESLanguage Environment <strong>Programming</strong> Reference (MSGFILE)PGMNAMEThe PGMNAME option controls the handling of program-names and entry-pointnames.PGMNAME option syntax►►COMPATPGMNAME( LONGMIXED )LONGUPPER►◄Default is: PGMNAME(COMPAT)Abbreviations are: PGMN(LM|LU|CO)LONGUPPER can be abbreviated as UPPER, LU, orU. LONGMIXED can be abbreviated asMIXED, LM, orM.|||||PGMNAME controls the handling of names used in the following contexts:v Program-names defined in the PROGRAM-ID paragraphv Program entry-point names in the ENTRY statementv Program-name references in:– CALL statements that reference nested programs, statically linked programs, orDLLs– SET procedure-pointer or function-pointer statements that reference staticallylinked programs or DLLs– CANCEL statements that reference nested programs338 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


PGMNAME(COMPAT)||||With PGMNAME(COMPAT), program-names are handled in a manner compatible witholder versions of <strong>COBOL</strong> compilers:v The program-name can be up to 30 characters in length.vvvAll the characters used in the name must be alphabetic, digits, the hyphen, orthe underscore, except that if the program-name is a literal and is in theoutermost program, then the literal can also contain the extension characters @,#, and $, and the first character can be an underscore.At least one character must be alphabetic.The hyphen cannot be used as the first or last character.External program-names are processed by the compiler as follows:v They are folded to uppercase.v They are truncated to eight characters.v Hyphens are translated to zero (0).v If the first character is not alphabetic, and is not an underscore, it is converted asfollows:– 1-9 are translated to A-I.– Anything else is translated to J.PGMNAME(LONGUPPER)|||||With PGMNAME(LONGUPPER), program-names that are specified in the PROGRAM-IDparagraph as <strong>COBOL</strong> user-defined words must follow the normal <strong>COBOL</strong> rules <strong>for</strong><strong>for</strong>ming a user-defined word:v The program-name can be up to 30 characters in length.vvvAll the characters used in the name must be alphabetic, digits, the hyphen, orthe underscore.At least one character must be alphabetic.The hyphen cannot be used as the first or last character.When a program-name is specified as a literal, in either a definition or a reference,then:v The program-name can be up to 160 characters in length.vvvAll the characters used in the name must be alphabetic, digits, the hyphen, orthe underscore.At least one character must be alphabetic.The hyphen cannot be used as the first or last character.External program-names are processed by the compiler as follows:v They are folded to uppercase.v Hyphens are translated to zero (0).v If the first character is not alphabetic, and is not an underscore, it is converted asfollows:– 1-9 are translated to A-I.– Anything else is translated to J.Names of nested programs are folded to uppercase by the compiler but otherwiseare processed as is, without truncation or translation.Chapter 17. Compiler options 339


PGMNAME(LONGMIXED)Usage notesWith PGMNAME(LONGMIXED), program-names are processed as is, without truncation,translation, or folding to uppercase.With PGMNAME(LONGMIXED), all program-name definitions must be specified usingthe literal <strong>for</strong>mat of the program-name in the PROGRAM-ID paragraph or ENTRYstatement. The literal user <strong>for</strong> a program-name can contain any character in therange X'41'-X'FE'.vvvvThe following elements are not affected by the PGMNAME option:– Class-names and method-names.– System-names (assignment-names in SELECT ...ASSIGN, and text-names orlibrary-names in COPY statements).– Dynamic calls.Dynamic calls are resolved with truncation of the program-name to eightcharacters, folding to uppercase, and translation of embedded hyphens or aleading digit.– CANCEL of nonnested programs. Name resolution uses the same mechanism as<strong>for</strong> a dynamic call.Link-edit considerations: <strong>COBOL</strong> programs that are compiled with thePGMNAME(LONGUPPER) or PGMNAME(LONGMIXED) option must be link-edited in AMODE31.Dynamic calls are not permitted to <strong>COBOL</strong> programs compiled with thePGMNAME(LONGMIXED) or PGMNAME(LONGUPPER) options unless the program-name isless than or equal to 8 bytes, and all uppercase. In addition, the name of theprogram must be identical to the name of the module that contains it.When using the extended character set supported by PGMNAME(LONGMIXED), besure to use names that con<strong>for</strong>m to the linkage-editor, binder, prelinker, or systemconventions that apply, depending on the mechanism used to resolve the names.Using characters such as commas or parentheses is not recommended, becausethese characters are used in the syntax of linkage-editor and binder controlstatements.QUOTE/AP<strong>OS</strong>TRELATED REFERENCESPROGRAM-ID paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Use QUOTE if you want the figurative constant [ALL] QUOTE or [ALL] QUOTES torepresent one or more quotation mark (″) characters. Use AP<strong>OS</strong>T if you want thefigurative constant [ALL] QUOTE or [ALL] QUOTES to represent one or more singlequotation mark (’) characters.340 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


QUOTE/AP<strong>OS</strong>T option syntax►►QUOTEAP<strong>OS</strong>T►◄Default is: QUOTEAbbreviations are: Q|AP<strong>OS</strong>TDelimiters: You can use either quotation marks or single quotation marks as literaldelimiters regardless of whether the AP<strong>OS</strong>T or QUOTE option is in effect. Thedelimiter character used as the opening delimiter <strong>for</strong> a literal must be used as theclosing delimiter <strong>for</strong> that literal.RENTA program compiled as RENT is generated as a reentrant object program. A programcompiled as NORENT is generated as a nonreentrant object program. Either areentrant or a nonreentrant program can be invoked as a main program or as asubprogram.RENT option syntax►►RENTNORENT►◄Default is: RENTAbbreviations are: NoneDATA and RMODE settings: The RENT option interacts with other compiler options thataffect storage and its addressability. When a reentrant program is to be run withextended addressing, you can use the DATA(24|31) option to control whetherdynamic data areas are allocated in unrestricted storage or in storage obtainedfrom below 16 MB. Compile programs with RENT or RMODE(ANY) if they will be runwith extended addressing in virtual storage addresses above 16 MB.RENT also affects the RMODE (residency mode) of your generated object program. All<strong>Enterprise</strong> <strong>COBOL</strong> programs are AMODE ANY.DATA: The setting of the DATA option does not affect programs compiled withNORENT.For in<strong>for</strong>mation about which <strong>Enterprise</strong> <strong>COBOL</strong> programs need to be reentrant, seethe related task below about making programs reentrant.Chapter 17. Compiler options 341


Link-edit considerations: If all programs in a load module are compiled with RENT,it is recommended that the load module be link-edited with the RENT linkage-editoror binder option. (Use the REUS linkage-editor or binder option instead if the loadmodule will also contain any non-<strong>COBOL</strong> programs that are serially reusable.)If any program in a load module is compiled with NORENT, the load module mustnot be link-edited with the RENT or REUS link-edit attributes. The NOREUSlinkage-editor or binder option is needed to ensure that the CANCEL statement willguarantee a fresh copy of the program on a subsequent CALL.RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Making programs reentrant” on page 464DB2 Application <strong>Programming</strong> and SQL <strong>Guide</strong> (Using reentrant code)RELATED REFERENCES“Conflicting compiler options” on page 304RMODEThe RMODE setting influences the RMODE (residency mode) of your generated objectprogram.RMODE option syntax►►AUTORMODE( 24 )ANY►◄Default is: AUTOAbbreviations are: NoneA program compiled with the RMODE(AUTO) option will have RMODE 24 if NORENT isspecified, or RMODE ANY if RENT is specified. RMODE(AUTO) is compatible with oldercompilers such as VS <strong>COBOL</strong> II, which produced RMODE 24 <strong>for</strong> programs compiledwith NORENT, and RMODE ANY <strong>for</strong> programs compiled with RENT.A program compiled with the RMODE(24) option will have RMODE 24 whether NORENTor RENT is specified.A program compiled with the RMODE(ANY) option will have RMODE ANY whetherNORENT or RENT is specified.DATA and RENT: The RMODE option interacts with other compiler options and runtimeoptions that affect storage and its addressability. For in<strong>for</strong>mation about passingdata between programs with different modes, see the related concept about storageand its addressability.342 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Link-edit considerations: If the object code that <strong>COBOL</strong> generates has an attributeof RMODE 24, you must link-edit the code with RMODE 24. If the object code that<strong>COBOL</strong> generates has an attribute of RMODE ANY, you can link-edit the code witheither RMODE ANY or RMODE 24.RELATED CONCEPTS“Storage and its addressability” on page 42RELATED REFERENCES“Allocation of buffers <strong>for</strong> QSAM files” on page 173“Conflicting compiler options” on page 304SEQUENCEWhen you use SEQUENCE, the compiler examines columns 1 through 6 to check thatthe source statements are arranged in ascending order according to their EBCDICcollating sequence. The compiler issues a diagnostic message if any statements arenot in ascending order.Source statements with blanks in columns 1 through 6 do not participate in thissequence check and do not result in messages.SEQUENCE option syntax►►SEQUENCEN<strong>OS</strong>EQUENCE►◄Default is: SEQUENCEAbbreviations are: SEQ|N<strong>OS</strong>EQIf you use COPY statements with the SEQUENCE option in effect, be sure that yoursource program’s sequence fields and the copybook sequence fields arecoordinated.If you use NUMBER and SEQUENCE, the sequence is checked according to numeric,rather than EBCDIC, collating sequence.If you are doing a batch compilation and LIB and SEQUENCE are in effect, allprograms in the batch compilation are treated as a single input file. The sequencenumbers of the entire input file must be in ascending order.Use N<strong>OS</strong>EQUENCE to suppress this checking and the diagnostic messages.RELATED TASKS“Finding line sequence problems” on page 373Chapter 17. Compiler options 343


SIZEUse SIZE to indicate the amount of main storage to be made available <strong>for</strong>compilation.SIZE option syntax►►MAXSIZE( nnnnn )nnnK►◄Default is: SIZE(MAX)Abbreviations are: SZnnnnn specifies a decimal number, which must be at least 851968.nnnK specifies a decimal number in 1-KB increments, where 1 KB = 1024 bytes.The minimum acceptable value is 832K.MAX requests the largest available block of storage in the user region.Do not use SIZE(MAX) if you require that the compiler leave a specific amount ofunused storage available in the user region. For example, if you are using the CICSor SQL compiler option, use a value such as SIZE(4000K). (This value should work<strong>for</strong> most programs.) If you compile in 31-bit mode and specify SIZE(MAX), thecompiler uses storage as follows:v Above the 16-MB line: all the storage in the user regionv Below the 16-MB line: storage <strong>for</strong>:– Work-file buffers– Compiler modules that must be loaded below the lineSOURCEUse SOURCE to get a listing of your source program. This listing will include anystatements embedded by PROCESS or COPY statements.SOURCE option syntax►►SOURCEN<strong>OS</strong>OURCE►◄Default is: SOURCE344 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Abbreviations are: S|N<strong>OS</strong>You must specify SOURCE if you want embedded messages in the source listing.Use N<strong>OS</strong>OURCE to suppress the source code from the compiler output listing.If you want to limit the SOURCE output, use *CONTROL SOURCE or N<strong>OS</strong>OURCEstatements in your PROCEDURE DIVISION. Source statements that follow a *CONTROLN<strong>OS</strong>OURCE statement are not included in the listing until a subsequent *CONTROLSOURCE statement switches the output back to normal SOURCE <strong>for</strong>mat.“Example: MAP output” on page 382RELATED REFERENCES*CONTROL (*CBL) statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SPACEUse SPACE to select single-, double-, or triple-spacing in your source code listing.SPACE option syntax►►1SPACE( 2 )3►◄Default is: SPACE(1)Abbreviations are: NoneSPACE has meaning only when the SOURCE compiler option is in effect.RELATED REFERENCES“SOURCE” on page 344SQLUse the SQL compiler option to enable the DB2 coprocessor and to specify DB2suboptions. You must specify the SQL option if a <strong>COBOL</strong> source program containsSQL statements and the program has not been processed by the DB2 precompiler.Chapter 17. Compiler options 345


SQL option syntax►►N<strong>OS</strong>QLSQL(″DB2-suboption-string″)►◄Default is: N<strong>OS</strong>QLAbbreviations are: NoneWhen you use the SQL option, the DB2 coprocessor writes the database requestmodule (DBRM) to ddname DBRMLIB. DB2 must be available on the machine onwhich you compile.If you specify the N<strong>OS</strong>QL option, any SQL statements found in the source programare diagnosed and discarded.Use either quotation marks or single quotation marks to delimit the string of DB2suboptions.You can partition a long suboption string into multiple suboption strings inmultiple CBL statements. For example://STEP1 EXEC IGYWC, ...// PARM.<strong>COBOL</strong>='SQL("string1")'//<strong>COBOL</strong>.SYSIN DD *CBL SQL("string2")CBL SQL('string3')IDENTIFICATION DIVISION.PROGRAM-ID. DRIVER1....The DB2 suboptions are concatenated in the order of their appearance. Thus in theexample above, the compiler passes the following suboption string to the DB2coprocessor:"string1 string2 string3"The concatenated strings are delimited with single spaces as shown. If multipleinstances of the same DB2 option are found, the last specification of each optionprevails. The compiler limits the length of the concatenated DB2 suboption stringto 4 KB.RELATED CONCEPTS“DB2 coprocessor” on page 419“<strong>COBOL</strong> and DB2 CCSID determination” on page 425RELATED TASKS“Compiling with the SQL option” on page 423“Separating DB2 suboptions” on page 424RELATED REFERENCES“Conflicting compiler options” on page 304346 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


SQLCCSIDUse the SQLCCSID compiler option to control whether the CODEPAGE compiler optionwill influence the processing of SQL statements in your <strong>COBOL</strong> programs.SQLCCSID option syntax►►SQLCCSIDN<strong>OS</strong>QLCCSID►◄Default is: SQLCCSIDAbbreviations are: SQLC|N<strong>OS</strong>QLCThe SQLCCSID option has an effect only if you use the integrated DB2 coprocessor(SQL compiler option).||||||If SQLCCSID is in effect, the setting of the CODEPAGE compiler option will influencethe processing of SQL statements within your <strong>COBOL</strong> programs when you use theintegrated DB2 coprocessor. If N<strong>OS</strong>QLCCSID is in effect, the CODEPAGE setting will notinfluence the processing of SQL statements when you use the integrated DB2coprocessor; only <strong>COBOL</strong> statements will be sensitive to the CCSID specified in theCODEPAGE option.For further in<strong>for</strong>mation about this option, see the related task.RELATED CONCEPTS“DB2 coprocessor” on page 419“<strong>COBOL</strong> and DB2 CCSID determination” on page 425RELATED TASKS“<strong>Programming</strong> with the SQLCCSID or N<strong>OS</strong>QLCCSID option” on page 426RELATED REFERENCES“Code-page determination <strong>for</strong> string host variables in SQL statements” on page 426“CODEPAGE” on page 310“SQL” on page 345SSRANGEUse SSRANGE to generate code that checks whether subscripts (including ALLsubscripts) or indexes try to reference an area outside the region of the table. Eachsubscript or index is not individually checked <strong>for</strong> validity; rather, the effectiveaddress is checked to ensure that it does not cause a reference outside the region ofthe table.Variable-length items are also checked to ensure that the reference is within theirmaximum defined length.Chapter 17. Compiler options 347


SSRANGE option syntax►►N<strong>OS</strong>SRANGESSRANGE►◄Default is: N<strong>OS</strong>SRANGEAbbreviations are: SSR|N<strong>OS</strong>SRReference modification expressions are checked to ensure that:v The starting position is greater than or equal to 1.v The starting position is not greater than the current length of the subject dataitem.v The length value (if specified) is greater than or equal to 1.v The starting position and length value (if specified) do not reference an areabeyond the end of the subject data item.If SSRANGE is in effect at compile time, range-checking code is generated. You caninhibit range checking by specifying the CHECK(OFF) runtime option. Doing soleaves range-checking code dormant in the object code. Optionally, therange-checking code can be used to aid in resolving unexpected errors withoutrecompilation.If an out-of-range condition is detected, an error message is generated and theprogram is terminated.Attention: Range checking is done only if you compile a program with the SSRANGEoption and run it with the CHECK(ON) option.RELATED CONCEPTS“Reference modifiers” on page 109RELATED TASKS“Checking <strong>for</strong> valid ranges” on page 373TERMINALUse TERMINAL to send progress and diagnostic messages to the SYSTERM ddname.TERMINAL option syntax►►NOTERMINALTERMINAL►◄348 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Default is: NOTERMINALAbbreviations are: TERM|NOTERMUse NOTERMINAL if you do not want this additional output.TESTUse TEST to produce object code that enables Debug Tool to per<strong>for</strong>m batch andinteractive debugging. With TEST, you can also enable the inclusion of symbolicvariables in the <strong>for</strong>matted dumps produced by Language Environment.TEST option syntax►►NOTESTTESTHOOK ,N<strong>OS</strong>EPARATE ,NOEJPD( )NOHOOK ,SEPARATE ,EJPD►◄Option default is: NOTESTSuboption defaults are: HOOK, N<strong>OS</strong>EPARATE, NOEJPDAbbreviations are: SEP|N<strong>OS</strong>EPYou can specify TEST suboptions in any order, and can specify any combination ofsuboptions (one, two, or all). If you code a left parenthesis after TEST, however, youmust code at least one suboption.The amount of debugging support available depends on which TEST suboptionsyou use, as explained below. Use NOTEST if you do not want to generate object codethat has debugging in<strong>for</strong>mation and do not require that <strong>for</strong>matted dumps includesymbolic variables.Hook suboptions (compiled-in versus dynamic hooks)HOOK Compiled-in hooks are generated at all statements, labels, and path points,and at all program entry and exit points (both in outermost and incontained programs). In addition, if the DATEPROC option is in effect, hooksare generated at all date-processing statements.A path point is any location in a program where the logic flow is notnecessarily sequential, or can change. Some examples of path points areIF-THEN-ELSE constructs, PERFORM loops, ON SIZE ERROR phrases, and CALLstatements.NOHOOK No compiled-in hooks are generated. With TEST(NOHOOK), you can use theDynamic Debug facility of Debug Tool (SET DYNDEBUG ON) to interactivelydebug your program.Symbolic debugging in<strong>for</strong>mation suboptionsChapter 17. Compiler options 349


In<strong>for</strong>mation needed to enable symbolic debugging is always generated if the TESToption is in effect.SEPARATESpecify the SEPARATE suboption to control module size while retainingdebugging capability. Symbolic in<strong>for</strong>mation is written to the SYSDEBUGdata set instead of to the object module. See the section below aboutcontrolling module size while retaining debugging capability.N<strong>OS</strong>EPARATESpecify the N<strong>OS</strong>EPARATE suboption to include symbolic debuggingin<strong>for</strong>mation in the object module.JUMPTO and GOTO enablement suboptionsThe EJPD and NOEJPD suboptions control enablement of the Debug Tool commandsJUMPTO and GOTO in production debugging sessions. These suboptions have aneffect only if the TEST(NOHOOK) and OPTIMIZE compiler options are specified.EJPD When TEST(NOHOOK,. . .,EJPD) and OPTIMIZE are specified:v The JUMPTO and GOTO commands are enabled.v The amount of program optimization is reduced. Optimization is donewithin statements, but most optimizations do not cross statementboundaries.NOEJPD When TEST(NOHOOK,. . .,NOEJPD) and OPTIMIZE are specified:v The JUMPTO and GOTO commands are not enabled.v The normal amount of program optimization is done.Controlling module size while retaining debugging capability:The TEST option causes the compiler to generate debug in<strong>for</strong>mation tables thatDebug Tool uses to resolve data-names, paragraph-names, and the like. Thisin<strong>for</strong>mation can take a lot of storage. You can choose either to compile thisin<strong>for</strong>mation into the object program or to write it to the separate SYSDEBUG dataset:vvFor smaller load modules, use the SEPARATE suboption and keep the separatedebugging files <strong>for</strong> use during Debug Tool sessions.To avoid having to manage separate debugging files, compile with theN<strong>OS</strong>EPARATE suboption; note though that this suboption results in larger loadmodules.If you invoke the <strong>COBOL</strong> compiler from JCL or TSO and you specifyTEST(. . .,SEPARATE,. . .), the symbolic debug in<strong>for</strong>mation tables are written tothe data set that you specify in the SYSDEBUG DD statement. For details about codingthat statement and about the SYSDEBUG data set, see the related in<strong>for</strong>mationbelow about defining the debug data set and about logical record length and blocksize.When you invoke the <strong>COBOL</strong> compiler from the z/<strong>OS</strong> UNIX shell and you specifyTEST(. . .,SEPARATE,. . .), the symbolic debug in<strong>for</strong>mation tables are written tofile.dbg in the current directory, where file is the name of the <strong>COBOL</strong> source file.Per<strong>for</strong>mance versus debugging capability:350 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


You can control the amount of debugging capability that you get and so also theprogram per<strong>for</strong>mance, as follows:vvvvFor the best per<strong>for</strong>mance, but with some restrictions on debugging, compileusing OPTIMIZE and TEST(NOHOOK,. . .,NOEJPD).When you use the Dynamic Debug facility of Debug Tool (SET DYNDEBUG ON),you can interactively debug your program even if the program has nocompiled-in debug hooks.With TEST(NOHOOK,. . .,NOEJPD), you can also compile using OPTIMIZE (eitherOPT(STD) or OPT(FULL)) <strong>for</strong> a more efficient program, but with some restrictionson debugging:– The Debug Tool commands JUMPTO and GOTO are not supported.– Except <strong>for</strong> the DESCRIBE ATTRIBUTES command, Debug Tool commands cannotrefer to any data item that was discarded from a program by the OPT(FULL)option.– The Debug Tool command AT CALL entry-name is not supported.For some reduction in program per<strong>for</strong>mance from the production-debuggingscenario above, but to enable the Debug Tool commands JUMPTO and GOTO,specify OPTIMIZE and TEST(NOHOOK,. . .,EJPD).The restrictions above about referring to items discarded by OPT(FULL) andabout the AT CALL command also apply when you use this combination ofoptions.For medium per<strong>for</strong>mance but fewer restrictions on debugging, specify NOOPT andTEST(NOHOOK).This combination does not run as fast as optimized code, but it providesincreased debugging capability. All Debug Tool commands are supported exceptAT CALL entry-name.For slowest per<strong>for</strong>mance but maximum debugging capability, specify NOOPT andTEST(HOOK).TEST(HOOK) causes the compiler to put compiled-in hooks at every statement,resulting in slower code, but all Debug Tool commands are supported.Language Environment:The TEST option specified with any of its suboptions can improve your <strong>for</strong>matteddumps from Language Environment by adding these two features to the dumps:v A line number that indicates the failing statement, rather than just an offsetv The values of the program variablesWith NOTEST, the dump will not have program variables nor the line number of thefailing statement.<strong>Enterprise</strong> <strong>COBOL</strong> uses the Language Environment-provided dump services toproduce dumps that are consistent in content and <strong>for</strong>mat with those that areproduced by other Language Environment-con<strong>for</strong>ming member languages.Whether Language Environment produces a dump <strong>for</strong> unhandled conditionsdepends on the setting of the runtime option TERMTHDACT. If you specifyTERMTHDACT(DUMP), a dump is generated when a condition of severity 2 or greatergoes unhandled.SEPARATE suboption and Language Environment:Chapter 17. Compiler options 351


For programs that are compiled using TEST(. . .,SEPARATE,. . .), LanguageEnvironment gets the name of the separate debug data set (which is written toddname SYSDEBUG) from the object program. To change the name of the separatedebug data set, use the Language Environment <strong>COBOL</strong> debug file exit.RELATED TASKS“Defining the debug data set (SYSDEBUG)” on page 270Language Environment Debugging <strong>Guide</strong> (Generating a Language Environmentdump with TERMTHDACT)Debug Tool User’s <strong>Guide</strong> (Special considerations while using the TESTruntime option)Language Environment Customization (Modifying the <strong>COBOL</strong> debug file name)RELATED REFERENCES“Logical record length and block size” on page 266“cob2 input and output files” on page 289“Conflicting compiler options” on page 304“OPTIMIZE” on page 336Language Environment <strong>Programming</strong> Reference (TEST | NOTEST)THREADTHREAD indicates that a <strong>COBOL</strong> program is to be enabled <strong>for</strong> execution in aLanguage Environment enclave that has multiple P<strong>OS</strong>IX threads or PL/I tasks.THREAD option syntax►►NOTHREADTHREAD►◄Default is: NOTHREADAbbreviations are: NoneA program that has been compiled with the THREAD option can also be used in anonthreaded application. However, if a <strong>COBOL</strong> program is to be run in a threadedapplication, all the <strong>COBOL</strong> programs in the Language Environment enclave mustbe compiled with the THREAD option.NOTHREAD indicates that the <strong>COBOL</strong> program is not to be enabled <strong>for</strong> execution inan enclave that has multiple P<strong>OS</strong>IX threads or PL/I tasks.Programs compiled using compilers earlier than <strong>Enterprise</strong> <strong>COBOL</strong> are treated as ifcompiled with NOTHREAD.When the THREAD option is in effect, the following elements are not supported. Ifencountered, they are diagnosed as errors:v ALTER statementv DEBUG-ITEM special register352 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvvvvvvvGO TO statement without procedure-nameINITIAL phrase in PROGRAM-ID clauseNested programsRERUNSegmentation moduleSORT or MERGE statementsSTOP literal statementUSE FOR DEBUGGING statementAdditionally, some language constructs have different semantics than in thenonthreaded case.Although threaded applications are subject to a number of programming andenvironment restrictions, the use of a program in nonthreaded applications is notso restricted. For example, a program compiled with the THREAD option can run inthe CICS and IMS environments, can run AMODE 24, and can call and be called byother programs that are not enabled <strong>for</strong> multithreading, provided that theapplication does not contain multiple P<strong>OS</strong>IX threads or PL/I tasks at run time.Programs compiled with the THREAD option are supported in a reusableenvironment that is created by calling the Language Environment preinitializationroutine CEEPIPI. But a reusable environment created by calling IGZERRE orILB<strong>OS</strong>TP0 or by using the RTEREUS runtime option is not supported <strong>for</strong> programscompiled with the THREAD option.Per<strong>for</strong>mance consideration: If you use the THREAD option, you can expect someruntime per<strong>for</strong>mance degradation due to the overhead of serialization logic that isautomatically generated.RELATED TASKSChapter 27, “Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading,” on page 493RELATED REFERENCES“Conflicting compiler options” on page 304TRUNCTRUNC affects the way that binary data is truncated during moves and arithmeticoperations.TRUNC option syntax►►STDTRUNC( OPT )BIN►◄Default is: TRUNC(STD)Abbreviations are: NoneChapter 17. Compiler options 353


TRUNC has no effect on COMP-5 data items; COMP-5 items are handled as ifTRUNC(BIN) is in effect regardless of the TRUNC suboption specified.TRUNC(STD)TRUNC(STD) applies only to USAGE BINARY receiving fields in MOVE statementsand arithmetic expressions. When TRUNC(STD) is in effect, the final result ofan arithmetic expression, or the sending field in the MOVE statement, istruncated to the number of digits in the PICTURE clause of the BINARYreceiving field.TRUNC(OPT)TRUNC(OPT) is a per<strong>for</strong>mance option. When TRUNC(OPT) is in effect, thecompiler assumes that data con<strong>for</strong>ms to PICTURE specifications in USAGEBINARY receiving fields in MOVE statements and arithmetic expressions. Theresults are manipulated in the most optimal way, either truncating to thenumber of digits in the PICTURE clause, or to the size of the binary field instorage (halfword, fullword, or doubleword).Tips:vUse the TRUNC(OPT) option only if you are sure that the data beingmoved into the binary areas will not have a value with larger precisionthan that defined by the PICTURE clause <strong>for</strong> the binary item. Otherwise,unpredictable results could occur. This truncation is per<strong>for</strong>med in themost efficient manner possible; there<strong>for</strong>e, the results are dependent onthe particular code sequence generated. It is not possible to predict thetruncation without seeing the code sequence generated <strong>for</strong> a particularstatement.v There are some cases when programs compiled with the TRUNC(OPT)option under <strong>Enterprise</strong> <strong>COBOL</strong> could give different results than thesame programs compiled under <strong>OS</strong>/VS <strong>COBOL</strong> with NOTRUNC. You mustactually lose nonzero high-order digits <strong>for</strong> this difference to appear.TRUNC(BIN)The TRUNC(BIN) option applies to all <strong>COBOL</strong> language that processes USAGEBINARY data. When TRUNC(BIN) is in effect, all binary items (USAGE COMP,COMP-4, orBINARY) are handled as native hardware binary items, that is, asif they were each individually declared USAGE COMP-5:vvvvBINARY receiving fields are truncated only at halfword, fullword, ordoubleword boundaries.BINARY sending fields are handled as halfwords, fullwords, ordoublewords when the receiver is numeric; TRUNC(BIN) has no effectwhen the receiver is not numeric.The full binary content of fields is significant.DISPLAY will convert the entire content of binary fields with notruncation.Recommendations: TRUNC(BIN) is the recommended option <strong>for</strong> programsthat use binary values set by other products. Other products, such as IMS,DB2, C/C++, FORTRAN, and PL/I, might place values in <strong>COBOL</strong> binarydata items that do not con<strong>for</strong>m to the PICTURE clause of the data items. Youcan use TRUNC(OPT) with CICS programs provided that your data con<strong>for</strong>msto the PICTURE clause <strong>for</strong> your BINARY data items.USAGE COMP-5 has the effect of applying TRUNC(BIN) behavior to individualdata items. There<strong>for</strong>e, you can avoid the per<strong>for</strong>mance overhead of usingTRUNC(BIN) <strong>for</strong> every binary data item by specifying COMP-5 on only someof the binary data items, such as those data items that are passed to354 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


TRUNC example 1non-<strong>COBOL</strong> programs or other products and subsystems. The use ofCOMP-5 is not affected by the TRUNC suboption in effect.Large literals in VALUE clauses: When you use the compiler optionTRUNC(BIN), numeric literals specified in VALUE clauses <strong>for</strong> binary dataitems (COMP, COMP-4, orBINARY) can generally contain a value of magnitudeup 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 inthePICTURE clause.01 BIN-VAR PIC S99 USAGE BINARY....MOVE 123451 to BIN-VARThe following table shows values of the data items after the MOVE statement.Data item Decimal Hex DisplaySender 123451 00|01|E2|3B 123451Receiver TRUNC(STD) 51 00|33 51Receiver TRUNC(OPT) -7621 E2|3B 2JReceiver TRUNC(BIN) -7621 E2|3B 762JA halfword of storage is allocated <strong>for</strong> BIN-VAR. The result of this MOVE statement ifthe program is compiled with the TRUNC(STD) option is 51; the field is truncated tocon<strong>for</strong>m to the PICTURE clause.If you compile the program with TRUNC(BIN), the result of the MOVE statement is-7621. The reason <strong>for</strong> the unusual result is that nonzero high-order digits aretruncated. Here, the generated code sequence would merely move the lowerhalfword quantity X’E23B’ to the receiver. Because the new truncated valueoverflows into the sign bit of the binary halfword, the value becomes a negativenumber.It is better not to compile this MOVE statement with TRUNC(OPT), because 123451 hasgreater precision than the PICTURE clause <strong>for</strong> BIN-VAR. With TRUNC(OPT), the resultsare again -7621. This is because the best per<strong>for</strong>mance was obtained by not doing adecimal truncation.TRUNC example 201 BIN-VAR PIC 9(6) USAGE BINARY...MOVE 1234567891 to BIN-VARThe following table shows values of the data items after the MOVE statement.Data item Decimal Hex DisplaySender 1234567891 49|96|02|D3 1234567891Receiver TRUNC(STD) 567891 00|08|AA|53 567891Receiver TRUNC(OPT) 567891 53|AA|08|00 567891Receiver TRUNC(BIN) 1234567891 49|96|02|D3 1234567891Chapter 17. Compiler options 355


When you specify TRUNC(STD), the sending data is truncated to six integer digits tocon<strong>for</strong>m to the PICTURE clause of the BINARY receiver.When you specify TRUNC(OPT), the compiler assumes the sending data is not largerthan the PICTURE clause precision of the BINARY receiver. The most efficient codesequence in this case is truncation as if TRUNC(STD) were in effect.When you specify TRUNC(BIN), no truncation occurs because all of the sending datafits into the binary fullword allocated <strong>for</strong> BIN-VAR.RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49RELATED TASKS“Compiling with the CICS option” on page 411RELATED REFERENCESVALUE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)VBREFUse VBREF to get a cross-reference among all verb used in the source program andthe line numbers in which they are used. VBREF also produces a summary of howmany times each verb was used in the program.VBREF option syntax►►NOVBREFVBREF►◄Default is: NOVBREFAbbreviations are: NoneUse NOVBREF <strong>for</strong> more efficient compilation.WORDUse WORD(xxxx) to specify that an alternate reserved-word table is to be used duringcompilation.356 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


WORD option syntax►►NOWORDWORD(xxxx)►◄Default is: NOWORDAbbreviations are: WD|NOWDxxxx specifies the ending characters of the name of the reserved-word table(IGYCxxxx) to be used in your compilation. IGYC are the first four standardcharacters of the name, and xxxx can be one to four characters in length.Alternate reserved-word tables provide changes to the IBM-supplied defaultreserved-word table. Your systems programmer might have created one or morealternate reserved-word tables <strong>for</strong> your site. See your systems programmer <strong>for</strong> thenames of alternate reserved-word tables.<strong>Enterprise</strong> <strong>COBOL</strong> provides an alternate reserved-word table (IGYCCICS)specifically <strong>for</strong> CICS applications. It is set up to flag <strong>COBOL</strong> words not supportedunder CICS with an error message. If you want to use this CICS reserved-wordtable during your compilation, specify the compiler option WORD(CICS).RELATED TASKS“Compiling with the CICS option” on page 411RELATED REFERENCES“Conflicting compiler options” on page 304“CICS reserved-word table” on page 415XMLPARSEUse XMLPARSE to select the parser to be used <strong>for</strong> XML processing and, there<strong>for</strong>e, theXML processing capabilities that are available to your program.XMLPARSE option syntax►►XMLSSXMLPARSE( COMPAT ) ►◄Default is: XMLSSAbbreviations are: XP(X), XP(C)If you specify the XMLPARSE(XMLSS) option, XML PARSE statements are processedusing the z/<strong>OS</strong> XML System Services parser. The following XML parsingcapabilities are available only if you specify XMLPARSE(XMLSS):Chapter 17. Compiler options 357


||||vvvvvvvValidation of XML input documents against an XML schema (by using theVALIDATING phrase of the XML PARSE statement)Enhanced namespace processing (special registers XML-NAMESPACE,XML-NNAMESPACE, XML-NAMESPACE-PREFIX, and XML-NNAMESPACE-PREFIX)Automatic conversion of document fragments to Unicode UTF-16 (by using theRETURNING NATIONAL phrase of the XML PARSE statement)Specification of the encoding of the input document (by using the ENCODINGphrase of the XML PARSE statement)Direct parsing of XML documents encoded in UTF-8Parsing of XML documents, a buffer of XML at a timeOffloading of XML parsing to System z ® Application Assist Processors (zAAPs)If you specify the XMLPARSE(COMPAT) option, XML PARSE statements are processedusing the XML parser that is a built-in component of the <strong>COBOL</strong> run time. XMLPARSE statement results and operational behaviors are then compatible with thoseobtained with <strong>Enterprise</strong> <strong>COBOL</strong> Version 3, and the advanced features describedabove <strong>for</strong> XMLPARSE(XMLSS) are not available.RELATED TASKSChapter 28, “Processing XML input,” on page 503RELATED REFERENCESXML PARSE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and ReferenceXREFUse XREF to produce a sorted cross-reference listing.XREF option syntax►►XREFNOXREFFULL( SHORT )►◄Default is: XREF(FULL)Abbreviations are: X|NOXYou can choose XREF, XREF(FULL), orXREF(SHORT). If you specify XREF without anysuboptions, XREF(FULL) will be in effect.A section of the listing shows all the program-names, data-names, andprocedure-names that are referenced in your program, and the line numbers wherethose names are defined. External program-names are identified.358 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Example: XREF output: data-name cross-references” on page 398“Example: XREF output: program-name cross-references” on page 400A section is also included that cross-references COPY or BASIS statements in theprogram with the data sets or files from which associated copybooks wereobtained.“Example: XREF output: COPY/BASIS cross-references” on page 400EBCDIC data-names and procedure-names are listed in alphanumeric order. DBCSdata-names and procedure-names are listed based on their physical order in theprogram; they are shown be<strong>for</strong>e the EBCDIC data-names and procedure-namesunless the DBCSXREF installation option is selected with a DBCS ordering program.In that case, DBCS data-names and procedure-names are in the order specified bythe DBCS ordering program.If you use XREF and SOURCE, data-name and procedure-name cross-referencein<strong>for</strong>mation is printed on the same line as the original source. Line-numberreferences or other in<strong>for</strong>mation appears on the right-hand side of the listing page.On the right of source lines that reference an intrinsic function, the letters IFN areprinted with the line number of the locations where the function arguments aredefined. In<strong>for</strong>mation included in the embedded references lets you know if anidentifier is undefined (UND) or defined more than once (DUP), if items are implicitlydefined (IMP) (such as special registers or figurative constants), or if aprogram-name is external (EXT).If you use XREF and N<strong>OS</strong>OURCE, you get only the sorted cross-reference listing.XREF(SHORT) prints only the explicitly referenced data items in the cross-referencelisting. XREF(SHORT) applies to DBCS data-names and procedure-names as well asto single-byte names.NOXREF suppresses this listing.|||||||Usage notesv Group names used in a MOVE CORRESPONDING statement are in the XREF listing.The elementary names in those groups are also listed.v In the data-name XREF listing, line numbers that are preceded by the letter Mindicate that the data item is explicitly modified by a statement on that line.v XREF listings take additional storage.v If there is more than one data set in your SYSLIB concatenation, in some casesthe COPY/BASIS cross-reference might be incomplete or missing. This loss canoccur if XREF is set only in a CBL or PROCESS statement, and XREFOPT=NO is set asan installation default or NOXREF is coded in your JCL PARM parameter.To ensure that the COPY/BASIS cross-reference is complete, either verify with yoursystems programmer that XREFOPT=FULL or XREFOPT=SHORT is your installationdefault, or code the XREF option in your JCL PARM parameter.RELATED CONCEPTSChapter 19, “Debugging,” on page 367RELATED TASKS“Getting listings” on page 377Chapter 17. Compiler options 359


YEARWINDOWRELATED REFERENCESLanguage Environment Debugging <strong>Guide</strong> (<strong>COBOL</strong> compiler options)Use YEARWINDOW to specify the first year of the 100-year window (the centurywindow) to be applied to windowed date field processing by the <strong>COBOL</strong> compiler.YEARWINDOW option syntax►► YEARWINDOW(base-year) ►◄ZWBDefault is: YEARWINDOW(1900)Abbreviations are: YWbase-year represents the first year of the 100-year window. You must specify it withone of the following values:v An unsigned decimal number between 1900 and 1999.This specifies the starting year of a fixed window. For example,YEARWINDOW(1930) indicates a century window of 1930-2029.v A negative integer from -1 through -99.This indicates a sliding window. The first year of the window is calculated byadding the negative integer to the current year. For example, YEARWINDOW(-80)indicates that the first year of the century window is 80 years be<strong>for</strong>e the year inwhich the program is run.Usage notesv The YEARWINDOW option has no effect unless the DATEPROC option is also in effect.v At run time, two conditions must be true:– The century window must have its beginning year in the 1900s.– The current year must lie within the century window <strong>for</strong> the compilationunit.For example, if the current year is 2009, the DATEPROC option is in effect, and youuse the YEARWINDOW(1900) option, the program will terminate with an errormessage.If you compile with ZWB, the compiler removes the sign from a signed zoneddecimal (DISPLAY) field be<strong>for</strong>e comparing this field to an alphanumeric elementaryfield during execution.360 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


ZWB option syntax►►ZWBNOZWB►◄Default is: ZWBAbbreviations are: NoneIf the zoned decimal item is a scaled item (that is, it contains the symbol P in itsPICTURE string), its use in comparisons is not affected by ZWB. Such items alwayshave their sign removed be<strong>for</strong>e the comparison is made to an alphanumeric field.ZWB affects how a program runs. The same <strong>COBOL</strong> source program can givedifferent results, depending on this option setting.Use NOZWB if you want to test input numeric fields <strong>for</strong> SPACES.Chapter 17. Compiler options 361


362 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 18. Compiler-directing statementsSeveral statements help you to direct the compilation of your program.These are the compiler-directing statements:BASIS statementThis extended source program library statement provides a complete<strong>COBOL</strong> program as the source <strong>for</strong> a compilation. For rules of <strong>for</strong>mationand processing, see the description of text-name <strong>for</strong> the COPY statement.*CONTROL (*CBL) statementThis compiler-directing statement selectively suppresses or allows outputto be produced. The names *CONTROL and *CBL are synonymous.COPY statementCOPY statement syntax►► COPY text-nameliteral-1 OF library-nameIN literal-2►SUPPRESS►►◄▼REPLACING operand-1 BY operand-2|||This library statement places prewritten text into a <strong>COBOL</strong> program.Neither text-name nor library-name need to be unique within a program.They can be identical to other user-defined words in the program, exceptthat they cannot contain the underscore.The uniqueness of text-name and library-name is determined after the<strong>for</strong>mation and conversion rules <strong>for</strong> a system-dependent name have beenapplied. If library-name is omitted, SYSLIB is assumed.Compiling with JCL:text-name, library-name, and literal-1 and literal-2 are processed as follows:v The name (which can be from one to 30 characters long) is truncated toeight characters. Only the first eight characters of text-name andlibrary-name are used as the identifying name. These eight charactersmust be unique within any <strong>COBOL</strong> library.v The name is folded to uppercase.v Hyphens that are not the first or last character are translated to zero (0),and a warning message is issued.v If the first character is numeric, then the characters 1-9 are translated toA-I, zero (0) is converted to J, and a warning message is issued.For example:COPY INVOICES1QCOPY "Company-#Employees" IN Personellib© Copyright IBM Corp. 1991, 2009 363


In the IN/OF phrase, library-name is the ddname that identifies thepartitioned data set to be copied from. Use a DD statement such as in thefollowing example to define library-name://COPYLIB DD DSNAME=ABC.COB,VOLUME=SER=111111,// DISP=SHR,UNIT=3380To specify more than one copy library, use either JCL or a combination ofJCL and the IN/OF phrase. Using just JCL, concatenate data sets in your DDstatement <strong>for</strong> SYSLIB. Alternatively, define multiple DD statements andinclude the IN/OF phrase in your COPY statements.The maximum block size <strong>for</strong> the copy library depends on the device onwhich your data set resides.Compiling in the z/<strong>OS</strong> UNIX shell:When you compile using the cob2 command, copybooks are included fromthe z/<strong>OS</strong> UNIX file system. text-name, library-name, and literal-1 and literal-2are processed as follows:vvvvvvUser-defined words are folded to uppercase. Literals are not folded.Because UNIX is case sensitive, if your file-name is lowercase or mixedcase, you must specify it as a literal.If text-name is a literal and library-name is omitted, text-name is useddirectly: as a file-name, a relative path name, or an absolute path name(if the first character is /). For example:COPY "MyInc"COPY "x/MyInc"COPY "/u/user1/MyInc"If text-name is a user-defined word, and an environment variable of thatname is defined, the value of the environment variable is used as thename of the file that contains the copybook.If an environment variable of that name is not defined, the copybook issearched <strong>for</strong> under the following names, in this order:1. text-name.cpy2. text-name.CPY3. text-name.cbl4. text-name.CBL5. text-name.cob6. text-name.COB7. text-nameIf library-name is a literal, it is treated as the actual path, relative orabsolute, from which to copy file text-name.If library-name is a user-defined word, it is treated as an environmentvariable. The value of the environment variable is used as the path. Ifthe environment variable is not set, an error occurs.If both library-name and text-name are specified, the compiler <strong>for</strong>ms thepath name <strong>for</strong> the copybook by concatenating library-name and text-namewith a path separator (/) inserted between the two values. For example,suppose you have the following setting <strong>for</strong> COPY MYCOPY OF MYLIB:export MYCOPY=mystuff/today.cpyexport MYLIB=/u/user1These settings result in:/u/user1/mystuff/today.cpy364 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If library-name is an environment variable that identifies the path fromwhich copybooks are to be copied, use an export command to definelibrary-name, as in this example:export COPYLIB=/u/mystuff/copybooksThe name of the environment variable must be uppercase. To specify morethan one copy library, set the environment variable to multiple path namesdelimited by colon (:).If library-name is omitted and text-name is not an absolute path name, thecopybook is searched <strong>for</strong> in this order:1. In the current directory2. In the paths specified on the -I cob2 option3. In the paths specified in the SYSLIB environment variableFor additional in<strong>for</strong>mation about the COPY statement, <strong>for</strong> example, the rules<strong>for</strong> text replacement, see the related reference.DELETE statementThis extended source library statement removes <strong>COBOL</strong> statements fromthe BASIS source program.EJECT statementThis compiler-directing statement specifies that the next source statement isto be printed at the top of the next page.ENTER statementThe statement is treated as a comment.INSERT statementThis library statement adds <strong>COBOL</strong> statements to the BASIS sourceprogram.PROCESS (CBL) statementThis statement, which you place be<strong>for</strong>e the IDENTIFICATION DIVISIONheader of an outermost program, indicates which compiler options are tobe used during compilation of the program.REPLACE statementThis statement is used to replace source program text.SERVICE LABEL statementThis statement is generated by the CICS translator to indicate control flow,and should be used at the resume point <strong>for</strong> a call to CEE3SRP. It is notintended <strong>for</strong> general use.SKIP1/2/3 statementThese statements indicate lines to be skipped in the source listing.TITLE statementThis statement specifies that a title (header) should be printed at the top ofeach page of the source listing.USE statementThe USE statement provides declaratives to specify these elements:v Error-handling procedures: EXCEPTION/ERRORv User label-handling procedures: LABELv Debugging lines and sections: DEBUGGINGChapter 18. Compiler-directing statements 365


RELATED TASKS“Changing the header of a source listing” on page 7“Specifying compiler options under z/<strong>OS</strong>” on page 271“Specifying compiler options under z/<strong>OS</strong> UNIX” on page 284“Setting environment variables under z/<strong>OS</strong> UNIX” on page 283“Eliminating repetitive coding” on page 679RELATED REFERENCES“cob2 syntax and options” on page 287COPY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)366 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 19. DebuggingYou can choose from two approaches to determine the cause of problems inprogram behavior of your application: source-language debugging or interactivedebugging.For source-language debugging, <strong>COBOL</strong> provides several language elements,compiler options, and listing outputs that make debugging easier.If the problem with your program is not easily detected and you do not have adebugger available, you might need to analyze a storage dump of your program.For interactive debugging, you can use Debug Tool. Debug Tool offers theseproductivity enhancements:v Interactive debugging (in full-screen or line mode), or debugging in batch modeDuring an interactive full-screen mode session, you can use Debug Tool’sfull-screen services and session panel windows on a 3270 device to debug yourprogram while it is running.v <strong>COBOL</strong>-like commandsFor each high-level language supported, commands <strong>for</strong> coding actions to betaken at breakpoints are provided in a syntax similar to that programminglanguage.v Mixed-language debuggingYou can debug an application that contains programs written in a differentlanguage. Debug Tool automatically determines the language of the program orsubprogram being run.v <strong>COBOL</strong>-CICS debuggingDebug Tool supports the debugging of CICS applications in both interactive andbatch mode.v Support <strong>for</strong> remote debuggingWorkstation users can use the Debug Perspective of Rational ® Developer <strong>for</strong>System z <strong>for</strong> debugging programs that reside on z/<strong>OS</strong>.RELATED TASKS“Debugging with source language”“Debugging using compiler options” on page 372“Using the debugger” on page 377“Getting listings” on page 377Debug Tool User’s <strong>Guide</strong>RELATED REFERENCESDebug Tool Reference and MessagesLanguage Environment Debugging <strong>Guide</strong> (Formatting and analyzing systemdumps, Debugging example <strong>COBOL</strong> programs)Debugging with source languageYou can use several <strong>COBOL</strong> language features to pinpoint the cause of a failure ina program.© Copyright IBM Corp. 1991, 2009 367


If a failing program is part of a large application that is already in production(precluding source updates), write a small test case to simulate the failing part ofthe program. Code debugging features in the test case to help detect theseproblems:v Errors in program logicv Input-output errorsv Mismatches of data typesv Uninitialized datav Problems with proceduresRELATED TASKS“Tracing program logic”“Finding and handling input-output errors” on page 369“Validating data” on page 369“Finding uninitialized data” on page 370“Generating in<strong>for</strong>mation about procedures” on page 370RELATED REFERENCESSource language debugging (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Tracing program logicTrace the logic of your program by adding DISPLAY statements.For example, if you determine that the problem is in an EVALUATE statement or in aset of nested IF statements, use DISPLAY statements in each path to see the logicflow. If you determine that the calculation of a numeric value is causing theproblem, use DISPLAY statements to check the value of some interim results.If you use explicit scope terminators to end statements in your program, the logicis more apparent and there<strong>for</strong>e easier to trace.To determine whether a particular routine started and finished, you might insertcode like this into your program:DISPLAY "ENTER CHECK PROCEDURE".. (checking procedure routine).DISPLAY "FINISHED CHECK PROCEDURE"After you are sure that the routine works correctly, disable the DISPLAY statementsin one of two ways:vvPut an asterisk in column 7 of each DISPLAY statement line to convert it to acomment line.Put a D in column 7 of each DISPLAY statement to convert it to a comment line.When you want to reactivate these statements, include a WITH DEBUGGING MODEclause in the ENVIRONMENT DIVISION; the D in column 7 is ignored and theDISPLAY statements are implemented.Be<strong>for</strong>e you put the program into production, delete or disable the debugging aidsyou used and recompile the program. The program will run more efficiently anduse less storage.368 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED CONCEPTS“Scope terminators” on page 22RELATED REFERENCESDISPLAY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Finding and handling input-output errorsFile status keys can help you determine whether your program errors are due toinput-output errors occurring on the storage media.To use file status keys in debugging, check <strong>for</strong> a nonzero value in the status keyafter each input-output statement. If the value is nonzero (as reported in an errormessage), look at the coding of the input-output procedures in the program. Youcan also include procedures to correct the error based on the value of the statuskey.If you determine that a problem lies in an input-output procedure, include the USEEXCEPTION/ERROR declarative to help debug the problem. Then, when a file fails toopen, the appropriate EXCEPTION/ERROR declarative is per<strong>for</strong>med. The appropriatedeclarative might be a specific one <strong>for</strong> the file or one provided <strong>for</strong> the openattributes INPUT, OUTPUT, I-O, orEXTEND.Code each USE AFTER STANDARD ERROR statement in a section that follows theDECLARATIVES keyword in the PROCEDURE DIVISION.RELATED TASKS“Coding ERROR declaratives” on page 238“Using file status keys” on page 239RELATED REFERENCESStatus key (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Validating dataIf you suspect that your program is trying to per<strong>for</strong>m arithmetic on nonnumericdata or is receiving the wrong type of data on an input record, use the class test(the class condition) to validate the type of data.You can use the class test to check whether the content of a data item isALPHABETIC, ALPHABETIC-LOWER, ALPHABETIC-UPPER, DBCS, KANJI, orNUMERIC. Ifthedata item is described implicitly or explicitly as USAGE NATIONAL, the class testchecks the national character representation of the characters associated with thespecified character class.RELATED TASKS“Coding conditional expressions” on page 94“Testing <strong>for</strong> valid DBCS characters” on page 143RELATED REFERENCESClass condition (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 19. Debugging 369


Finding uninitialized dataUse an INITIALIZE or SET statement to initialize a table or data item when yoususpect that a problem might be caused by residual data in those fields.If the problem happens intermittently and not always with the same data, it couldbe that a switch was not initialized but is generally set to the right value (0 or 1)by chance. By using a SET statement to ensure that the switch is initialized, youcan determine that the uninitialized switch is the cause of the problem or removeit as a possible cause.RELATED REFERENCESINITIALIZE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SET statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Generating in<strong>for</strong>mation about proceduresGenerate in<strong>for</strong>mation about your program or test case and how it is running bycoding the USE FOR DEBUGGING declarative. This declarative lets you includestatements in the program and indicate when they should be per<strong>for</strong>med when yourun your program.For example, to determine how many times a procedure is run, you could includea debugging procedure in the USE FOR DEBUGGING declarative and use a counter tokeep track of the number of times that control passes to that procedure. You canuse the counter technique to check items such as these:vvHow many times a PERFORM statement runs, and thus whether a particularroutine is being used and whether the control structure is correctHow many times a loop routine runs, and thus whether the loop is executingand whether the number <strong>for</strong> the loop is accurateYou can use debugging lines or debugging statements or both in your program.Debugging lines are statements that are identified by a D in column 7. To makedebugging lines in your program active, code the WITH DEBUGGING MODE clause onthe SOURCE-COMPUTER line in the ENVIRONMENT DIVISION. Otherwise debugging linesare treated as comments.Debugging statements are the statements that are coded in the DECLARATIVES sectionof the PROCEDURE DIVISION. Code each USE FOR DEBUGGING declarative in a separatesection. Code the debugging statements as follows:v Only in a DECLARATIVES section.v Following the header USE FOR DEBUGGING.vOnly in the outermost program; they are not valid in nested programs.Debugging statements are also never triggered by procedures that are containedin nested programs.To use debugging statements in your program, you must include the WITHDEBUGGING MODE clause and use the DEBUG runtime option.Options restrictions:v You cannot use the USE FOR DEBUGGING declarative in a program that youcompile with the THREAD option.370 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vUSE FOR DEBUGGING declaratives, if the WITH DEBUGGING MODE clause has beenspecified, are mutually exclusive with the TEST(HOOK) compiler option. If USE FORDEBUGGING declaratives and the WITH DEBUGGING MODE clause are present, the TESToption is cancelled.“Example: USE FOR DEBUGGING”RELATED REFERENCESSOURCE-COMPUTER paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Debugging lines (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Debugging sections (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)DEBUGGING declarative (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: USE FOR DEBUGGINGThis example shows the kind of statements that are needed to use a DISPLAYstatement and a USE FOR DEBUGGING declarative to test a program.The DISPLAY statement writes in<strong>for</strong>mation to the terminal or to an output data set.The USE FOR DEBUGGING declarative is used with a counter to show how manytimes a routine runs.Environment Division....Data Division....Working-Storage Section.. . . (other entries your program needs)01 Trace-Msg PIC X(30) Value " Trace <strong>for</strong> Procedure-Name : ".01 Total PIC 9(9) Value 1....Procedure Division.Declaratives.Debug-Declaratives Section.Use For Debugging On Some-Routine.Debug-Declaratives-Paragraph.Display Trace-Msg, Debug-Name, Total.End Declaratives.Main-Program Section.. . . (source program statements)Per<strong>for</strong>m Some-Routine.. . . (source program statements)Stop Run.Some-Routine.. . . (whatever statements you need in this paragraph)Add 1 To Total.Some-Routine-End.The DISPLAY statement in the DECLARATIVES SECTION issues this message every timethe procedure Some-Routine runs:Trace For Procedure-Name : Some-Routine 22The number at the end of the message, 22, is the value accumulated in the dataitem Total; it indicates the number of times Some-Routine has run. The statementsin the debugging declarative are per<strong>for</strong>med be<strong>for</strong>e the named procedure runs.You can also use the DISPLAY statement to trace program execution and show theflow through the program. You do this by dropping Total from the DISPLAYstatement and changing the USE FOR DEBUGGING declarative in the DECLARATIVESSECTION to:Chapter 19. Debugging 371


USE FOR DEBUGGING ON ALL PROCEDURES.As a result, a message is displayed be<strong>for</strong>e each nondebugging procedure in theoutermost program runs.Debugging using compiler optionsYou can use certain compiler options to help you find errors in your program, findvarious elements in your program, obtain listings, and prepare your program <strong>for</strong>debugging.You can find the following errors by using compiler options (the options areshown in parentheses):v Syntax errors such as duplicate data-names (NOCOMPILE)v Missing sections (SEQUENCE)v Invalid subscript values (SSRANGE)You can find the following elements in your program by using compiler options:v Error messages and locations of the associated errors (FLAG)v Program entity definitions and references; text-names and library-names fromCOPY or BASIS statements, and the associated data sets or files from whichcopybooks are obtained (XREF)v Data items in the DATA DIVISION (MAP)v Verb references (VBREF)You can get a copy of your source (SOURCE) or a listing of generated code (LIST).You prepare your program <strong>for</strong> debugging by using the TEST compiler option.RELATED TASKS“Finding coding errors”“Finding line sequence problems” on page 373“Checking <strong>for</strong> valid ranges” on page 373“Selecting the level of error to be diagnosed” on page 374“Finding program entity definitions and references” on page 376“Listing data items” on page 376“Getting listings” on page 377RELATED REFERENCESChapter 17, “Compiler options,” on page 301Finding coding errorsUse the NOCOMPILE option to compile conditionally or to only check syntax. Whenused with the SOURCE option, NOCOMPILE produces a listing that will help you findcoding mistakes such as missing definitions, improperly defined data items, andduplicate data-names.If you are compiling in the TSO <strong>for</strong>eground, you can send the messages to yourscreen by using the TERM compiler option and defining your data set as theSYSTERM data set.372 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Checking syntax only: To only check the syntax of your program, and not produceobject code, use NOCOMPILE without a suboption. If you also specify the SOURCEoption, the compiler produces a listing.When you specify NOCOMPILE, several compiler options are suppressed. See therelated reference below about the COMPILE option <strong>for</strong> details.Compiling conditionally: To compile conditionally, use NOCOMPILE(x), where x isone of the severity levels of errors. Your program is compiled if all the errors are ofa lower severity than x. The severity levels that you can use, from highest tolowest, are S (severe), E (error), and W (warning).If an error of level x or higher occurs, the compilation stops and your program isonly checked <strong>for</strong> syntax.RELATED REFERENCES“COMPILE” on page 313Finding line sequence problemsUse the SEQUENCE compiler option to find statements that are out of sequence.Breaks in sequence indicate that a section of a source program was moved ordeleted.When you use SEQUENCE, the compiler checks the source statement numbers todetermine whether they are in ascending sequence. Two asterisks are placed besidestatement numbers that are out of sequence. The total number of these statementsis printed as the first line in the diagnostics after the source listing.RELATED REFERENCES“SEQUENCE” on page 343Checking <strong>for</strong> valid rangesUse the SSRANGE compiler option to check whether addresses fall within properranges.SSRANGE causes the following addresses to be checked:v Subscripted or indexed data references: Is the effective address of the desiredelement within the maximum boundary of the specified table?v Variable-length data references (a reference to a data item that contains anOCCURS DEPENDING ON clause): Is the actual length positive and within themaximum defined length <strong>for</strong> the group data item?v Reference-modified data references: Are the offset and length positive? Is thesum of the offset and length within the maximum length <strong>for</strong> the data item?If the SSRANGE option is in effect, checking is per<strong>for</strong>med at run time if both of thefollowing conditions are true:vvThe <strong>COBOL</strong> statement that contains the indexed, subscripted, variable-length, orreference-modified data item is per<strong>for</strong>med.The CHECK runtime option is ON.If an address is generated outside the range of the data item that contains thereferenced data, an error message is generated and the program stops. TheChapter 19. Debugging 373


message identifies the table or identifier that was referenced and the line numberwhere the error occurred. Additional in<strong>for</strong>mation is provided depending on thetype of reference that caused the error.If all subscripts, indices, and reference modifiers in a given data reference areliterals and they result in a reference outside the data item, the error is diagnosedat compile time regardless of the setting of the SSRANGE option.Per<strong>for</strong>mance consideration: SSRANGE can somewhat degrade per<strong>for</strong>mance becauseof the extra overhead to check each subscripted or indexed item.RELATED REFERENCES“SSRANGE” on page 347“Per<strong>for</strong>mance-related compiler options” on page 672Selecting the level of error to be diagnosedUse the FLAG compiler option to specify the level of error to be diagnosed duringcompilation and to indicate whether error messages are to be embedded in thelisting. Use FLAG(I) or FLAG(I,I) to be notified of all errors.Specify as the first parameter the lowest severity level of the syntax-error messagesto be issued. Optionally specify the second parameter as the lowest level of thesyntax-error messages to be embedded in the source listing. This severity levelmust be the same or higher than the level <strong>for</strong> the first parameter. If you specifyboth parameters, you must also specify the SOURCE compiler option.Table 49. Severity levels of compiler messagesSeverity levelResulting messagesU (unrecoverable)U messages onlyS (severe)All S and U messagesE (error)All E, S, and U messagesW (warning)All W, E, S, and U messagesI (in<strong>for</strong>mational)All messagesWhen you specify the second parameter, each syntax-error message (except aU-level message) is embedded in the source listing at the point where the compilerhad enough in<strong>for</strong>mation to detect that error. All embedded messages (except thoseissued by the library compiler phase) directly follow the statement to which theyrefer. The number of the statement that had the error is also included with themessage. Embedded messages are repeated with the rest of the diagnosticmessages at the end of the source listing.When you specify the N<strong>OS</strong>OURCE compiler option, the syntax-error messages areincluded only at the end of the listing. Messages <strong>for</strong> unrecoverable errors are notembedded in the source listing, because an error of this severity terminates thecompilation.“Example: embedded messages” on page 375RELATED TASKS“Generating a list of compiler messages” on page 279374 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED REFERENCES“Severity codes <strong>for</strong> compiler diagnostic messages” on page 281“Messages and listings <strong>for</strong> compiler-detected errors” on page 280“FLAG” on page 322Example: embedded messagesThe following example shows the embedded messages generated by specifying asecond parameter to the FLAG option. Some messages in the summary apply tomore than one <strong>COBOL</strong> statement.LineID PL SL ----+-*A-1-B--+----2----+----3----+----4----+----5----+----6----+----7-|--+ Map and Cross Reference...090671** /090672** *****************************************************************090673** *** INITIALIZE PARAGRAPH **090674** *** Open files. Accept date, time and <strong>for</strong>mat header lines. **090675** *** Load location-table. **090676** *****************************************************************090677** 100-initialize-paragraph.090678** move spaces to ws-transaction-record IMP 331090679** move spaces to ws-commuter-record IMP 307090680** move zeroes to commuter-zipcode IMP 318090681** move zeroes to commuter-home-phone IMP 319090682** move zeroes to commuter-work-phone IMP 320090683** move zeroes to commuter-update-date IMP 324090684** open input update-transaction-file 204==090684==> IGYPS2052-S An error was found in the definition of file "LOCATION-FILE". Thereference to this file was discarded.090685** location-file 193090686** i-o commuter-file 181090687** output print-file 217090688** if commuter-file-status not = "00" and not = "97" 241090689** 1 display "100-OPEN"090690** 1 move 100 to comp-code 231090691** 1 per<strong>for</strong>m 500-vsam-error 91069090692** 1 per<strong>for</strong>m 900-abnormal-termination 91114090693** end-if090694** accept ws-date from date UND==090694==> IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.090695** move corr ws-date to header-date UND 455==090695==> IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.090696** accept ws-time from time UND==090696==> IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.090697** move corr ws-time to header-time UND 449==090697==> IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.090698** read location-file 193==090698==> IGYPS2053-S An error was found in the definition of file "LOCATION-FILE". Thisinput/output statement was discarded.090699** at end090700** 1 set location-eof to true 256090701** end-read...LineID Message code Message textIGYSC0090-W 1700 sequence errors were found in this program.IGYSC3002-I A severe error was found in the program. The "OPTIMIZE" compiler option was cancelled.160 IGYDS1089-S "ASSIGNN" was invalid. Scanning was resumed at the next area "A" item, level-number, orthe start of the next clause.193 IGYGR1207-S The "ASSIGN" clause was missing or invalid in the "SELECT" entry <strong>for</strong> file "LOCATION-FILE".The file definition was discarded.269 IGYDS1066-S "REDEFINES" object "WS-DATE" was not the immediately preceding level-1 data item.The "REDEFINES" clause was discarded.90602 IGYPS2052-S An error was found in the definition of file "LOCATION-FILE". The reference to this filewas discarded. Same message on line: 9068490694 IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.Same message on line: 9069590696 IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.Same message on line: 9069790698 IGYPS2053-S An error was found in the definition of file "LOCATION-FILE". This input/output statementwas discarded. Same message on line: 90709Messages Total In<strong>for</strong>mational Warning Error Severe TerminatingPrinted: 13 1 1 11* Statistics <strong>for</strong> <strong>COBOL</strong> program IGYTCARA:* Source records = 1735Chapter 19. Debugging 375


* Data Division statements = 287* Procedure Division statements = 471End of compilation 1, program IGYTCARA, highest severity 12.Return code 12Finding program entity definitions and referencesUse the XREF(FULL) compiler option to find out where a data-name,procedure-name, or program-name is defined and referenced. Use it also toproduce a cross-reference of COPY or BASIS statements to the data sets or files fromwhich copybooks were obtained.A sorted cross-reference includes the line number where the data-name,procedure-name, or program-name was defined and the line numbers of allreferences to it.To include only the explicitly referenced data items, use the XREF(SHORT) option.Use both the XREF (either FULL or SHORT) and the SOURCE options to print a modifiedcross-reference to the right of the source listing. This embedded cross-referenceshows the line number where the data-name or procedure-name was defined.For further details, see the related reference below about the XREF compiler option.“Example: XREF output: data-name cross-references” on page 398“Example: XREF output: program-name cross-references” on page 400“Example: XREF output: COPY/BASIS cross-references” on page 400“Example: XREF output: embedded cross-reference” on page 401RELATED TASKS“Getting listings” on page 377RELATED REFERENCES“XREF” on page 358Listing data itemsUse the MAP compiler option to produce a listing of the DATA DIVISION items and allimplicitly declared items. Use the MAP output to locate the contents of a data itemin a system dump.When you use the MAP option, an embedded MAP summary that contains condensedMAP in<strong>for</strong>mation is generated to the right of the <strong>COBOL</strong> source data declaration.When both XREF data and an embedded MAP summary are on the same line, theembedded summary is printed first.You can select or inhibit parts of the MAP listing and embedded MAP summary byusing *CONTROL MAP|NOMAP (or *CBL MAP|NOMAP) statements throughout the source.For example:*CONTROL NOMAP01 A02 B*CONTROL MAP“Example: MAP output” on page 382376 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Getting listings”Using the debuggerRELATED REFERENCES“MAP” on page 328You can use Debug Tool to debug your <strong>Enterprise</strong> <strong>COBOL</strong> programs. Use the TESTcompiler option to prepare your <strong>COBOL</strong> program so that you can step through theexecutable program with the debugger.For remote debugging, the Debug Perspective of Rational Developer <strong>for</strong> System zprovides the client graphical user interface to the debugging in<strong>for</strong>mation providedby the Debug Tool engine running under z/<strong>OS</strong> or UNIX.You can specify the TEST suboption SEPARATE to have the symbolic in<strong>for</strong>mationtables <strong>for</strong> Debug Tool generated in a data set that is separate from your objectmodule. Also, you can enable your <strong>COBOL</strong> program <strong>for</strong> debugging using overlayhooks (production debugging), rather than compiled-in hooks, by compiling with theTEST(NOHOOK,. . .) option. (Compiled-in hooks cause some per<strong>for</strong>mancedegradation even when the runtime TEST option is off.)Specify the NOOPTIMIZE and TEST(HOOK,. . .) compiler options to get the mostdebugging function.For details about which compiler options to use <strong>for</strong> maximum debuggingcapability versus best per<strong>for</strong>mance, see the related reference about the TESTcompiler option.RELATED TASKS“Defining the debug data set (SYSDEBUG)” on page 270Debug Tool User’s <strong>Guide</strong> (Preparing your program <strong>for</strong> debugging)Getting listingsRELATED REFERENCES“TEST” on page 349Get the in<strong>for</strong>mation that you need <strong>for</strong> debugging by requesting the appropriatecompiler listing with the use of compiler options.Attention: The listings produced by the compiler are not a programming interfaceand are subject to change.Table 50. Using compiler options to get listingsUse Listing Contents Compiler optionTo check a list of theoptions in effect <strong>for</strong> theprogram, statistics aboutthe content of the program,and diagnostic messagesabout the compilationShort listing v List of options in effect<strong>for</strong> the programvvStatistics about thecontent of the programDiagnostic messagesabout the compilation 1N<strong>OS</strong>OURCE, NOXREF, NOVBREF,NOMAP, NOOFFSET,NOLISTChapter 19. Debugging 377


Table 50. Using compiler options to get listings (continued)Use Listing Contents Compiler optionTo aid in testing anddebugging your program;to have a record after theprogram has beendebuggedSource listing Copy of your source “SOURCE” on page 344To find certain data itemsin a storage dump; to seethe final storage allocationafter reentrancy oroptimization has beenaccounted <strong>for</strong>; to see whereprograms are defined andcheck their attributesMap of DATA DIVISIONitemsAll DATA DIVISION itemsand all implicitly declareditemsEmbedded map summary(in the right margin of thelisting <strong>for</strong> lines in the DATADIVISION that contain datadeclarations)“MAP” on page 328 2To find where a name isdefined, referenced, ormodified; to determine thecontext (such as whether averb was used in a PERFORMblock) in which a procedureis referenced; to determinethe data set or file fromwhich a copybook wasobtainedSorted cross-referencelisting of names; sortedcross-reference listing ofCOPY/BASIS statements andcopybook data sets or filesNested program map (if theprogram contains nestedprograms)Data-names,procedure-names, andprogram-names; referencesto these namesCOPY/BASIS text-names andlibrary names, and the datasets or files from whichassociated copybooks wereobtained“XREF” on page 358 2,3To find the failing verb in aprogram or the address instorage of a data item thatwas moved during theprogramTo verify you still have avalid logic path after youmove or add PROCEDUREDIVISION sectionsTo find an instance of acertain verbEmbedded modifiedcross-reference providesline numbers wheredata-names andprocedure-names weredefinedPROCEDURE DIVISION code Generated code “LIST” on page 328 2,4produced by the compiler 3and assembler codeCondensed PROCEDUREDIVISION listingAlphabetic listing of verbsCondensed verb listing,global tables,WORKING-STORAGEin<strong>for</strong>mation, and literalsEach verb used, number oftimes each verb was used,line numbers where eachverb was used“OFFSET” on page 335“VBREF” on page 356378 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 50. Using compiler options to get listings (continued)Use Listing Contents Compiler option1. To eliminate messages, turn off the options (such as FLAG) that govern the level of compile diagnosticin<strong>for</strong>mation.2. To use your line numbers in the compiled program, use the NUMBER compiler option. The compiler checks thesequence of your source statement line numbers in columns 1 through 6 as the statements are read in. When itfinds a line number out of sequence, the compiler assigns to it a number with a value one higher than the linenumber of the preceding statement. The new value is flagged with two asterisks. A diagnostic messageindicating an out-of-sequence error is included in the compilation listing.3. The context of the procedure reference is indicated by the characters preceding the line number.4. You can control the listing of generated object code by selectively placing *CONTROL LIST and *CONTROL NOLIST(or equivalently, *CBL LIST and *CBL NOLIST) statements in your source. Note that the *CONTROL statement isdifferent than the PROCESS (or CBL) statement.The output is generated if:vvYou specify the COMPILE option (or the NOCOMPILE(x) option is in effect and an error level x or higher does notoccur).You do not specify the OFFSET option. OFFSET and LIST are mutually exclusive options with OFFSET takingprecedence.“Example: short listing”“Example: SOURCE and NUMBER output” on page 381“Example: MAP output” on page 382“Example: embedded map summary” on page 383“Example: nested program map” on page 386“Example: XREF output: data-name cross-references” on page 398“Example: XREF output: program-name cross-references” on page 400“Example: XREF output: COPY/BASIS cross-references” on page 400“Example: XREF output: embedded cross-reference” on page 401“Example: OFFSET compiler output” on page 402“Example: VBREF compiler output” on page 403RELATED TASKS“Generating a list of compiler messages” on page 279“Reading LIST output” on page 387Language Environment Debugging <strong>Guide</strong> (Debugging <strong>COBOL</strong> programs)RELATED REFERENCES“Messages and listings <strong>for</strong> compiler-detected errors” on page 280Example: short listingThe parenthetical numbers shown in the listing below correspond to numberedexplanations that follow the listing. For illustrative purposes, some errors thatcause diagnostic messages were deliberately introduced.Invocation parameters: (1)OPTFILEPROCESS(CBL) statements: (2)CBL NODECKCBL NOADV,NODYN,NONAME,NONUMBER,QUOTE,SEQ,DUMPCBL N<strong>OS</strong>OURCE, NOXREF, NOVBREF, NOMAP, NOOFFSET, NOLISTOptions from SYSOPTF: (3)C,NODU,FLAG(I),X,MAP,NOLIST,RENT,OPT,SSRTEST(NOHOOK,SEP) TRUNC(OPT)Options in effect: (4)NOADATANOADVQUOTEChapter 19. Debugging 379


|ARITH(COMPAT)NOAWONOBLOCK0BUFSIZE(4096)NOCICSCODEPAGE(1140)COMPILENOCURRENCYDATA(31)NODATEPROCDBCSNODECKNODIAGTRUNCNODLLDUMPNODYNAMNOEXITNOEXPORTALLNOFASTSRTFLAG(I)NOFLAGSTDINTDATE(ANSI)LANGUAGE(EN)NOLIBLINECOUNT(60)NOLISTNOMAPNOMDECKNONAMENSYMBOL(NATIONAL)NONUMBERNUMPROC(NOPFD)OBJECTNOOFFSETOPTIMIZE(STD)OUTDD(SYSOUT)PGMNAME(COMPAT)RENTRMODE(AUTO)SEQUENCESIZE(MAX)N<strong>OS</strong>OURCESPACE(1)N<strong>OS</strong>QLSQLCCSIDSSRANGENOTERMTEST(NOHOOK,SEPARATE,NOEJPD)NOTHREADTRUNC(OPT)NOVBREFNOWORDXMLPARSE(XMLSS)NOXREFYEARWINDOW(1900)ZWBLineID Message code Message text (5)IGYDS0139-W Diagnostic messages were issued during processing of compiler options.These messages are located at the beginning of the listing.IGYSC0090-W 3 sequence errors were found in this program.160 IGYDS1089-S "ASSIGNN" was invalid. Scanning was resumed at the next area "A" item,level-number,or the start of the next clause.193 IGYGR1207-S The "ASSIGN" clause was missing or invalid in the "SELECT" entry <strong>for</strong> file"LOCATION-FILE". The file definition was discarded.269 IGYDS1066-S "REDEFINES" object "WS-DATE" was not the immediately preceding level-1 data item.The "REDEFINES" clause was discarded.901 IGYPS2052-S An error was found in the definition of file "LOCATION-FILE". The reference tothis file was discarded. Same message on line: 983993 IGYPS2121-S "WS-DATE" was not defined as a data-name. The statement was discarded.Same message on line: 994995 IGYPS2121-S "WS-TIME" was not defined as a data-name. The statement was discarded.Same message on line: 996997 IGYPS2053-S An error was found in the definition of file "LOCATION-FILE". This input/outputstatement was discarded. Same message on line: 1008Messages Total In<strong>for</strong>mational Warning Error Severe Terminating (6)Printed: 14 3 11* Statistics <strong>for</strong> <strong>COBOL</strong> program IGYTCARA: (7)* Source records = 1735* Data Division statements = 287* Procedure Division statements = 471End of compilation 1, program IGYTCARA, highest severity 12. (8)Return code 12380 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


(1) Message about options passed to the compiler at compiler invocation. Thismessage does not appear if no options were passed.OPTFILERequests options from a SYSOPTF data set.(2) Options coded in the PROCESS (or CBL) statement.NOOFFSETSuppresses a condensed listing of the PROCEDURE DIVISION.NOMAP Suppresses a map report of the items defined in the DATA DIVISION.(3) Options obtained from the SYSOPTF data set (because the OPTFILEcompiler option was specified).NOLIST Suppresses an assembler-language expansion of the source code.TEST(NOHOOK,SEP)The program was compiled <strong>for</strong> use with Debug Tool or <strong>for</strong>matteddumps.(4) Status of options at the start of this compilation.(5) Program diagnostics. The first message refers you to any library phasediagnostics. Diagnostics <strong>for</strong> the library phase are presented at thebeginning of the listing.(6) Count of diagnostic messages in this program, grouped by severity level.(7) Program statistics <strong>for</strong> the program IGYTCARA.(8) Program statistics <strong>for</strong> the compilation unit. When you per<strong>for</strong>m a batchcompilation, the return code is the highest message severity level <strong>for</strong> theentire compilation.Example: SOURCE and NUMBER outputIn the portion of the listing shown below, the programmer numbered two of thestatements out of sequence. The note numbers in the listing correspond tonumbered explanations that follow the listing.(1)LineID PL SL ----+-*A-1-B--+----2----+----3----+----4----+----5----+----6----+----7-|--+----8 Cross-Reference(2) (3) (4)087000**************************************************************** *087100*** D O MAIN LOGIC * *087200*** * *087300*** Initialization. Read and process update transactions until * *087400*** EOE. Close files and stop run. * *087500**************************************************************** *087600 procedure division.087700 000-do-main-logic.087800 display "PROGRAM IGYTCARA - Beginning"087900 per<strong>for</strong>m 050-create-vsam-master-file. 90633088150 display "per<strong>for</strong>m 050-create-vsam-master finished".088151** 088125 per<strong>for</strong>m 100-initialize-paragraph 90677088200 display "per<strong>for</strong>m 100-initialize-paragraph finished"088300 read update-transaction-file into ws-transaction-record 204 331088400 at end1 088500 set transaction-eof to true 254088600 end-read088700 display "READ completed"088800 per<strong>for</strong>m until transaction-eof 2541 088900 display "inside per<strong>for</strong>m until loop"1 089000 per<strong>for</strong>m 200-edit-update-transaction 907331 089100 display "After per<strong>for</strong>m 200-edit "1 089200 if no-errors 3652 089300 per<strong>for</strong>m 300-update-commuter-record 908422 089400 display "After per<strong>for</strong>m 300-update "1 089650 else089651** 2 089600 per<strong>for</strong>m 400-print-transaction-errors 909952 089700 display "After per<strong>for</strong>m 400-errors "1 089800 end-if1 089900 per<strong>for</strong>m 410-re-initialize-fields 91056Chapter 19. Debugging 381


1 090000 display "After per<strong>for</strong>m 410-reinitialize"1 090100 read update-transaction-file into ws-transaction-record 204 3311 090200 at end2 090300 set transaction-eof to true 2541 090400 end-read1 090500 display "After '2nd READ' "090600 end-per<strong>for</strong>m(1) Scale line, which labels Area A, Area B, and source-code column numbers(2) Source-code line number assigned by the compiler(3) Program (PL) and statement (SL) nesting level(4) Columns 1 through 6 of program (the sequence number area)Example: MAP outputThe following example shows output from the MAP option. The numbers used inthe explanation below correspond to the numbers that annotate the output.Data Division Map(1)Data Definition Attribute codes (rightmost column) have the following meanings:D = Object of OCCURS DEPENDING G = GLOBAL S = Spanned fileE = EXTERNAL O = Has OCCURS clause U = Undefined <strong>for</strong>mat fileF = Fixed-length file OG= Group has own length definition V = Variable-length fileFB= Fixed-length blocked file R = REDEFINES VB= Variable-length blocked file(2) (3) (4) (5) (6) (7) (8) (9) (10)Source Hierarchy and Base Hex-Displacement Asmblr Data Data DefLineID Data Name Locator Blk Structure Definition Data Type Attributes4 PROGRAM-ID IGYTCARA-----------------------------------------------------------------------------------*181 FD COMMUTER-FILE VSAM F183 1 COMMUTER-RECORD BLF=00000 000 DS 0CL80 Group184 2 COMMUTER-KEY BLF=00000 000 0 000 000 DS 16C Display185 2 FILLER BLF=00000 010 0 000 010 DS 64C Display187 FD COMMUTER-FILE-MST VSAM F189 1 COMMUTER-RECORD-MST BLF=00001 000 DS 0CL80 Group190 2 COMMUTER-KEY-MST BLF=00001 000 0 000 000 DS 16C Display191 2 FILLER BLF=00001 010 0 000 010 DS 64C Display193 FD LOCATION-FILE QSAM FB198 1 LOCATION-RECORD BLF=00002 000 DS 0CL80 Group199 2 LOC-CODE BLF=00002 000 0 000 000 DS 2C Display200 2 LOC-DESCRIPTION BLF=00002 002 0 000 002 DS 20C Display201 2 FILLER BLF=00002 016 0 000 016 DS 58C Display204 FD UPDATE-TRANSACTION-FILE QSAM FB209 1 UPDATE-TRANSACTION-RECORD BLF=00003 000 DS 80C Display217 FD PRINT-FILE QSAM FB222 1 PRINT-RECORD BLF=00004 000 DS 121C Display229 1 WORKING-STORAGE-FOR-IGYCARA BLW=00000 000 DS 1C Display231 77 COMP-CODE BLW=00000 008 DS 2C Binary232 77 WS-TYPE BLW=00000 010 DS 3C Display235 1 I-F-STATUS-AREA BLW=00000 018 DS 0CL2 Group236 2 I-F-FILE-STATUS BLW=00000 018 0 000 000 DS 2C Display237 88 I-O-SUCCESSFUL240 1 STATUS-AREA BLW=00000 020 DS 0CL8 Group241 2 COMMUTER-FILE-STATUS BLW=00000 020 0 000 000 DS 2C Display242 88 I-O-OKAY243 2 COMMUTER-VSAM-STATUS BLW=00000 022 0 000 002 DS 0CL6 Group244 3 VSAM-R15-RETURN-CODE BLW=00000 022 0 000 002 DS 2C Binary245 77 UNUSED-DATA-ITEM BLW=XXXXX 022 DS 10C Display (11)(1) Explanations of the data definition attribute codes.(2) Source line number where the data item was defined.(3) Level definition or number. The compiler generates this number in thefollowing way:v First level of any hierarchy is always 01. Increase 1 <strong>for</strong> each level (anyitem you coded as level 02 through 49).v Level-numbers 66, 77, and 88, and the indicators FD and SD, are notchanged.(4) Data-name that is used in the source module in source order.(5) Base locator used <strong>for</strong> this data item.(6) Hexadecimal displacement from the beginning of the base locator value.382 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


(7) Hexadecimal displacement from the beginning of the containing structure.(8) Pseudoassembler code showing how the data is defined. When a structurecontains variable-length fields, the maximum length of the structure isshown.(9) Data type and usage.(10) Data definition attribute codes. The definitions are explained at the top ofthe DATA DIVISION map.(11) UNUSED-DATA-ITEM was not referenced in the PROCEDURE DIVISION. BecauseOPTIMIZE(FULL) was specified, UNUSED-DATA-ITEM was deleted, resulting inthe base locator being set to XXXXX.“Example: embedded map summary”“Example: nested program map” on page 386RELATED REFERENCES“Terms used in MAP output” on page 384“Symbols used in LIST and MAP output” on page 385Example: embedded map summaryThe following example shows an embedded map summary from specifying the MAPoption. The summary appears in the right margin of the listing <strong>for</strong> lines in the DATADIVISION that contain data declarations.000002 Identification Division.000003000004 Program-id. IGYTCARA....000177 Data division.000178 File section.000179000180000181 FD COMMUTER-FILE000182 record 80 characters. (1) (2) (3) (4)...000222 01 print-record pic x(121). BLF=00004+000 121C...000228 Working-storage section.000229 01 Working-storage-<strong>for</strong>-IGYCARA pic x. BLW=00000+000 1C000230000231 77 comp-code pic S9999 comp. BLW=00000+008 2C000232 77 ws-type pic x(3) value spaces. BLW=00000+010 3C000233000234000235 01 i-f-status-area. BLW=00000+018 0CL2000236 05 i-f-file-status pic x(2). BLW=00000+018,0000000 2C000237 88 i-o-successful value zeroes.000238000239000240 01 status-area. BLW=00000+020 0CL8000241 05 commuter-file-status pic x(2). BLW=00000+020,0000000 2C000242 88 i-o-okay value zeroes.000243 05 commuter-vsam-status. BLW=00000+022,0000002 0CL6000244 10 vsam-r15-return-code pic 9(2) comp. BLW=00000+022,0000002 2C000245 10 vsam-function-code pic 9(1) comp. BLW=00000+024,0000004 2C000246 10 vsam-feedback-code pic 9(3) comp. BLW=00000+026,0000006 2C000247000248 77 update-file-status pic xx. BLW=00000+028 2C000249 77 loccode-file-status pic xx. BLW=00000+030 2C000250 77 updprint-file-status pic xx. BLW=00000+038 2C000251000252 01 flags. BLW=00000+040 0CL3000253 05 transaction-eof-flag pic x value space. BLW=00000+040,0000000 1C000254 88 transaction-eof value "Y".000255 05 location-eof-flag pic x value space. BLW=00000+041,0000001 1C000256 88 location-eof value "Y".000257 05 transaction-match-flag pic x. BLW=00000+042,0000002 1C...000876 procedure division.000877 000-do-main-logic.000878 display "PROGRAM IGYTCARA - Beginning"000879 per<strong>for</strong>m 050-create-vsam-master-file.(1) Base locator used <strong>for</strong> this data itemChapter 19. Debugging 383


(2) Hexadecimal displacement from the beginning of the base locator value(3) Hexadecimal displacement from the beginning of the containing structure(4) Pseudoassembler code showing how the data is definedRELATED REFERENCES“Symbols used in LIST and MAP output” on page 385Terms used in MAP outputThe following table describes the terms used in the listings produced by the MAPcompiler option.Table 51. Terms used in MAP outputTerm Definition DescriptionALPHABETIC DS nC Alphabetic data item (PICTURE A)ALPHA-EDIT DS nC Alphabetic-edited data itemAN-EDIT DS nC Alphanumeric-edited data itemBINARYDS 1H 2 ,1F 2 ,2F 2 ,2C,4C,or8CBinary data item (USAGE BINARY, COMPUTATIONAL, orCOMPUTATIONAL-5)COMP-1 DS 4C Single-precision internal floating-point data item (USAGECOMPUTATIONAL-1)COMP-2 DS 8C Double-precision internal floating-point data item (USAGECOMPUTATIONAL-2)DBCS DS nC DBCS data item (USAGE DISPLAY-1)DBCS-EDIT DS nC DBCS-edited data item (USAGE DISPLAY-1)DISP-FLOAT DS nC Display floating-point data item (USAGE DISPLAY)DISPLAY DS nC Alphanumeric data item (PICTURE X)DISP-NUM DS nC Zoned decimal data item (USAGE DISPLAY)DISP-NUM-EDIT DS nC Numeric-edited data item (USAGE DISPLAY)FDFile definitionFUNCTION-PTR DS nC Function pointer (USAGE FUNCTION-POINTER)GROUP DS 0CLn 1 Fixed-length alphanumeric group data itemGRP-VARLEN DS 0CLn 1 Variable-length alphanumeric group data itemINDEX DS nC Index data item (USAGE INDEX)INDEX-NAME DS nC Index nameNATIONAL DS nC Category national data item (USAGE NATIONAL)NAT-EDIT DS nC National-edited data item (USAGE NATIONAL)NAT-FLOAT DS nC National floating-point data item (USAGE NATIONAL)NAT-GROUP DS 0CLn 1 National group (GROUP-USAGE NATIONAL)NAT-GRP-VARLEN DS 0CLn 1 National variable-length group (GROUP-USAGE NATIONAL)NAT-NUM DS nC National decimal data item (USAGE NATIONAL)NAT-NUM-EDIT DS nC National numeric-edited data item (USAGE NATIONAL)OBJECT-REF DS nC Object-reference data item (USAGE OBJECT REFERENCE)PACKED-DEC DS nP Internal decimal data item (USAGE PACKED-DECIMAL orCOMPUTATIONAL-3)POINTER DS nC Pointer data item (USAGE POINTER)384 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 51. Terms used in MAP output (continued)Term Definition DescriptionPROCEDURE-PTR DS nC Procedure pointer (USAGE PROCEDURE-POINTER)SDSort file definitionVSAM, QSAM,File processing methodLINESEQ1-49, 77 Level-numbers <strong>for</strong> data descriptions66 Level-number <strong>for</strong> RENAMES88 Level-number <strong>for</strong> condition-names1. n is the size in bytes <strong>for</strong> fixed-length groups and the maximum size in bytes <strong>for</strong> variable-length groups.2. If the SYNCHRONIZED clause appears, these fields are used.Symbols used in LIST and MAP outputThe following table describes the symbols used in the listings produced by theLIST or MAP option.Table 52. Symbols used in LIST and MAP outputSymbolDefinitionAPBdisp=n 1ALL subscript parameter block displacementAVN=n 1Variable name cell <strong>for</strong> ALTER statementBL=n 1Base locator <strong>for</strong> special registersBLA=n 1 Base locator <strong>for</strong> alphanumeric temporaries 4BLF=n 1Base locator <strong>for</strong> filesBLK=n 1Base locator <strong>for</strong> LOCAL-STORAGEBLL=n 1Base locator <strong>for</strong> LINKAGE SECTIONBLM=n 1Base locator <strong>for</strong> factory dataBLO=n 1Base locator <strong>for</strong> object instance dataBLS=n 1Base locator <strong>for</strong> sort itemsBLT=n 1Base locator <strong>for</strong> XML-TEXT and XML-NTEXTBLV=n 1Base locator <strong>for</strong> variably located dataBLW=n 1Base locator <strong>for</strong> WORKING-STORAGEBLX=n 1Base locator <strong>for</strong> external dataCBL=n 1Base locator <strong>for</strong> constant global table (CGT)CLLE=@=n 1Load list entry address in TGTCLO=n 1Class object cellDOV=n 1DSA overflow cellEVALUATE=n 1Evaluate Boolean cellFCB=n 1File control block (FCB) addressGN=n(hhhhh) 2.Generated procedure-name and its offset in hexadecimalIDX=n 1Base locator <strong>for</strong> index-namesIDX=n 1Index cell numberILS=n 1Index cell <strong>for</strong> LOCAL-STORAGE table or instance variableOD<strong>OS</strong>AVE=n 1ODO save cell numberChapter 19. Debugging 385


Table 52. Symbols used in LIST and MAP output (continued)SymbolDefinitionOPT=nnnn 3Optimizer temporary storage cellPBL=n 1Base locator <strong>for</strong> procedure codePFM=n 1PERFORM n times cellsPGMLIT AT + nnnn 3Displacement <strong>for</strong> program literal from beginning of literal poolPSV=n 1Per<strong>for</strong>m save cell numberPVN=n 1Variable name cell <strong>for</strong> PERFORM statementRBKST=n 1Register backstore cellSFCB=n 1Secondary file control block <strong>for</strong> external fileSYSLIT AT + nnnn 3Displacement <strong>for</strong> system literal from beginning of system literal poolTGT FDMP TEST INFO. AREA + FDUMP/TEST in<strong>for</strong>mation areannnn 3TGTFIXD + nnnn 3Offset from beginning of fixed portion of task global table (TGT)TOV=n 1TGT overflow cell numberTS1=aaaa Temporary storage cell number in subpool 1TS2=aaaa Temporary storage cell number in subpool 2TS3=aaaa Temporary storage cell number in subpool 3TS4=aaaa Temporary storage cell number in subpool 4V(routine name)Assembler VCON <strong>for</strong> external routineVLC=n 1Variable-length name cell number (ODO)VNI=n 1Variable name initializationWHEN=n 1Evaluate WHEN cell number1. n is the number of the entry. For base locators, it can also be XXXXX, indicating a data item that was deleted byOPTIMIZE(FULL) processing.2. (hhhhh) is the program offset in hexadecimal.3. nnnn is the offset in decimal from the beginning of the entry.4. Alphanumeric temporaries are temporary data values used in processing alphanumeric intrinsic function andalphanumeric EVALUATE statement subjects.Example: nested program mapThis example shows a map of nested procedures produced by specifying the MAPcompiler option. Numbers in parentheses refer to notes that follow the example.Nested Program MapProgram Attribute codes (rightmost column) have the following meanings:C = COMMONI = INITIAL (1)U = PROCEDURE DIVISION USING... (5)Source NestingProgramLineID Level Program Name from PROGRAM-ID paragraph Attributes2 0 NESTMAIN. ..................U120 1 (4) SUBPRO1 ..................I,C,U(2)199 2 NESTED1 .................I,C,U253 1 SUBPRO2 ..................U335 2 NESTED2 .................C,U(3)(1) Explanations of the program attribute codes386 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


(2) Source line number where the program was defined(3) Depth of program nesting(4) Program-name(5) Program attribute codesReading LIST outputParts of the LIST compiler output might be useful to you <strong>for</strong> debugging a program.The LIST compiler option produces seven pieces of output:v An assembler listing of the initialization code <strong>for</strong> the program (programsignature in<strong>for</strong>mation bytes) from which you can verify program characteristicssuch as these:– Compiler options in effect– Types of data items present– Verbs used in the PROCEDURE DIVISIONv An assembler listing of the source code <strong>for</strong> the programFrom the address in storage of the instruction that was executing when an abendoccurred, you can find the <strong>COBOL</strong> verb that corresponds to that instruction.After you find the address of the failing instruction, go to the assembler listingand find the verb <strong>for</strong> which that instruction was generated.v Location of compiler-generated tables in the object modulev A map of the task global table (TGT), including in<strong>for</strong>mation about the programglobal table (PGT) and constant global table (CGT)Use the TGT to find in<strong>for</strong>mation about the environment in which your programis running.v In<strong>for</strong>mation about the location and size of WORKING-STORAGE and control blocksYou can use the WORKING-STORAGE portion of LIST output to find the location ofdata items defined in WORKING-STORAGE. (The beginning location ofWORKING-STORAGE is not shown <strong>for</strong> programs compiled with the RENT option.)v Map of the dynamic save area (DSA)The map of the DSA (also known as the stack frame) contains in<strong>for</strong>mation aboutthe contents of the storage acquired each time a separately compiled procedureis entered.v In<strong>for</strong>mation about the location of literals and code <strong>for</strong> dynamic storage usageYou do not need to be able to program in assembler language to understand theLIST output. The comments that accompany most of the assembler code provideyou with a conceptual understanding of the functions per<strong>for</strong>med by the code.“Example: program initialization code” on page 388“Example: assembler code generated from source code” on page 395“Example: TGT memory map” on page 396“Example: DSA memory map” on page 398“Example: location and size of WORKING-STORAGE” on page 398RELATED REFERENCES“Signature in<strong>for</strong>mation bytes: compiler options” on page 389“Signature in<strong>for</strong>mation bytes: DATA DIVISION” on page 391“Signature in<strong>for</strong>mation bytes: ENVIRONMENT DIVISION” on page 392“Signature in<strong>for</strong>mation bytes: PROCEDURE DIVISION verbs” on page 392Chapter 19. Debugging 387


“Signature in<strong>for</strong>mation bytes: more PROCEDURE DIVISION items” on page 394Language Environment <strong>Programming</strong> <strong>Guide</strong> (Stack storage overview)Example: program initialization codeA listing of the program initialization code gives you in<strong>for</strong>mation about thecharacteristics of the <strong>COBOL</strong> source program. Interpret the program signaturein<strong>for</strong>mation bytes to verify characteristics of your program.(1) (2) (3) (4)000000 IMIN DS 0H PROGRAM:IMINUSING *,15000000 47F0 F028 B 40(,15) BYPASS CONSTANTS. BRANCH TO @STM000004 00 DC AL1(0) ZERO NAME LENGTH FOR DUMPS000005 C3C5C5 DC CL3'CEE' CEE EYE CATCHER (5)000008 00000110 DC X'00000110' STACK FRAME SIZE00000C 00000014 DC A(@PPA1-IMIN) OFFSET TO PPA1 FROM PRIMARY ENTRY000010 47F0 F001 B 1(,15) RESERVED000014 @PPA1 DS 0H PPA1 STARTS HERE000014 98 DC X'98' OFFSET TO LENGTH OF NAME FROM PPA1000015 CE DC X'CE' CEL SIGNATURE000016 AC DC X'AC' CEL FLAGS: '10101100'B000017 00 DC X'00' MEMBER FLAGS FOR <strong>COBOL</strong>000018 000000B6 DC A(@PPA2) ADDRESS OF PPA200001C 00000000 DC F'0' OFFSET TO THE BDI (NONE)000020 00000000 DC F'0' ADDRESS OF ENTRY POINT DESCRIPTORS000024 0000 DC X'0000' RESERVED000026 00 DC X'00' DSA FPR 8-15 SAVE AREA OFFSET/16000027 00 DC X'00' DSA FPR 8-15 SAVE AREA BIT MASK000028 @STM DS 0H STM STARTS HERE000028 90EC D00C STM 14,12,12(13) @STM: SAVE CALLER'S REGISTERS00002C 4110 F038 LA 1,56(,15) GET ADDRESS OF PARMLIST INTO R1000030 98EF F04C LM 14,15,76(15) LOAD ADDRESSES FROM @BRVAL000034 07FF BR 15 DO ANY NECESSARY INITIALIZATION000036 0000 DC AL2'0' AVAILABLE HALF-WORD000038 @MAINENT DS 0H PRIMARY ENTRY POINT ADDRESS000038 00000000 DC A(IMIN) @PARMS: 1) PRIMARY ENTRY POINT ADDRESS00003C 00000000 DC AL4'0' 2) Available000040 000003C0 DC A(DAB) 3) DAB ADDRESS (6)000044 000000AE DC A(@EPNAM) 4) ENTRY POINT NAME ADDRESS000048 00000000 DC A(IMIN) 5) CURRENT ENTRY POINT ADDRESS00004C 00000272 DC A(START) @BRVAL: 6) PROCEDURE CODE ADDRESS000050 00000000 DC V(IGZCBSO) 7) INITIALIZATION ROUTINE000054 000000CA DC A(@CEEPARM) 8) ADDRESS OF PARM LIST FOR CEEINT000058 00104001 DC X'00104001' DSA WORD 0 CONSTANT00005C 00000000 DC AL4'0' AVAILABLE WORD000060 00000000 DC AL4'0' AVAILABLE WORD000064 00000000 DC AL4'0' AVAILABLE WORD000068 F2F0F0F9 DC CL4'2009' @TIMEVRS: YEAR OF COMPILATION (7)00006C F0F9F3F0 DC CL4'0930' MONTH/DAY OF COMPILATION (8)000070 F1F0F4F8 DC CL4'1048' HOURS/MINUTES OF COMPILATION (9)000074 F1F6 DC CL2'16' SECONDS FOR COMPILATION DATE000076 F0F4F0F2F0F0 DC CL6'040200' VERSION/RELEASE/MOD LEVEL OF PROD (10)00007C 0474 DC X'0474' UNSIGNED BINARY CODE PAGE CCSID VALUE (11)00007E 0000 DC AL2'0' AVAILABLE HALF-WORD000080 0000 DC X'0000' INFO. BYTES 28-29 (12)000082 076C DC X'076C' SIGNED BINARY YEARWINDOW OPTION VALUE000084 A0487C4C2000 DC X'A0487C4C2000' INFO. BYTES 1-600008A 000000080000 DC X'000000080000' INFO. BYTES 7-12000090 000000000800 DC X'000000000800' INFO. BYTES 13-18 (12)000096 0000000000 DC X'0000000000' INFO. BYTES 19-2300009B 00 DC X'00' <strong>COBOL</strong> SIGNATURE LEVEL00009C 00000001 DC X'00000001' # DATA DIVISION STATEMENTS (13)0000A0 00000003 DC X'00000003' # PROCEDURE DIVISION STATEMENTS (14)0000A4 000080 DC X'000080' INFO. BYTES 24-26 (12)0000A7 00 DC X'00' INFO. BYTE 270000A8 40404040 DC C' ' USER LEVEL INFO (LVLINFO) (15)0000AC 0004 DC X'0004' LENGTH OF PROGRAM NAME0000AE @EPNAM DS 0H ENTRY POINT NAME0000AE C9D4C9D540404040 DC C'IMIN ' PROGRAM NAME (16)0000B6 @PPA2 DS 0H PPA2 STARTS HERE0000B6 05 DC X'05' CEL MEMBER IDENTIFIER0000B7 00 DC X'00' CEL MEMBER SUB-IDENTIFIER0000B8 00 DC X'00' CEL MEMBER DEFINED BYTE0000B9 01 DC X'01' CONTROL LEVEL OF PROLOG0000BA 00000000 DC V(CEESTART) VCON FOR LOAD MODULE0000BE 00000000 DC F'0' OFFSET TO THE CDI (NONE)0000C2 FFFFFFB2 DC A(@TIMEVRS-@PPA2) OFFSET TO TIMESTAMP/VERSION INFO0000C6 00000000 DC A(IMIN) ADDRESS OF CU PRIMARY ENTRY POINT0000CA @CEEPARM DS 0H PARM LIST FOR CEEINT0000CA 00000038 DC A(@MAINENT) POINTER TO PRIMARY ENTRY PT ADDR0000CE 00000008 DC A(@PARMCEE-@CEEPARM) OFFSET TO PARAMETERS FOR CEEINT0000D2 @PARMCEE DS 0H PARAMETERS FOR CEEINT0000D2 00000006 DC F'6' 1) NUMBER OF ENTRIES IN PARM LIST0000D6 00000038 DC A(@MAINENT) 2) POINTER TO PRIMARY ENTRY PT ADDR0000DA 00000000 DC V(CEESTART) 3) ADDRESS OF CEESTART388 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


0000DE 00000000 DC V(CEEBETBL) 4) ADDRESS OF CEEBETBL0000E2 00000005 DC F'5' 5) CEL MEMBER IDENTIFIER0000E6 00000000 DC F'0' 6) FOR CEL MEMBER USE...(1) Offset from the start of the <strong>COBOL</strong> program.(2) Hexadecimal representation of assembler instructions.(3) Pseudoassembler code generated <strong>for</strong> the <strong>COBOL</strong> program.(4) Comments that explain the assembler code.(5) Eye-catcher indicating that the <strong>COBOL</strong> compiler is LanguageEnvironment-enabled.(6) Address of the task global table (TGT), or the address of the dynamicaccess block (DAB) if the program is reentrant.(7) Four-digit year when the program was compiled.(8) Month and the day when the program was compiled.(9) Time when the program was compiled.(10) Version, release, and modification level of the <strong>COBOL</strong> compiler used tocompile this program (each represented in two digits).(11) Code page CCSID value (from CODEPAGE compiler option).(12) Program signature in<strong>for</strong>mation bytes. These provide in<strong>for</strong>mation aboutthese elements of the program:v Compiler optionsv DATA DIVISIONv ENVIRONMENT DIVISIONv PROCEDURE DIVISION(13) Number of statements in the DATA DIVISION.(14) Number of statements in the PROCEDURE DIVISION.(15) 4-byte user-controled level in<strong>for</strong>mation field. The value of this field iscontrolled by the LVLINFO.(16) Program-name as used in the IDENTIFICATION DIVISION.RELATED REFERENCES“Signature in<strong>for</strong>mation bytes: compiler options”“Signature in<strong>for</strong>mation bytes: DATA DIVISION” on page 391“Signature in<strong>for</strong>mation bytes: ENVIRONMENT DIVISION” on page 392“Signature in<strong>for</strong>mation bytes: PROCEDURE DIVISION verbs” on page 392“Signature in<strong>for</strong>mation bytes: more PROCEDURE DIVISION items” on page 394Signature in<strong>for</strong>mation bytes: compiler optionsThis table shows program signature in<strong>for</strong>mation that is part of the listing ofprogram initialization code provided when you use the LIST compiler option.Chapter 19. Debugging 389


Table 53. Signature in<strong>for</strong>mation bytes <strong>for</strong> compiler optionsByte Bit On Off1 0 ADV NOADV1 AP<strong>OS</strong>T QUOTE2 DATA(31) DATA(24)3 DECK NODECK4 DUMP NODUMP5 DYNAM NODYNAM6 FASTSRT NOFASTSRT7 Reserved2 0 LIB NOLIB1 LIST NOLIST2 MAP NOMAP3 NUM NONUM4 OBJ NOOBJ5 OFFSET NOOFFSET6 OPTIMIZE NOOPTIMIZE7 ddname supplied in OUTDD option OUTDD(SYSOUT) is in effect.will be used.3 0 NUMPROC(PFD) NUMPROC(NOPFD)1 RENT NORENT2 Reserved3 SEQUENCE N<strong>OS</strong>EQUENCE4 SIZE(MAX) SIZE(value)5 SOURCE N<strong>OS</strong>OURCE6 SSRANGE N<strong>OS</strong>SRANGE7 TERM NOTERM4 0 TEST NOTEST1 TRUNC(STD) TRUNC(OPT)2 WORD was specified. NOWORD3 VBREF NOVBREF4 XREF NOXREF5 ZWB NOZWB6 NAME NONAME7 Reserved5 0 NUMPROC(MIG)1 NUMCLS(ALT) NUMCLS(PRIM)2 DBCS NODBCS3 AWO NOAWO4 TRUNC(BIN) Not TRUNC(BIN)6 CURRENCY NOCURRENCY7 Compilation unit is a class. Compilation unit is a program.390 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|Table 53. Signature in<strong>for</strong>mation bytes <strong>for</strong> compiler options (continued)Byte Bit On Off26 0 RMODE(ANY) RMODE(24)1–3 TEST(HOOK) TEST(NOHOOK)4 OPT(FULL) OPT(STD) or NOOPT5 INTDATE(LILIAN) INTDATE(ANSI)6 TEST(SEPARATE) Not TEST(SEPARATE)7 Reserved27 0 PGMNAME(LONGUPPER) Not PGMNAME(LONGUPPER)1 PGMNAME(LONGMIXED) Not PGMNAME(LONGMIXED)2 DLL NODLL3 EXPORTALL NOEXPORTALL4 DATEPROC NODATEPROC5 ARITH(EXTEND) ARITH(COMPAT)6 THREAD NOTHREAD7 TEST(EJPD) TEST(NOEJPD)28 0 SQL N<strong>OS</strong>QL1 CICS NOCICS2 MDECK NOMDECK3 SQLCCSID N<strong>OS</strong>QLCCSID4 OPTFILE is in effect. OPTFILE is not in effect.5 XMLPARSE(XMLSS) XMLPARSE(COMPAT)6 BLOCK0 NOBLOCK0Signature in<strong>for</strong>mation bytes: DATA DIVISIONThis table shows program signature in<strong>for</strong>mation that is part of the listing ofprogram initialization code provided when you use the LIST compiler option.Table 54. Signature in<strong>for</strong>mation bytes <strong>for</strong> the DATA DIVISIONByte Bit Item6 0 QSAM file descriptor1 VSAM sequential file descriptor2 VSAM indexed file descriptor3 VSAM relative file descriptor4 CODE-SET clause (ASCII files) in file descriptor5 Spanned records6 PIC G or PIC N (DBCS data item)7 OCCURS DEPENDING ON clause in data description entryChapter 19. Debugging 391


Table 54. Signature in<strong>for</strong>mation bytes <strong>for</strong> the DATA DIVISION (continued)Byte Bit Item7 0 SYNCHRONIZED clause in data description entry1 JUSTIFIED clause in data description entry2 USAGE IS POINTER item3 Complex OCCURS DEPENDING ON clause4 External floating-point items in the DATA DIVISION5 Internal floating-point items in the DATA DIVISION6 Line-sequential file7 USAGE IS PROCEDURE-POINTER or FUNCTION-POINTER itemRELATED REFERENCES“LIST” on page 328Signature in<strong>for</strong>mation bytes: ENVIRONMENT DIVISIONThis table shows program signature in<strong>for</strong>mation that is part of the listing ofprogram initialization code provided when you use the LIST compiler option.Table 55. Signature in<strong>for</strong>mation bytes <strong>for</strong> the ENVIRONMENT DIVISIONByte Bit Item8 0 FILE STATUS clause in FILE-CONTROL paragraph1 RERUN clause in I-O-CONTROL paragraph of INPUT-OUTPUTSECTION2 UPSI switch defined in SPECIAL-NAMES paragraphSignature in<strong>for</strong>mation bytes: PROCEDURE DIVISION verbsThe following table shows program signature in<strong>for</strong>mation that is part of the listingof program initialization code provided when you use the LIST compiler option.Table 56. Signature in<strong>for</strong>mation bytes <strong>for</strong> PROCEDURE DIVISION verbsByte Bit Item9 0 ACCEPT1 ADD2 ALTER3 CALL4 CANCEL6 CL<strong>OS</strong>E10 0 COMPUTE2 DELETE4 DISPLAY5 DIVIDE392 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 56. Signature in<strong>for</strong>mation bytes <strong>for</strong> PROCEDURE DIVISION verbs (continued)Byte Bit Item11 1 END-PERFORM2 ENTER3 ENTRY4 EXIT5 EXEC6 GO TO7 IF12 0 INITIALIZE1 INVOKE2 INSPECT3 MERGE4 MOVE5 MULTIPLY6 OPEN7 PERFORM13 0 READ2 RELEASE3 RETURN4 REWRITE5 SEARCH7 SET14 0 SORT1 START2 STOP3 STRING4 SUBTRACT7 UNSTRING15 0 USE1 WRITE2 CONTINUE3 END-ADD4 END-CALL5 END-COMPUTE6 END-DELETE7 END-DIVIDEChapter 19. Debugging 393


Table 56. Signature in<strong>for</strong>mation bytes <strong>for</strong> PROCEDURE DIVISION verbs (continued)Byte Bit Item16 0 END-EVALUATE1 END-IF2 END-MULTIPLY3 END-READ4 END-RETURN5 END-REWRITE6 END-SEARCH7 END-START17 0 END-STRING1 END-SUBTRACT2 END-UNSTRING3 END-WRITE4 GOBACK5 EVALUATE7 SERVICE18 0 END-INVOKE1 END-EXEC2 XML3 END-XMLCheck return code: A return code greater than 4 from the compiler could meanthat some of the verbs shown in the in<strong>for</strong>mation bytes might have been discardedfrom the program.Signature in<strong>for</strong>mation bytes: more PROCEDURE DIVISION itemsThis table shows program signature in<strong>for</strong>mation that is part of the listing ofprogram initialization code provided when you use the LIST compiler option.Table 57. Signature in<strong>for</strong>mation bytes <strong>for</strong> more PROCEDURE DIVISION itemsByte Bit Item21 0 Hexadecimal literal1 Altered GO TO2 I-O ERROR declarative3 LABEL declarative4 DEBUGGING declarative5 Program segmentation6 OPEN...EXTEND7 EXIT PROGRAM394 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 57. Signature in<strong>for</strong>mation bytes <strong>for</strong> more PROCEDURE DIVISIONitems (continued)Byte Bit Item22 0 CALL literal1 CALL identifier2 CALL...ONOVERFLOW3 CALL...LENGTH OF4 CALL...ADDRESS OF5 CL<strong>OS</strong>E ...REEL/UNIT6 Exponentiation used7 Floating-point items used23 0 COPY1 BASIS2 DBCS name in program3 Shift-out and Shift-in in program4-7 Highest error severity at entry to ASM2 module IGYBINIT24 0 DBCS literal1 REPLACE2 Reference modification was used.3 Nested program4 INITIAL5 COMMON6 SELECT ...OPTIONAL7 EXTERNAL25 0 GLOBAL1 RECORD IS VARYING2 ACCEPT FROM SYSIPT used in LABEL declarative3 DISPLAY UPON SYSLST used in LABEL declarative4 DISPLAY UPON SYSPCH used in LABEL declarative5 Intrinsic function was used29 0 Java-based OO syntax in program1 FUNCTION RANDOM used in program2 NATIONAL data used in programRELATED REFERENCES“LIST” on page 328Example: assembler code generated from source codeThe following example shows a listing of the assembler code that is generatedfrom source code when you use the LIST compiler option. You can use this listingto find the <strong>COBOL</strong> verb that corresponds to the instruction that failed.DATA VALIDATION AND UPDATE PROGRAM IGYTCARA Date 08/30/2009 Time 10:48:16000433 MOVE000435 READChapter 19. Debugging 395


000436 SET (1)(2) (3) (5) (6)000F26 92E8 A00A MVI 10(10),X'E8' LOCATION-EOF-FLAG000F2A GN=13 EQU *000F2A 47F0 B426 BC 15,1062(0,11) GN=75(000EFA)000F2E GN=74 EQU *000439 IF000F2E 95E8 A00A CLI 10(10),X'E8' LOCATION-EOF-FLAG000F32 4780 B490 BC 8,1168(0,11) GN=14(000F64)000440 DISPLAY000F36 5820 D05C L 2,92(0,13) TGTFIXD+92000F3A 58F0 202C L 15,44(0,2) V(IGZCDSP )000F3E 4110 97FF LA 1,2047(0,9) PGMLIT AT +1999000F42 05EF BALR 14,15000443 CALL000F44 4130 A012 LA 3,18(0,10) COMP-CODE000F48 5030 D21C ST 3,540(0,13) TS2=4000F4C 9680 D21C OI 540(13),X'80' TS2=4000F50 4110 D21C LA 1,540(0,13) TS2=4000F54 58F0 9000 L 15,0(0,9) V(ILBOABN0)000F58 05EF BALR 14,15000F5A 50F0 D078 ST 15,120(0,13) TGTFIXD+120000F5E BF38 D089 ICM 3,8,137(13) TGTFIXD+137000F62 0430 SPM 3,0000F64 (4) GN=14 EQU *000F64 5820 D154 L 2,340(0,13) VN=3000F68 07F2 BCR 15,2(1) Source line number and <strong>COBOL</strong> verb, paragraph name, or section nameIn line 000436, SET is the <strong>COBOL</strong> verb. An asterisk (*) be<strong>for</strong>e a nameindicates that the name is a paragraph name or a section name.(2) Relative location of the object code instruction in the module, inhexadecimal notation(3) Object code instruction, in hexadecimal notationThe first two or four hexadecimal digits are the instruction, and theremaining digits are the instruction operands. Some instructions have twooperands.(4) Compiler-generated names (GN) <strong>for</strong> code sequences(5) Object code instruction in a <strong>for</strong>m that closely resembles assemblerlanguage(6) Comments about the object code instruction:v One or two operands that participate in the machine instructions aredisplayed on the right. An asterisk immediately follows the data-namesthat are defined in more than one structure (in that way made unique byqualification in the source program).v The relative location of any generated label that appears as an operandis displayed in parentheses.RELATED REFERENCES“Symbols used in LIST and MAP output” on page 385Example: TGT memory mapThe following example shows LIST output <strong>for</strong> the task global table (TGT) within<strong>for</strong>mation about the environment in which your program runs.396 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


DATA VALIDATION AND UPDATE PROGRAM IGYTCARA Date 08/30/2009 Time 10:48:16*** TGT MEMORY MAP ***(1) (2)TGTLOC000000 RESERVED - 72 BYTES000048 TGT IDENTIFIER00004C RESERVED - 4 BYTES000050 TGT LEVEL INDICATOR000051 RESERVED - 3 BYTES000054 32 BIT SWITCH000058 POINTER TO RUNCOM00005C POINTER TO COBVEC000060 POINTER TO PROGRAM DYNAMIC BLOCK TABLE000064 NUMBER OF FCB'S000068 WORKING-STORAGE LENGTH00006C RESERVED - 4 BYTES000070 ADDRESS OF IGZESMG WORK AREA000074 ADDRESS OF 1ST GETMAIN BLOCK (SPACE MGR)000078 RESERVED - 2 BYTES00007A RESERVED - 2 BYTES00007C RESERVED - 2 BYTES00007E MERGE FILE NUMBER000080 ADDRESS OF CEL COMMON ANCHOR AREA000084 LENGTH OF TGT000088 RESERVED - 1 SINGLE BYTE FIELD000089 PROGRAM MASK USED BY THIS PROGRAM00008A RESERVED - 2 SINGLE BYTE FIELDS00008C NUMBER OF SECONDARY FCB CELLS000090 LENGTH OF THE ALTER VN(VNI) VECTOR000094 COUNT OF NESTED PROGRAMS IN COMPILE UNIT000098 DDNAME FOR DISPLAY OUTPUT0000A0 RESERVED - 8 BYTES0000A8 POINTER TO COM-REG SPECIAL REGISTER0000AC RESERVED - 52 BYTES0000E0 ALTERNATE COLLATING SEQUENCE TABLE PTR.0000E4 ADDRESS OF SORT G.N. ADDRESS BLOCK0000E8 ADDRESS OF PGT0000EC RESERVED - 4 BYTES0000F0 POINTER TO 1ST IPCB0000F4 ADDRESS OF THE CLLE FOR THIS PROGRAM0000F8 POINTER TO ABEND INFORMATION TABLE0000FC POINTER TO TEST INFO FIELDS IN THE TGT000100 ADDRESS OF START OF <strong>COBOL</strong> PROGRAM000104 POINTER TO ALTER VNI'S IN CGT000108 POINTER TO ALTER VN'S IN TGT00010C POINTER TO FIRST PBL IN THE PGT000110 POINTER TO FIRST FCB CELL000114 WORKING-STORAGE ADDRESS000118 POINTER TO FIRST SECONDARY FCB CELL00011C POINTER TO STATIC CLASS INFO BLOCK 1000120 POINTER TO STATIC CLASS INFO BLOCK 2*** VARIABLE PORTION OF TGT ***000124 BASE LOCATORS FOR SPECIAL REGISTERS00012C BASE LOCATORS FOR WORKING-STORAGE (3)000134 BASE LOCATORS FOR LINKAGE-SECTION000138 BASE LOCATORS FOR FILES00014C CLLE ADDR. CELLS FOR CALL LIT. SUB-PGMS.000170 INDEX CELLS000194 FCB CELLS0001A8 INTERNAL PROGRAM CONTROL BLOCKS(1) Hexadecimal offset of the TGT field from the start of the TGT(2) Explanation of the contents of the TGT fieldChapter 19. Debugging 397


(3) TGT fields <strong>for</strong> the base locators of <strong>COBOL</strong> data areasExample: DSA memory mapThe following example shows LIST output <strong>for</strong> the dynamic save area (DSA). TheDSA contains in<strong>for</strong>mation about the contents of the storage acquired when aseparately compiled procedure is entered.DATA VALIDATION AND UPDATE PROGRAM IGYTCARA Date 08/30/2009 Time 10:48:16*** DSA MEMORY MAP ***(1) (2)DSALOC000000 REGISTER SAVE AREA00004C STACK NAB (NEXT AVAILABLE BYTE)000058 ADDRESS OF INLINE-CODE PRIMARY DSA00005C ADDRESS OF TGT000060 ADDRESS OF CAA000084 SWITCHES000088 CURRENT INT. PROGRAM OR METHOD NUMBER00008C ADDRESS OF CALL STATEMENT PROGRAM NAME000090 CALC ROUTINE REGISTER SAVE AREA0000C4 ADDRESS OF FILE MUTEX USE COUNT CELLS0000C8 PROCEDURE DIVISION RETURNING VALUE*** VARIABLE PORTION OF DSA ***0000D0 BACKSTORE CELLS FOR SYMBOLIC REGISTERS000158 BASE LOCATORS FOR ALPHANUMERIC TEMPS00015C VARIABLE-LENGTH CELLS000170 ODO SAVE CELLS00017C VARIABLE NAME (VN) CELLS FOR PERFORM0001EC PERFORM SAVE CELLS000320 TEMPORARY STORAGE-1000330 TEMPORARY STORAGE-2000500 ALL PARAMETER BLOCK000564 ALPHANUMERIC TEMPORARY STORAGE(1) Hexadecimal offset of the DSA field from the start of the DSA(2) Explanation of the contents of the DSA fieldExample: location and size of WORKING-STORAGEThe following example shows LIST output about the WORKING-STORAGE <strong>for</strong> aprogram compiled with the RENT option.(1) (2)WRK-STOR WILL BE ALLOCATED FOR 000015B0 BYTES(1) WORKING-STORAGE identification(2) Length of WORKING-STORAGE in hexadecimal notationRELATED CONCEPTS“Storage and its addressability” on page 42Example: XREF output: data-name cross-referencesThe following example shows a sorted cross-reference of data-names that isproduced by the XREF compiler option. Numbers in parentheses refer to notes afterthe example.An "M" preceding a data-name reference indicates that thedata-name is modified by this reference.398 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


(1) (2) (3)Defined Cross-reference of data-names References264 ABEND-ITEM1265 ABEND-ITEM2347 ADD-CODE ........... 1126 1192381 ADDRESS-ERROR. ........ M1156280 AREA-CODE. .......... 1266 1291 1354 1375382 CITY-ERROR .......... M1159(4)Context usage is indicated by the letter preceding a procedure-namereference. These letters and their meanings are:A = ALTER (procedure-name)D = GO TO (procedure-name) DEPENDING ONE = End of range of (PERFORM) through (procedure-name)G = GO TO (procedure-name)P = PERFORM (procedure-name)T = (ALTER) TO PROCEED TO (procedure-name)U = USE FOR DEBUGGING (procedure-name)(5) (6) (7)Defined Cross-reference of procedures References877 000-DO-MAIN-LOGIC943 050-CREATE-STL-MASTER-FILE . . P879995 100-INITIALIZE-PARAGRAPH ... P8811471 1100-PRINT-I-F-HEADINGS. ... P9261511 1200-PRINT-I-F-DATA. ..... P9281573 1210-GET-MILES-TIME. ..... P15401666 1220-STORE-MILES-TIME. .... P15411682 1230-PRINT-SUB-I-F-DATA. ... P15621706 1240-COMPUTE-SUMMARY ..... P15631052 200-EDIT-UPDATE-TRANSACTION. . P8901154 210-EDIT-THE-REST. ...... P11451189 300-UPDATE-COMMUTER-RECORD . . P8931237 310-FORMAT-COMMUTER-RECORD . . P1194 P12091258 320-PRINT-COMMUTER-RECORD. . . P1195 P1206 P1212 P12221318 330-PRINT-REPORT ....... P1208 P1232 P1286 P1310 P13701342 400-PRINT-TRANSACTION-ERRORS . P896Cross-reference of data-names:(1) Line number where the name was defined.(2) Data-name.(3) Line numbers where the name was used. If M precedes the line number, thedata item was explicitly modified at the location.Cross-reference of procedure references:(4) Explanations of the context usage codes <strong>for</strong> procedure references.(5) Line number where the procedure-name is defined.(6) Procedure-name.(7) Line numbers where the procedure is referenced, and the context usagecode <strong>for</strong> the procedure.“Example: XREF output: program-name cross-references” on page 400“Example: XREF output: COPY/BASIS cross-references” on page 400“Example: XREF output: embedded cross-reference” on page 401Chapter 19. Debugging 399


Example: XREF output: program-name cross-referencesThe following example shows a sorted cross-reference of program-names producedby the XREF compiler option. Numbers in parentheses refer to notes that follow theexample.(1) (2) (3)Defined Cross-reference of programs ReferencesEXTERNAL EXTERNAL1. ..........252 X............... 4112 X1.............. 33720 X11.............. 251627 X12.............. 321735 X2.............. 408(1) Line number where the program-name was defined. If the program isexternal, the word EXTERNAL is displayed instead of a definition linenumber.(2) Program-name.(3) Line numbers where the program is referenced.Example: XREF output: COPY/BASIS cross-referencesThe following example shows a sorted cross-reference of copybooks to thelibrary-names and data-set names of the associated copybooks, produced by theXREF compiler option under z/<strong>OS</strong>. Numbers in parentheses refer to notes after theexample.COPY/BASIS cross-reference of text-names, library names(1) (1) (2) (3) (4)Text-name Library File name Concat ISPF(Member) (DDNAME) (Data set name) Level CreatedACTIONS OTHERLIB USERID.<strong>COBOL</strong>.COPY 0 1992/07/11ACTIONS SYSLIB USERID.<strong>COBOL</strong>.COPY 0 1992/07/11CUSTOMER ALTDDXXY USERID.<strong>COBOL</strong>.LIB3 0 2007/06/01CUSTOMER SYSLIB USERID.<strong>COBOL</strong>.LIB2PDSE 1 2007/06/07HOUSE ALTDDXXY USERID.<strong>COBOL</strong>.LIB2 1 2007/06/07HOUSE SYSLIB USERID.<strong>COBOL</strong>.LIB2PDSE 1IMOTOR SYSLIB USERID.<strong>COBOL</strong>.LIB4X 3 2007/06/07ISOVERFY SYSLIB USERID.<strong>COBOL</strong>.COPY 0NSMAP SYSLIB USERID.<strong>COBOL</strong>.LIB3 2(1) Text-name and library (an abbreviation <strong>for</strong> library-name) are from thestatement COPY text-name OF library-name in the source, <strong>for</strong> example,Copy ACTIONS Of OTHERLIB.(2) The name of the data set from which the COPY member was copied.(3) Abbreviation <strong>for</strong> concatenation level. Indicates how many levels deep agiven data set is from the first data set in the concatenation <strong>for</strong> a givenddname.For example, four data sets in the example above are concatenated toddname SYSLIB:DDNAME DSNAME (concatenation level)SYSLIB DD DSN=USERID.<strong>COBOL</strong>.COPY, 0400 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


DD DSN=USERID.<strong>COBOL</strong>.LIB2PDSE, 1DD DSN=USERID.<strong>COBOL</strong>.LIB3, 2DD DSN=USERID.<strong>COBOL</strong>.LIB4X 3Thus <strong>for</strong> example member NSMAP shown in the listing above was foundin data set USERID.<strong>COBOL</strong>.LIB3, which is two levels down from the firstdata set in the SYSLIB concatenation.(4) Creation date is shown if the PDS or PDSE was edited with STATS ON inISPF.|||Tip: Under z/<strong>OS</strong>, if there is more than one data set in your SYSLIB concatenation,the COPY/BASIS cross-reference might in some cases be incomplete or missing.For details, see the related reference about the XREF compiler option.If you compile in the z/<strong>OS</strong> UNIX shell, the cross-reference looks like the excerptshown below.COPY/BASIS cross-reference of text-names, library names, and file names(5) (5) (6)Text-name Library-name File name'/copydir/copyM.cbl' SYSLIB /u/JSMITH/cobol//copydir/copyM.cbl'/copyA.cpy' SYSLIB /u/JSMITH/cobol//copyA.cpy'cobol/copyA.cpy' ALTDD2 /u/JSMITH/cobol/copyA.cpy'copy/stuff.cpy' ALTDD2 /u/JSMITH/copy/stuff.cpy'copydir/copyM.cbl' SYSLIB /u/JSMITH/cobol/copydir/copyM.cbl'copydir/copyM.cbl' SYSLIB (default) /u/JSMITH/cobol/copydir/copyM.cbl'stuff.cpy' ALTDD /u/JSMITH/copy/stuff.cpy"copyA.cpy" (7) SYSLIB (default) /u/JSMITH/cobol/copyA.cpy"reallyXXVeryLongLon> SYSLIB (default) (8) = truncated on right < = truncated on left(5) From the COPY statement in the source; <strong>for</strong> example the COPY statementcorresponding to the third item in the cross-reference above would be:COPY 'cobol/copyA.cpy' Of ALTDD2(6) The fully qualified path of the file from which the COPY member wascopied(7) Truncation of a long text-name or library-name on the right is marked by agreater-than sign (>).(8) Truncation of a long file name on the left is marked by a less-than sign (


000984 100-initialize-paragraph.000985 move spaces to ws-transaction-record IMP 340 (2)000986 move spaces to ws-commuter-record IMP 316000987 move zeroes to commuter-zipcode IMP 327000988 move zeroes to commuter-home-phone IMP 328000989 move zeroes to commuter-work-phone IMP 329000990 move zeroes to commuter-update-date IMP 333000991 open input update-transaction-file 204000992 location-file 193000993 i-o commuter-file 181000994 output print-file 217...001442 1100-print-i-f-headings.001443001444 open output print-file. 217001445001446 move function when-compiled to when-comp. IFN 698 (2)001447 move when-comp (5:2) to compile-month. 698 640001448 move when-comp (7:2) to compile-day. 698 642001449 move when-comp (3:2) to compile-year. 698 644001450001451 move function current-date (5:2) to current-month. IFN 649001452 move function current-date (7:2) to current-day. IFN 651001453 move function current-date (3:2) to current-year. IFN 653001454001455 write print-record from i-f-header-line-1 222 635001456 after new-page. 138...(1) Line number of the definition of the data-name or procedure-name in theprogram(2) Special definition symbols:UND The user name is undefined.DUP The user name is defined more than once.IMP Implicitly defined name, such as special registers and figurativeconstants.IFN Intrinsic function reference.EXT External reference.* The program-name is unresolved because the NOCOMPILE option isin effect.Example: OFFSET compiler outputThe following example shows a compiler listing that has a condensed verb listing,global tables, WORKING-STORAGE in<strong>for</strong>mation, and literals. The listing is output fromthe OFFSET compiler option.DATA VALIDATION AND UPDATE PROGRAM IGYTCARA Date 08/30/2009 Time 10:48:16...(1) (2) (3)LINE # HEXLOC VERB LINE # HEXLOC VERB LINE # HEXLOC VERB000880 0026F0 DISPLAY 000881 002702 PERFORM 000933 002702 OPEN000934 002722 IF 000935 00272C DISPLAY 000936 002736 PERFORM001389 002736 DISPLAY 001390 002740 DISPLAY 001391 00274A DISPLAY001392 002754 DISPLAY 001393 00275E DISPLAY 001394 002768 DISPLAY001395 002772 DISPLAY 000937 00277C PERFORM 001434 00277C DISPLAY001435 002786 STOP 000939 0027A2 MOVE 000940 0027AC WRITE000941 0027D6 IF 000942 0027E0 DISPLAY 000943 0027EA PERFORM001389 0027EA DISPLAY 001390 0027F4 DISPLAY 001391 0027FE DISPLAY001392 002808 DISPLAY 001393 002812 DISPLAY 001394 00281C DISPLAY001395 002826 DISPLAY 000944 002830 DISPLAY 000945 00283A PERFORM001403 00283A DISPLAY 001404 002844 DISPLAY 001405 00284E DISPLAY001406 002858 DISPLAY 001407 002862 CALL 000947 002888 CL<strong>OS</strong>E(1) Line number. Your line numbers or compiler-generated line numbers arelisted.(2) Offset, from the start of the program, of the code generated <strong>for</strong> this verb(in hexadecimal notation).402 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The verbs are listed in the order in which they occur and are listed once<strong>for</strong> each time they are used.(3) Verb used.RELATED REFERENCES“OFFSET” on page 335Example: VBREF compiler outputThe following example shows an alphabetic listing of all the verbs in a program,and shows where each is referenced. The listing is produced by the VBREF compileroption.(1) (2) (3)2 ACCEPT ....... 101 1012 ADD......... 129 1301 CALL........ 1405 CL<strong>OS</strong>E. ....... 90 94 97 152 15320 COMPUTE. .......150 164 164 165 166 166 166 166 167 168 168 169 169 170 171 171171 172 172 1732 CONTINUE .......106 1072 DELETE ........96 11947 DISPLAY. .......88 90 91 92 92 93 94 94 94 95 96 96 97 99 99 100 100 100 100103 109 117 117 118 119 138 139 139 139 139 139 139 140 140 140140 143 148 148 149 149 149 152 152 152 153 1622 EVALUATE .......116 15547 IF..........88 90 93 94 94 95 96 96 97 99 100 103 105 105 107 107 107 109110 111 111 112 113 113 113 113 114 114 115 115 116 118 119 124124 126 127 129 132 133 134 135 136 148 149 152 152183 MOVE.........90 93 95 98 98 98 98 98 99 100 101 101 102 104 105 105 106 106107 107 108 108 108 108 108 108 109 110 111 112 113 113 113 114114 114 115 115 116 116 117 117 117 118 118 118 119 119 120 121121 121 121 121 121 121 121 121 121 122 122 122 122 122 123 123123 123 123 123 123 124 124 124 125 125 125 125 125 125 125 126126 126 126 126 127 127 127 127 128 128 129 129 130 130 130 130131 131 131 131 131 132 132 132 132 132 132 133 133 133 133 133134 134 134 134 134 135 135 135 135 135 135 136 136 137 137 137137 137 138 138 138 138 141 141 142 142 144 144 144 144 145 145145 145 146 149 150 150 150 151 151 155 156 156 157 157 158 158159 159 160 160 161 161 162 162 162 168 168 168 169 169 170 171171 172 172 173 1735 OPEN.........93 95 99 144 14862 PERFORM. .......88 88 88 88 89 89 89 91 91 91 91 93 93 94 94 95 95 95 95 9696 96 97 97 97 100 100 101 102 104 109 109 111 116 116 117 117117 118 118 118 118 119 119 119 120 120 124 125 127 128 133 134135 136 136 137 150 151 151 153 1538 READ.........88 89 96 101 102 108 149 1511 REWRITE. .......1184 SEARCH ........106 106 141 14246 SET..........88 89 101 103 104 105 106 108 108 136 141 142 149 150 151 152 154155 156 156 156 156 157 157 157 157 158 158 158 158 159 159 159159 160 160 160 160 161 161 161 161 162 162 164 1642 STOP.........92 1434 STRING ........123 126 132 13433 WRITE. ........94 116 129 129 129 129 129 130 130 130 130 145 146 146 146 146 147147 151 165 165 166 166 167 174 174 174 174 174 174 174 175 175(1) Number of times the verb is used in the program(2) Verb(3) Line numbers where the verb is usedChapter 19. Debugging 403


404 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 3. Targeting <strong>COBOL</strong> programs <strong>for</strong> certain environmentsChapter 20. Developing <strong>COBOL</strong> programs <strong>for</strong>CICS . . . . . . . . . . . . . . . . 407Coding <strong>COBOL</strong> programs to run under CICS . . 407Getting the system date under CICS. . . . . 409Calling to or from <strong>COBOL</strong> programs . . . . 409Determining the success of ECI calls. . . . . 411Compiling with the CICS option . . . . . . . 411Separating CICS suboptions . . . . . . . 413Integrated CICS translator . . . . . . . . 413Using the separate CICS translator . . . . . . 414CICS reserved-word table . . . . . . . . . 415Handling errors by using CICS HANDLE . . . . 416Example: handling errors by using CICSHANDLE . . . . . . . . . . . . . 417Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2environment . . . . . . . . . . . . . 419DB2 coprocessor . . . . . . . . . . . . 419Coding SQL statements . . . . . . . . . . 420Using SQL INCLUDE with the DB2 coprocessor 420Using character data in SQL statements . . . 421Using national decimal data in SQL statements 422Using national group items in SQL statements 422Using binary items in SQL statements . . . . 423Determining the success of SQL statements . . 423Compiling with the SQL option . . . . . . . 423Separating DB2 suboptions . . . . . . . . 424<strong>COBOL</strong> and DB2 CCSID determination. . . . . 425Code-page determination <strong>for</strong> string hostvariables in SQL statements . . . . . . . 426<strong>Programming</strong> with the SQLCCSID orN<strong>OS</strong>QLCCSID option . . . . . . . . . 426Differences in how the DB2 precompiler andcoprocessor behave . . . . . . . . . . . 427Period at the end of EXEC SQL INCLUDEstatements . . . . . . . . . . . . . 427EXEC SQL INCLUDE and nested COPYREPLACING . . . . . . . . . . . . 427EXEC SQL and REPLACE or COPYREPLACING . . . . . . . . . . . . 428Source code after an END-EXEC statement . . 428Multiple definitions of host variables . . . . 428EXEC SQL statement continuation lines . . . 428Bit-data host variables . . . . . . . . . 428SQL-INIT-FLAG . . . . . . . . . . . 429Choosing the DYNAM or NODYNAM compileroption . . . . . . . . . . . . . . . . 429Building a mixed <strong>COBOL</strong>-Java application thatstarts with <strong>COBOL</strong> . . . . . . . . . . 433Writing mixed-language IMS applications . . . 434Using the STOP RUN statement . . . . . 434Processing messages and synchronizingtransactions . . . . . . . . . . . . 434Accessing databases . . . . . . . . . 434Using the application interface block . . . 435Chapter 23. Running <strong>COBOL</strong> programs underz/<strong>OS</strong> UNIX . . . . . . . . . . . . . . 437Running in z/<strong>OS</strong> UNIX environments . . . . . 437Setting and accessing environment variables . . . 438Setting environment variables that affectexecution . . . . . . . . . . . . . . 439Runtime environment variables . . . . . . 439Example: setting and accessing environmentvariables . . . . . . . . . . . . . . 440Calling UNIX/P<strong>OS</strong>IX APIs . . . . . . . . . 440Accessing main program parameters . . . . . 442Example: accessing main program parameters 443Chapter 22. Developing <strong>COBOL</strong> programs <strong>for</strong>IMS . . . . . . . . . . . . . . . . 431Compiling and linking <strong>COBOL</strong> programs <strong>for</strong>running under IMS . . . . . . . . . . . 431Using object-oriented <strong>COBOL</strong> and Java under IMS 432Calling a <strong>COBOL</strong> method from a Javaapplication under IMS . . . . . . . . . 432© Copyright IBM Corp. 1991, 2009 405


406 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 20. Developing <strong>COBOL</strong> programs <strong>for</strong> CICS<strong>COBOL</strong> programs that are written <strong>for</strong> CICS can run under CICS Transaction Server.CICS <strong>COBOL</strong> application programs that use CICS services must use the CICScommand-level interface.When you use the CICS compiler option, the <strong>Enterprise</strong> <strong>COBOL</strong> compiler handlesboth native <strong>COBOL</strong> statements and embedded CICS statements in the sourceprogram. You can still use the separate CICS translator to translate CICSstatements to <strong>COBOL</strong> code, but use of the integrated CICS translator isrecommended instead.After you compile and link-edit your program, you need to do some other stepssuch as updating CICS tables be<strong>for</strong>e you can run the <strong>COBOL</strong> program under CICS.However, these CICS topics are beyond the scope of <strong>COBOL</strong> in<strong>for</strong>mation. Forfurther in<strong>for</strong>mation, see the related tasks.You can determine how runtime errors are handled by setting the CBLPSHPOPruntime option. For in<strong>for</strong>mation about CICS HANDLE and CBLPSHPOP, see the relatedtasks.RELATED CONCEPTS“Integrated CICS translator” on page 413RELATED TASKS“Coding <strong>COBOL</strong> programs to run under CICS”“Compiling with the CICS option” on page 411“Using the separate CICS translator” on page 414“Handling errors by using CICS HANDLE” on page 416Language Environment <strong>Programming</strong> <strong>Guide</strong> (Condition handling under CICS:using the CBLPSHPOP run-time option)CICS Application <strong>Programming</strong> <strong>Guide</strong>RELATED REFERENCES“CICS” on page 309Coding <strong>COBOL</strong> programs to run under CICSTo code a program to run under CICS, code CICS commands in the PROCEDUREDIVISION by using the EXEC CICS command <strong>for</strong>mat.EXEC CICS command-name command-optionsEND-EXECCICS commands have the basic <strong>for</strong>mat shown above. Within EXEC commands, usethe space as a word separator; do not use a comma or a semicolon.Restriction: <strong>COBOL</strong> class definitions and methods (object-oriented <strong>COBOL</strong>) cannotbe run in a CICS environment. In addition, when you code yourprograms to run under CICS, do not use the following code:vFILE-CONTROL entry in the ENVIRONMENT DIVISION, unless the FILE-CONTROL entryis used <strong>for</strong> a SORT statement© Copyright IBM Corp. 1991, 2009 407


vvvvFILE SECTION of the DATA DIVISION, unless the FILE SECTION is used <strong>for</strong> a SORTstatementUser-specified parameters to the main programUSE declaratives (except USE FOR DEBUGGING)These <strong>COBOL</strong> language statements:– ACCEPT <strong>for</strong>mat 1: data transfer (you can use <strong>for</strong>mat-2 ACCEPT to retrieve thesystem date and time)– CL<strong>OS</strong>E– DELETE– DISPLAY UPON CONSOLE– DISPLAY UPON SYSPUNCH– MERGE– OPEN– READ– RERUN– REWRITE– START– STOP literal– WRITEIf you plan to use the separate CICS translator, you must put any REPLACEstatements that contain EXEC commands after the PROCEDURE DIVISION header <strong>for</strong>the program, otherwise the commands will not be translated.Coding file input and output: You must use CICS commands <strong>for</strong> most input andoutput processing. There<strong>for</strong>e, do not describe files or code any OPEN, CL<strong>OS</strong>E, READ,START, REWRITE, WRITE, orDELETE statements. Instead, use CICS commands toretrieve, update, insert, and delete data.Coding a <strong>COBOL</strong> program to run above the 16-MB line: Under <strong>Enterprise</strong><strong>COBOL</strong>, the following restrictions apply when you code a <strong>COBOL</strong> program to runabove the 16-MB line:vvvIf you use IMS/ESA ® without DBCTL, DL/I CALL statements are supported only ifall the data passed in the call resides below the 16-MB line. There<strong>for</strong>e, you mustspecify the DATA(24) compiler option. However, if you use IMS/ESA with DBCTL,you can use the DATA(31) compiler option instead and pass data that residesabove the 16-MB line.If you use EXEC DLI instead of DL/I CALL statements, you can specify DATA(31)regardless of the level of the IMS product.If the receiving program is link-edited with AMODE 31, addresses that are passedmust be 31 bits long, or 24 bits long with the leftmost byte set to zeros.If the receiving program is link-edited with AMODE 24, addresses that are passedmust be 24 bits long.Displaying the contents of data items: DISPLAY to the system logical output device(SYSOUT, SYSLIST, SYSLST) is supported under CICS. The DISPLAY output iswritten to the Language Environment message file (transient data queue CESE).DISPLAY ...UPON CONSOLE and DISPLAY ...UPON SYSPUNCH, however, are notallowed.408 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED CONCEPTS“Integrated CICS translator” on page 413RELATED TASKS“Sorting under CICS” on page 231“Getting the system date under CICS”“Calling to or from <strong>COBOL</strong> programs”“Determining the success of ECI calls” on page 411“Using the separate CICS translator” on page 414RELATED REFERENCES“CICS SORT application restrictions” on page 232Getting the system date under CICSTo retrieve the system date in a CICS program, use a <strong>for</strong>mat-2 ACCEPT statement orthe CURRENT-DATE intrinsic function.You can use any of these <strong>for</strong>mat-2 ACCEPT statements in the CICS environment toget the system date:v ACCEPT identifier-2 FROM DATE (two-digit year)v ACCEPT identifier-2 FROM DATE YYYYMMDDv ACCEPT identifier-2 FROM DAY (two-digit year)v ACCEPT identifier-2 FROM DAY YYYYDDDvACCEPT identifier-2 FROM DAY-OF-WEEK (one-digit integer, where 1 representsMonday)You can use this <strong>for</strong>mat-2 ACCEPT statement in the CICS environment to get thesystem time:v ACCEPT identifier-2 FROM TIMEAlternatively, you can use the CURRENT-DATE intrinsic function, which can alsoprovide the time.These methods work in both CICS and non-CICS environments.Do not use a <strong>for</strong>mat-1 ACCEPT statement in a CICS program.RELATED TASKS“Assigning input from a screen or file (ACCEPT)” on page 37RELATED REFERENCESCURRENT-DATE (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Calling to or from <strong>COBOL</strong> programsYou can make calls to or from VS <strong>COBOL</strong> II, <strong>COBOL</strong> <strong>for</strong> MVS & VM, <strong>COBOL</strong> <strong>for</strong><strong>OS</strong>/390 & VM, and <strong>Enterprise</strong> <strong>COBOL</strong> programs by using the CALL statement.If you are calling a separately compiled <strong>COBOL</strong> program that was processed witheither the separate CICS translator or the integrated CICS translator, you must passDFHEIBLK and DFHCOMMAREA as the first two parameters in the CALL statement.Chapter 20. Developing <strong>COBOL</strong> programs <strong>for</strong> CICS 409


Called programs that are processed by the separate CICS translator or theintegrated CICS translator can contain any function that is supported by CICS <strong>for</strong>the language.Dynamic calls:||You can use <strong>COBOL</strong> dynamic calls when running under CICS. If a <strong>COBOL</strong>program contains EXEC CICS statements or contains EXEC SQL statements, theNODYNAM compiler option is required. To dynamically call a program in this case,you can use CALL identifier with the NODYNAM compiler option.If a <strong>COBOL</strong> program contains no EXEC CICS statements and contains no EXEC SQLstatements, there is no requirement to compile with NODYNAM. To dynamically call aprogram in this case, you can use either CALL literal with the DYNAM compiler option,or CALL identifier.You must define dynamically called programs in the CICS program processingtable (PPT) if you are not using CICS autoinstall. Under CICS, <strong>COBOL</strong> programsdo not support dynamic calls to subprograms that have the RELOAD=YES optioncoded in their CICS PROGRAM definition. Dynamic calls to programs that are definedwith RELOAD=YES can cause a storage shortage. Use the RELOAD=NO option <strong>for</strong>programs that are to be dynamically called by <strong>COBOL</strong>.Interlanguage communication (ILC):Support <strong>for</strong> ILC with other high-level languages is available. Where ILC is notsupported, you can use CICS LINK, XCTL, and RETURN instead.The following table shows the calling relationship between <strong>COBOL</strong> and assemblerprograms. In the table, assembler programs that con<strong>for</strong>m to the interface that isdescribed in the Language Environment <strong>Programming</strong> <strong>Guide</strong> are called LanguageEnvironment-con<strong>for</strong>ming assembler programs. Those that do not con<strong>for</strong>m to theinterface are non-Language Environment-con<strong>for</strong>ming assembler programs.|Table 58. Calls between <strong>COBOL</strong> and assembler under CICSCalls between <strong>COBOL</strong> andassembler programsFrom an <strong>Enterprise</strong> <strong>COBOL</strong>program to the assemblerprogram?From the assembler program toan <strong>Enterprise</strong> <strong>COBOL</strong> program?LanguageEnvironment-con<strong>for</strong>mingassembler programYesYesNon-LanguageEnvironment-con<strong>for</strong>mingassembler programYesNoNested programs:When you compile with the integrated CICS translator, the translator generates theDFHEIBLK and DFHCOMMAREA control blocks with the GLOBAL clause in the outermostprogram. There<strong>for</strong>e if you code nested programs, you do not have to pass thesecontrol blocks as arguments on calls to the nested programs.If you code nested programs and you plan to use the separate CICS translator,pass DFHEIBLK and DFHCOMMAREA as parameters to the nested programs that containEXEC commands or references to the EXEC interface block (EIB). You must pass the410 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


same parameters also to any program that <strong>for</strong>ms part of the control hierarchybetween such a program and its top-level program.RELATED CONCEPTS“Integrated CICS translator” on page 413RELATED TASKS“Using the separate CICS translator” on page 414“Choosing the DYNAM or NODYNAM compiler option” on page 429“Handling errors when calling programs” on page 244Language Environment Writing ILC Communication Applications (ILC under CICS)CICS External Interfaces <strong>Guide</strong>Language Environment <strong>Programming</strong> <strong>Guide</strong>RELATED REFERENCES“DYNAM” on page 320Determining the success of ECI callsAfter calls to the external CICS interface (ECI), the content of the RETURN-CODEspecial register is set to an unpredictable value. There<strong>for</strong>e, even if your <strong>COBOL</strong>program terminates normally after successfully using the external CICS interface,the job step could end with an undefined return code.To ensure that a meaningful return code occurs at termination, set the RETURN-CODEspecial register be<strong>for</strong>e you terminate your program. To make the job return codereflect the status of the last call to CICS, set the RETURN-CODE special register basedon the response codes from the last call to the external CICS interface.RELATED TASKSCICS External Interfaces <strong>Guide</strong>Compiling with the CICS optionUse the CICS compiler option to enable the integrated CICS translator and tospecify CICS suboptions.If you specify the NOCICS option, the compiler diagnoses and discards any CICSstatements that it finds in your source program. If you have already used theseparate CICS translator, you must use NOCICS.You can specify the CICS option in any of the compiler option sources: compilerinvocation, PROCESS or CBL statements, or installation default. If the CICS option isthe <strong>COBOL</strong> installation default, you cannot specify CICS suboptions. However,making the CICS option the installation default is not recommended, because thechanges that are made by the integrated CICS translator are not appropriate <strong>for</strong>non-CICS applications.All CBL or PROCESS statements must precede any comment lines, in accordance withthe rules <strong>for</strong> <strong>Enterprise</strong> <strong>COBOL</strong>.The <strong>COBOL</strong> compiler passes to the integrated CICS translator the CICS suboptionstring that you provide in the CICS compiler option. The compiler does not analyzethe suboption string.Chapter 20. Developing <strong>COBOL</strong> programs <strong>for</strong> CICS 411


When you use the integrated CICS translator, you must compile with the followingoptions:Table 59. Compiler options required <strong>for</strong> the integrated CICS translatorCompiler optionCICSLIBNODYNAMRENTSIZE(xxx)CommentIf you specify NOLIB, DYNAM, orNORENT, the compiler <strong>for</strong>ces LIB,NODYNAM, and RENT on.Must be in effect with CICSMust be in effect with CICSMust be in effect with CICSxxx must be a size value (not MAX) that leaves enough storagein your user region <strong>for</strong> the integrated CICS translation process.In addition, IBM recommends that you use the compiler option WORD(CICS) tocause the compiler to flag language elements that are not supported under CICS.To compile your program with the integrated CICS translator, you can use thestandard JCL procedural statements that are supplied with <strong>COBOL</strong>. In addition tospecifying the above compiler options, you must change your JCL in two ways:v Specify the STEPLIB override <strong>for</strong> the <strong>COBOL</strong> step.vAdd the data set that contains the integrated CICS translator services, unlessthese services are in the linklist.|||The default name of the data set <strong>for</strong> CICS Transaction Server V4R1 isCICSTS41.CICS.SDFHLOAD, but your installation might have changed the name.For example, you might have the following line in your JCL://STEPLIB DD DSN=CICSTS41.CICS.SDFHLOAD,DISP=SHRThe <strong>COBOL</strong> compiler listing includes the error diagnostics (such as syntax errorsin the CICS statements) that the integrated CICS translator generates. The listingreflects the input source; it does not include the <strong>COBOL</strong> statements that theintegrated CICS translator generates.Compiling a sequence of programs: When you use the CICS option to compile asource file that contains a sequence of <strong>COBOL</strong> programs, the order of precedenceof the options from highest to lowest is:vvvOptions that are specified in the CBL or PROCESS card that initiates the unit ofcompilationOptions that are specified when the compiler is startedCICS default optionsRELATED CONCEPTS“Integrated CICS translator” on page 413RELATED TASKS“Coding <strong>COBOL</strong> programs to run under CICS” on page 407“Separating CICS suboptions” on page 413CICS Application <strong>Programming</strong> <strong>Guide</strong>RELATED REFERENCES“CICS” on page 309“Conflicting compiler options” on page 304412 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Separating CICS suboptionsYou can partition the specification of CICS suboptions into multiple CBL statements.CICS suboptions are cumulative. The compiler concatenates them from multiplesources in the order that they are specified.For example, suppose that a JCL file has the following code://STEP1 EXEC IGYWC, ...//PARM.<strong>COBOL</strong>="CICS("FLAG(I)")"//<strong>COBOL</strong>.SYSIN DD *CBL CICS("DEBUG")CBL CICS("LINKAGE")IDENTIFICATION DIVISION.PROGRAM-ID. <strong>COBOL</strong>1.During compilation, the compiler passes the following CICS suboption string tothe integrated CICS translator:"FLAG(I) DEBUG LINKAGE"The concatenated strings are delimited with single spaces and with a quotationmark or single quotation mark around the group. When the compiler findsmultiple instances of the same CICS suboption, the last specification of thesuboption in the concatenated string takes effect. The compiler limits the length ofthe concatenated CICS suboption string to 4 KB.RELATED REFERENCES“CICS” on page 309Integrated CICS translatorWhen you compile a <strong>COBOL</strong> program using the CICS compiler option, the <strong>COBOL</strong>compiler works with the integrated CICS translator to handle both native <strong>COBOL</strong>and embedded CICS statements in the source program.When the compiler encounters CICS statements, and at other significant points inthe source program, the compiler interfaces with the integrated CICS translator.The translator takes appropriate actions and then returns to the compiler, typicallyindicating which native language statements to generate.Although you can still translate embedded CICS statements separately, it isrecommended that you use the integrated CICS translator instead. Certainrestrictions that apply when you use the separate translator do not apply whenyou use the integrated translator, and using the integrated translator providesseveral advantages:vvvvvYou can use Debug Tool to debug the original source instead of the expandedsource that the separate CICS translator generates.You do not need to separately translate the EXEC CICS or EXEC DLI statementsthat are in copybooks.There is no intermediate data set <strong>for</strong> a translated but not compiled version of thesource program.Only one output listing instead of two is produced.Using nested programs that contain EXEC CICS statements is simpler.DFHCOMMAREA and DFHEIBLK are generated with the GLOBAL attribute in theoutermost program. You do not need to pass them as arguments on calls tonested programs or specify them in the USING phrase of the PROCEDURE DIVISIONheader of nested programs.Chapter 20. Developing <strong>COBOL</strong> programs <strong>for</strong> CICS 413


||vvvvYou can keep nested programs that contain EXEC CICS statements in separatefiles, and include those nested programs by using COPY statements.REPLACE statements can affect EXEC CICS statements.You can compile programs that contain CICS statements in a batch compilation(a sequence of programs).Because the compiler generates binary fields in CICS control blocks with <strong>for</strong>matCOMP-5 instead of BINARY, there is no dependency on the setting of the TRUNCcompiler option. You can use any setting of the TRUNC option in CICS programs,subject only to the requirements of the application logic and use of user-definedbinary fields.RELATED CONCEPTSCICS Application <strong>Programming</strong> <strong>Guide</strong> (The integrated CICS translator)RELATED TASKS“Coding <strong>COBOL</strong> programs to run under CICS” on page 407“Compiling with the CICS option” on page 411RELATED REFERENCES“CICS” on page 309“TRUNC” on page 353Using the separate CICS translatorTo run a <strong>COBOL</strong> program under CICS, you can use the separate CICS translator toconvert the CICS commands to <strong>COBOL</strong> statements, and then compile and link theprogram to create the executable module. However, using the CICS translator thatis integrated with <strong>Enterprise</strong> <strong>COBOL</strong> is recommended.To translate CICS statements separately, use the <strong>COBOL</strong>3 translator option. Thisoption causes the following line to be inserted:CBL RENT,NODYNAM,LIBYou can suppress the insertion of a CBL statement by using the CICS translatoroption NOCBLCARD.CICS provides the translator option ANSI85, which supports the following languagefeatures (introduced by Standard <strong>COBOL</strong> 85):v Blank lines intervening in literalsv Sequence numbers containing any characterv Lowercase characters supported in all <strong>COBOL</strong> wordsv REPLACE statementv Batch compilationv Nested programsv Reference modificationv GLOBAL variablesv Interchangeability of comma, semicolon, and spacev Symbolic character definitionAfter you use the separate CICS translator, use the following compiler optionswhen you compile the program:414 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 60. Compiler options required <strong>for</strong> the separate CICS translatorRequired compiler optionRENTNODYNAMLIBConditionThe program is translated by the CICS translator.The program contains a COPY or BASIS statement.In addition, IBM recommends that you use the compiler option WORD(CICS) tocause the compiler to flag language elements that are not supported under CICS.The following TRUNC compiler option recommendations are based on expectedvalues <strong>for</strong> binary data items:Table 61. TRUNC compiler options recommended <strong>for</strong> the separate CICS translatorRecommended compileroptionTRUNC(OPT)TRUNC(BIN)ConditionAll binary data items con<strong>for</strong>m to the PICTURE and USAGE clause<strong>for</strong> those data items.Not all binary data items con<strong>for</strong>m to the PICTURE and USAGEclause <strong>for</strong> those data items.For example, if you use the separate CICS translator and have a data item definedas PIC S9(8) BINARY that might receive a value greater than eight digits, use theTRUNC(BIN) compiler option, change the item to USAGE COMP-5, or change thePICTURE clause.You might also want to avoid using these options, which have no effect:v ADVv FASTSRTv OUTDDThe input data set <strong>for</strong> the compiler is the data set that you received as a result oftranslation, which is SYSPUNCH by default.RELATED CONCEPTS“Integrated CICS translator” on page 413CICS reserved-word tableRELATED TASKS“Compiling with the CICS option” on page 411<strong>COBOL</strong> provides an alternate reserved-word table (IGYCCICS) <strong>for</strong> CICSapplication programs. If you use the compiler option WORD(CICS), <strong>COBOL</strong> wordsthat are not supported under CICS are flagged with an error message.In addition to the <strong>COBOL</strong> words restricted by the IBM-supplied defaultreserved-word table, the IBM-supplied CICS reserved-word table restricts thefollowing <strong>COBOL</strong> words:v CL<strong>OS</strong>Ev DELETEChapter 20. Developing <strong>COBOL</strong> programs <strong>for</strong> CICS 415


vvvvvvvvvvvvvvFDFILEFILE-CONTROLINPUT-OUTPUTI-O-CONTROLMERGEOPENREADRERUNREWRITESDSORTSTARTWRITEIf you intend to use the SORT statement under CICS (<strong>COBOL</strong> supports an interface<strong>for</strong> the SORT statement under CICS), you must change the CICS reserved-wordtable to remove the words in bold above from the list of words marked asrestricted.RELATED TASKS“Compiling with the CICS option” on page 411“Sorting under CICS” on page 231RELATED REFERENCES“WORD” on page 356Handling errors by using CICS HANDLEThe setting of the CBLPSHPOP runtime option affects the state of the HANDLEspecifications when a program calls <strong>COBOL</strong> subprograms using a CALL statement.When CBLPSHPOP is ON and a <strong>COBOL</strong> subprogram (not a nested program) is calledwith a CALL statement, the following actions occur:1. As part of program initialization, the run time suspends the HANDLEspecifications of the calling program (using EXEC CICS PUSH HANDLE).2. The default actions <strong>for</strong> HANDLE apply until the called program issues its ownHANDLE commands.3. As part of program termination, the run time reinstates the HANDLEspecifications of the calling program (using EXEC CICS POP HANDLE).If you use the CICS HANDLE CONDITION or CICS HANDLE AID commands, the LABELspecified <strong>for</strong> the CICS HANDLE command must be in the same PROCEDURE DIVISIONas the CICS command that causes branching to the CICS HANDLE label. You cannotuse the CICS HANDLE commands with the LABEL option to handle conditions, aids,or abends that were caused by another program invoked with the <strong>COBOL</strong> CALLstatement. Attempts to per<strong>for</strong>m cross-program branching by using the CICS HANDLEcommand with the LABEL option result in a transaction abend.416 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If a condition, aid, or abend occurs in a nested program, the LABEL <strong>for</strong> thecondition, aid, or abend must be in the same nested program; otherwiseunpredictable results occur.Per<strong>for</strong>mance considerations: When CBLPSHPOP is OFF, the run time does notper<strong>for</strong>m CICS PUSH or POP on a CALL to any <strong>COBOL</strong> subprogram. If thesubprograms do not use any of the EXEC CICS condition-handling commands, youcan run with CBLPSHPOP(OFF), thus eliminating the overhead of the PUSH HANDLEand POP HANDLE commands. As a result, per<strong>for</strong>mance can be improved compared torunning with CBLPSHPOP(ON).If you are migrating an application from the VS <strong>COBOL</strong> II run time to theLanguage Environment run time, see the related reference <strong>for</strong> in<strong>for</strong>mation aboutthe CBLPSHPOP option <strong>for</strong> additional considerations.“Example: handling errors by using CICS HANDLE”RELATED TASKS“Running efficiently with CICS, IMS, or VSAM” on page 676RELATED REFERENCES<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong> (CICS HANDLEcommands and the CBLPSHPOP runtime option)<strong>Enterprise</strong> <strong>COBOL</strong> Version 3 Per<strong>for</strong>mance TuningExample: handling errors by using CICS HANDLEThe following example shows the use of CICS HANDLE in <strong>COBOL</strong> programs.Program A has a CICS HANDLE CONDITION command and program B has no CICSHANDLE commands. Program A calls program B; program A also calls nestedprogram A1. A condition is handled in one of three scenarios.(1) CBLPSHPOP(ON): IftheCICS READ command in program B causes acondition, the condition is not handled by program A (the HANDLEspecifications are suspended because the run time per<strong>for</strong>ms a CICS PUSHHANDLE). The condition turns into a transaction abend.(2) CBLPSHPOP(OFF): IftheCICS READ command in program B causes acondition, the condition is not handled by program A (the run timediagnoses the attempt to per<strong>for</strong>m cross-program branching by using a CICSHANDLE command with the LABEL option). The condition turns into atransaction abend.(3) If the CICS READ command in nested program A1 causes a condition, theflow of control goes to label ERR-1, and unpredictable results occur.************************************************************ Program A ************************************************************ID DIVISION.PROGRAM-ID. A....PROCEDURE DIVISION.EXEC CICS HANDLE CONDITIONERROR(ERR-1)END-EXEC.CALL 'B' USING DFHEIBLK DFHCOMMAREA.CALL 'A1'....Chapter 20. Developing <strong>COBOL</strong> programs <strong>for</strong> CICS 417


THE-END.EXEC CICS RETURN END-EXEC.ERR-1....* Nested program A1.ID DIVISION.PROGRAM-ID. A1.PROCEDURE DIVISION.EXEC CICS READ (3)FILE('LEDGER')INTO(RECORD)RIDFLD(ACCTNO)END-EXEC.END PROGRAM A1.END PROGRAM A.************************************************************* Program B ************************************************************ID DIVISION.PROGRAM-ID. B....PROCEDURE DIVISION.EXEC CICS READ (1) (2)FILE('MASTER')INTO(RECORD)RIDFLD(ACCTNO)END-EXEC....END PROGRAM B.418 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2 environmentIn general, the coding <strong>for</strong> your <strong>COBOL</strong> program will be the same if you want theprogram to access a DB2 database. However, to retrieve, update, insert, and deleteDB2 data and use other DB2 services, you must use SQL statements.To communicate with DB2, do these steps:v Code any SQL statements that you need, delimiting them with EXEC SQL andEND-EXEC statements.v Either use the DB2 stand-alone precompiler, or compile with the SQL compileroption and use the DB2 coprocessor.RELATED CONCEPTS“DB2 coprocessor”“<strong>COBOL</strong> and DB2 CCSID determination” on page 425RELATED TASKS“Coding SQL statements” on page 420“Compiling with the SQL option” on page 423“Choosing the DYNAM or NODYNAM compiler option” on page 429DB2 coprocessorRELATED REFERENCES“Differences in how the DB2 precompiler and coprocessor behave” on page 427When you use the DB2 coprocessor (called SQL statement coprocessor by DB2), thecompiler handles your source program that contains embedded SQL statementswithout your having to use a separate precompile step.|To use the DB2 coprocessor, specify the SQL compiler option.When the compiler encounters SQL statements in the source program, it interfaceswith the DB2 coprocessor. This coprocessor takes appropriate actions <strong>for</strong> the SQLstatements and indicates to the compiler which native <strong>COBOL</strong> statements togenerate <strong>for</strong> them.Although the use of a separate precompile step continues to be supported, it isrecommended that you use the coprocessor instead:vvvInteractive debugging with Debug Tool is enhanced when you use thecoprocessor because you see the SQL statements (not the generated <strong>COBOL</strong>source) in the listing.The <strong>COBOL</strong> compiler listing includes the error diagnostics (such as syntax errorsin the SQL statements) that the DB2 coprocessor generates.Certain restrictions on the use of <strong>COBOL</strong> language that apply when you use theprecompile step do not apply when you use the DB2 coprocessor. With thecoprocessor:– You can use SQL statements in any nested program. (With the precompiler,SQL statements are restricted to the outermost program.)– You can use SQL statements in copybooks.– REPLACE statements work in SQL statements.© Copyright IBM Corp. 1991, 2009 419


Compiling with the DB2 coprocessor generates a DB2 database request module(DBRM) along with the usual <strong>COBOL</strong> compiler outputs such as object module andlisting. The DBRM writes to the data set that you specified in the DBRMLIB DDstatement in the JCL <strong>for</strong> the <strong>COBOL</strong> compile step. As input to the DB2 bindprocess, the DBRM data set contains in<strong>for</strong>mation about the SQL statements andhost variables in the program.RELATED CONCEPTS“<strong>COBOL</strong> and DB2 CCSID determination” on page 425RELATED TASKS“Compiling with the SQL option” on page 423Coding SQL statementsRELATED REFERENCES“Differences in how the DB2 precompiler and coprocessor behave” on page 427“SQL” on page 345Delimit SQL statements with EXEC SQL and END-EXEC. The EXEC SQL and END-EXECdelimiters must each be complete on one line. You cannot continue them acrossmultiple lines.You also need to do these special steps:v Code an EXEC SQL INCLUDE statement to include an SQL communication area(SQLCA) in the WORKING-STORAGE SECTION or LOCAL-STORAGE SECTION of theoutermost program. LOCAL-STORAGE is recommended <strong>for</strong> recursive programs andprograms that use the THREAD compiler option.v Declare all host variables that you use in SQL statements in the WORKING-STORAGESECTION, LOCAL-STORAGE SECTION, orLINKAGE SECTION. However, you do not needto identify them with EXEC SQL BEGIN DECLARE SECTION and EXEC SQL ENDDECLARE SECTION.Restriction: You cannot use SQL statements in object-oriented classes or methods.RELATED TASKS“Using SQL INCLUDE with the DB2 coprocessor”“Using character data in SQL statements” on page 421“Using national decimal data in SQL statements” on page 422“Using national group items in SQL statements” on page 422“Using binary items in SQL statements” on page 423“Determining the success of SQL statements” on page 423DB2 Application <strong>Programming</strong> and SQL <strong>Guide</strong> (Coding SQL statements in a<strong>COBOL</strong> application)RELATED REFERENCES“Code-page determination <strong>for</strong> string host variables in SQL statements” on page 426DB2 SQL ReferenceUsing SQL INCLUDE with the DB2 coprocessorAn SQL INCLUDE statement is treated identically to a native <strong>COBOL</strong> COPY statementwhen you use the SQL compiler option.420 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The following two lines are there<strong>for</strong>e treated the same way. (The period that endsthe EXEC SQL INCLUDE statement is required.)EXEC SQL INCLUDE name END-EXEC.COPY "name".The processing of the name in an SQL INCLUDE statement follows the same rules asthose of the literal in a COPY literal-1 statement that does not have a REPLACINGphrase.The library search order <strong>for</strong> SQL INCLUDE statements is the same SYSLIBconcatenation as the compiler uses to resolve <strong>COBOL</strong> COPY statements that do notspecify a library-name.RELATED REFERENCESChapter 18, “Compiler-directing statements,” on page 363“Differences in how the DB2 precompiler and coprocessor behave” on page 427COPY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using character data in SQL statementsYou can code any of the following USAGE clauses to describe host variables <strong>for</strong>character data that you use in EXEC SQL statements: USAGE DISPLAY <strong>for</strong> single-byteor UTF-8 data, USAGE DISPLAY-1 <strong>for</strong> DBCS data, or USAGE NATIONAL <strong>for</strong> UTF-16data.When you use the stand-alone DB2 precompiler, you must specify the code page(CCSID) in EXEC SQL DECLARE statements <strong>for</strong> host variables that are declared withUSAGE NATIONAL. You must specify the code page <strong>for</strong> host variables that aredeclared with USAGE DISPLAY or DISPLAY-1 only if the CCSID that is in effect <strong>for</strong>the <strong>COBOL</strong> CODEPAGE compiler option does not match the CCSIDs that are used byDB2 <strong>for</strong> character and graphic data.Consider the following code. The two highlighted statements are unnecessarywhen you use the integrated DB2 coprocessor (with the SQLCCSID compiler option,as detailed in the related concept below), because the code-page in<strong>for</strong>mation ishandled implicitly.CBL CODEPAGE(1140) NSYMBOL(NATIONAL)...WORKING-STORAGE SECTION.EXEC SQL INCLUDE SQLCA END-EXEC.01 INT1 PIC S9(4) USAGE COMP.01 C1140.49 C1140-LEN PIC S9(4) USAGE COMP.49 C1140-TEXT PIC X(50).EXEC SQL DECLARE :C1140 VARIABLE CCSID 1140 END-EXEC.01 G1200.49 G1200-LEN PIC S9(4) USAGE COMP.49 G1200-TEXT PIC N(50) USAGE NATIONAL.EXEC SQL DECLARE :G1200 VARIABLE CCSID 1200 END-EXEC....EXEC SQL FETCH C1 INTO :INT1, :C1140, :G1200 END-EXEC.If you specify EXEC SQL DECLARE variable-name VARIABLE CCSID nnnn END-EXEC, thatspecification overrides the implied CCSID. For example, the following code wouldcause DB2 to treat C1208-TEXT as encoded in UTF-8 (CCSID 1208) rather than asencoded in the CCSID in effect <strong>for</strong> the <strong>COBOL</strong> CODEPAGE compiler option:Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2 environment 421


01 C1208.49 C1208-LEN PIC S9(4) USAGE COMP.49 C1208-TEXT PIC X(50).EXEC SQL DECLARE :C1208 VARIABLE CCSID 1208 END-EXEC.The NSYMBOL compiler option has no effect on a character literal inside an EXEC SQLstatement. Character literals in an EXEC SQL statement follow the SQL rules <strong>for</strong>character constants.RELATED CONCEPTS“<strong>COBOL</strong> and DB2 CCSID determination” on page 425RELATED TASKSDB2 Application <strong>Programming</strong> and SQL <strong>Guide</strong> (Coding SQL statements in a<strong>COBOL</strong> application)RELATED REFERENCES“Differences in how the DB2 precompiler and coprocessor behave” on page 427“CODEPAGE” on page 310DB2 SQL ReferenceUsing national decimal data in SQL statementsYou can use national decimal host variables in EXEC SQL statements when you useeither the integrated DB2 coprocessor or the DB2 precompiler. You do not need tospecify the CCSID in EXEC SQL DECLARE statements in either case. CCSID 1200 isused automatically.Any national decimal host variable that you specify in an EXEC SQL statement musthave the following characteristics:v It must be signed.v It must be specified with the SIGN LEADING SEPARATE clause.v USAGE NATIONAL must be in effect implicitly or explicitly.RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49RELATED TASKS“Defining national numeric data items” on page 129RELATED REFERENCES“Differences in how the DB2 precompiler and coprocessor behave” on page 427Using national group items in SQL statementsYou can use a national group item as a host variable in an EXEC SQL statement. Thenational group item is treated with group semantics (that is, as shorthand <strong>for</strong> theset of host variables that are subordinate to the group item) rather than as anelementary item.Because all subordinate items in a national group must have USAGE NATIONAL, anational group item cannot describe a variable-length string.RELATED TASKS“Using national groups” on page 130422 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Using binary items in SQL statementsFor binary data items that you specify in an EXEC SQL statement, you can declarethe data items as either USAGE COMP-5 or as USAGE BINARY, COMP, orCOMP-4.If you declare the binary data items as USAGE BINARY, COMP, orCOMP-4, use theTRUNC(BIN) option. (This technique might have a larger effect on per<strong>for</strong>mance thanusing USAGE COMP-5 on individual data items.) If instead TRUNC(OPT) or TRUNC(STD)is in effect, the compiler accepts the items but the data might not be valid becauseof the decimal truncation rules. You need to ensure that truncation does not affectthe validity of the data.RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49RELATED REFERENCES“TRUNC” on page 353Determining the success of SQL statementsWhen DB2 finishes executing an SQL statement, DB2 sends a return code in theSQLCA structure, with one exception, to indicate whether the operation succeededor failed. Your program should test the return code and take any necessary action.The exception occurs when a program runs under DSN from one of the alternateentry points of the TSO batch mode module IKJEFT01 (IKJEFT1A or IKJEFT1B). Inthis case, the return code is passed in register 15.After execution of SQL statements, the content of the RETURN-CODE special registermight not be valid. There<strong>for</strong>e, even if your <strong>COBOL</strong> program terminates normallyafter successfully using SQL statements, the job step could end with an undefinedreturn code. To ensure that a meaningful return code is given at termination, setthe RETURN-CODE special register be<strong>for</strong>e terminating your program.RELATED TASKSDB2 Application <strong>Programming</strong> and SQL <strong>Guide</strong> (Coding SQL statements in a<strong>COBOL</strong> application)Compiling with the SQL optionYou use the SQL compiler option to enable the DB2 coprocessor and to specify DB2suboptions.You can specify the SQL option in any of the compiler option sources: compilerinvocation, PROCESS or CBL statements, or installation default. You cannot specifyDB2 suboptions when the SQL option is the <strong>COBOL</strong> installation default, but youcan specify default DB2 suboptions by customizing the DB2 product installationdefaults.The DB2 suboption string that you provide in the SQL compiler option is madeavailable to the DB2 coprocessor. Only the DB2 coprocessor views the contents ofthe string.To use the DB2 coprocessor, you must compile with the options that are shown inthe table below, and DB2 must be available on the machine on which you compile.Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2 environment 423


Table 62. Compiler options required with the DB2 coprocessorCompiler optionSQLLIBSIZE(xxx)CommentIf you also use NOLIB, LIB is <strong>for</strong>ced on.Must be specified with SQLxxx is a size value (not MAX) that leaves enough storage in the userregion <strong>for</strong> the DB2 coprocessor services.You can use standard JCL procedural statements to compile your program with theDB2 coprocessor. In addition to specifying the above compiler options, specify thefollowing items in your JCL:vvDBRMLIB DD statement with the location <strong>for</strong> the generated database requestmodule (DBRM).STEPLIB override <strong>for</strong> the <strong>COBOL</strong> step, adding the data set that contains the DB2coprocessor services, unless these services are in the LNKLST. Typically, this dataset is DSN910.SDSNLOAD, but your installation might have changed the name.For example, you might have the following lines in your JCL://DBRMLIB DD DSN=PAYROLL.MONTHLY.DBRMLIB.DATA(MASTER),DISP=SHR//STEPLIB DD DSN=DSN910.SDSNLOAD,DISP=SHR|||||||Compiling a batch of programs: If you use the SQL option when compiling asource file that contains a sequence of <strong>COBOL</strong> programs (a batch compilesequence), SQL must be in effect <strong>for</strong> only the first program of the sequence.Although you can specify SQL upon compiler invocation, the option will be ineffect <strong>for</strong> only the first program. If you specify SQL in a CBL or PROCESS statement<strong>for</strong> a program other than the first program in the batch, you will receive acompiler diagnostic message.RELATED CONCEPTS“DB2 coprocessor” on page 419“<strong>COBOL</strong> and DB2 CCSID determination” on page 425RELATED TASKS“Separating DB2 suboptions”“Choosing the DYNAM or NODYNAM compiler option” on page 429RELATED REFERENCES“DYNAM” on page 320“SQL” on page 345DB2 Command ReferenceSeparating DB2 suboptionsBecause of the concatenation of multiple SQL option specifications, you canseparate DB2 suboptions (which might not fit in one CBL statement) into multipleCBL statements.The options that you include in the suboption string are cumulative. The compilerconcatenates these suboptions from multiple sources in the order that they arespecified. For example, suppose that your source file has the following code://STEP1 EXEC IGYWC, ...// PARM.<strong>COBOL</strong>='SQL("string1")'//<strong>COBOL</strong>.SYSIN DD *424 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


CBL SQL("string2")CBL SQL("string3")IDENTIFICATION DIVISION.PROGRAM-ID. DRIVER1.During compilation, the compiler passes the following suboption string to the DB2coprocessor:"string1 string2 string3"The concatenated strings are delimited with single spaces. If the compiler findsmultiple instances of the same SQL suboption, the last specification of thatsuboption in the concatenated string takes effect. The compiler limits the length ofthe concatenated DB2 suboption string to 4 KB.<strong>COBOL</strong> and DB2 CCSID determinationAll DB2 string data other than BLOB, BINARY, and VARBINARY data has anassociated encoding scheme and a coded character set ID (CCSID). This is true <strong>for</strong>fixed-length and variable-length character strings, fixed-length and variable-lengthgraphic character strings, CLOB host variables, and DBCLOB host variables.When you use the integrated DB2 coprocessor, the determination of the code pageCCSID that will be associated with the string host variables used in SQL statementprocessing depends on the setting of the <strong>COBOL</strong> SQLCCSID option, on theprogramming techniques used, and on various DB2 configuration options.When you use the SQL and SQLCCSID <strong>COBOL</strong> compiler options, the CCSID valuennnnn that is specified in the CODEPAGE compiler option, or that is determined fromthe <strong>COBOL</strong> data type of a host variable, is communicated automatically from<strong>COBOL</strong> to DB2. DB2 associates the <strong>COBOL</strong> CCSID with host variables, overridingthe CCSID that would otherwise be implied by DB2 external mechanisms anddefaults. This associated CCSID is used <strong>for</strong> the processing of the SQL statementsthat reference host variables.When you use the SQL and N<strong>OS</strong>QLCCSID compiler options, the CCSID value nnnnnthat is specified in the CODEPAGE compiler option is used only <strong>for</strong> processing<strong>COBOL</strong> statements within the <strong>COBOL</strong> program; that CCSID is not used <strong>for</strong> theprocessing of SQL statements. Instead, DB2 assumes in processing SQL statementsthat host variable data values are encoded according to the CCSID or CCSIDs thatare specified through DB2 external mechanisms and defaults.RELATED CONCEPTS“DB2 coprocessor” on page 419RELATED TASKS“<strong>Programming</strong> with the SQLCCSID or N<strong>OS</strong>QLCCSID option” on page 426RELATED REFERENCES“Code-page determination <strong>for</strong> string host variables in SQL statements” on page 426“CODEPAGE” on page 310“SQL” on page 345“SQLCCSID” on page 347Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2 environment 425


Code-page determination <strong>for</strong> string host variables in SQLstatementsWhen you use the integrated DB2 coprocessor (SQL compiler option), the code page<strong>for</strong> processing string host variables in SQL statements is determined as shownbelow, in descending order of precedence.vvvvvvvvA host variable that has USAGE NATIONAL is always processed by DB2 usingCCSID 1200 (Unicode UTF-16). For example:01 hostvariable pic n(10) usage national.An alphanumeric host variable that has an explicit FOR BIT DATA declaration isset by DB2 to CCSID 66535, which indicates that the variable does not representencoded characters. For example:EXEC SQL DECLARE hostvariable VARIABLE FOR BIT DATA END-EXECA BLOB, BINARY, or VARBINARY host variable has no CCSID association.These string types do not represent encoded characters.A host variable <strong>for</strong> which you specify an explicit CCSID override in the SQLDAis processed with that CCSID.A host variable that you specify in a declaration with an explicit CCSID isprocessed with that CCSID. For example:EXEC SQL DECLARE hostvariable VARIABLE CCSID nnnnn END-EXECAn alphanumeric host variable, if the SQLCCSID compiler option is in effect, isprocessed with the CCSID nnnnn from the CODEPAGE compiler option.A DBCS host variable, if the SQLCCSID option is in effect, is processed with themapped value mmmmm, which is the pure DBCS CCSID component of themixed (MBCS) CCSID nnnnn from the CODEPAGE(nnnnn) compiler option.An alphanumeric or DBCS host variable, if the N<strong>OS</strong>QLCCSID option is in effect, isprocessed with the CCSID from the DB2 ENCODING bind option, if specified,or from the APPLICATION ENCODING set in DSNHDECP through the DB2installation panel DSNTIPF.RELATED REFERENCES“CODEPAGE” on page 310“SQLCCSID” on page 347<strong>Programming</strong> with the SQLCCSID or N<strong>OS</strong>QLCCSID optionIn general, the SQLCCSID option is recommended <strong>for</strong> new applications that use theintegrated DB2 coprocessor, and as a long-term direction <strong>for</strong> existing applications.The N<strong>OS</strong>QLCCSID option is recommended as a mechanism <strong>for</strong> migrating existingprecompiler-based applications to use the integrated DB2 coprocessor.The SQLCCSID option is recommended <strong>for</strong> <strong>COBOL</strong>-DB2 applications that have anyof these characteristics:v Use <strong>COBOL</strong> Unicode supportvvUse other <strong>COBOL</strong> syntax that is indirectly sensitive to CCSID encoding, such asXML support or object-oriented syntax <strong>for</strong> Java interoperabilityProcess character data that is encoded in a CCSID that is different from thedefault CCSID assumed by DB2The N<strong>OS</strong>QLCCSID option is recommended <strong>for</strong> applications that require the highestcompatibility with the behavior of the DB2 precompiler.426 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


For applications that use <strong>COBOL</strong> alphanumeric data items as host variablesinteracting with DB2 string data that is defined with the FOR BIT DATA subtype,you must either:v Use the N<strong>OS</strong>QLCCSID compiler optionv Specify explicit FOR BIT DATA declarations <strong>for</strong> those host variables, <strong>for</strong> example:EXEC SQL DECLARE hostvariable VARIABLE FOR BIT DATA END-EXECUsage notesv If you use the DB2 DCLGEN command to generate <strong>COBOL</strong> declarations <strong>for</strong> a table,you can optionally create FOR BIT DATA declarations automatically. To do so,specify the DCLBIT(YES) option of the DCLGEN command.v Per<strong>for</strong>mance consideration: Using the SQLCCSID compiler option could result insome per<strong>for</strong>mance overhead in SQL processing, because with SQLCCSID in effectthe default DB2 CCSID association mechanism is overridden with a mechanismthat works on a per-host-variable basis.RELATED CONCEPTS“DB2 coprocessor” on page 419RELATED REFERENCES“SQLCCSID” on page 347Differences in how the DB2 precompiler and coprocessor behaveThe sections that follow enumerate the differences in behavior between thestand-alone <strong>COBOL</strong> DB2 precompiler and the integrated <strong>COBOL</strong> DB2 coprocessor.Period at the end of EXEC SQL INCLUDE statementsPrecompiler: The DB2 precompiler does not require that a period end each EXECSQL INCLUDE statement. If a period is specified, the precompiler processes it as partof the statement. If a period is not specified, the precompiler accepts the statementas if a period had been specified.Coprocessor: The DB2 coprocessor treats each EXEC SQL INCLUDE statement like aCOPY statement, and requires that a period end the statement. For example:IFA=BTHENEXEC SQL INCLUDE some_code_here END-EXEC.ELSE...END-IFNote that the period does not terminate the IF statement.EXEC SQL INCLUDE and nested COPY REPLACINGPrecompiler: With the DB2 precompiler, an EXEC SQL INCLUDE statement canreference a copybook that contains a COPY statement that uses the REPLACINGphrase.Coprocessor: With the DB2 coprocessor, an EXEC SQL INCLUDE statement cannotreference a copybook that contains a COPY statement that uses the REPLACINGphrase. The coprocessor processes each EXEC SQL INCLUDE statement identically to aCOPY statement, and nested COPY statements cannot have the REPLACING phrase.Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2 environment 427


EXEC SQL and REPLACE or COPY REPLACINGPrecompiler: With the DB2 precompiler, <strong>COBOL</strong> REPLACE statements and theREPLACING phrase of the COPY statement act on the expanded source created fromthe EXEC SQL statement. <strong>COBOL</strong> rules <strong>for</strong> REPLACE and REPLACING are used.Coprocessor: With the DB2 coprocessor, REPLACE and COPY...REPLACINGstatements act on the original source program, including EXEC SQL statements.Different behavior can result, as in the following example:REPLACE == ABC == By == XYZ ==.01 G.02 ABC PIC X(10)....EXEC SQL SELECT * INTO :G.ABC FROM TABLE1 END-EXECWith the precompiler, the reference to G.ABC will appear as ABC of G in theexpanded source and will be replaced with XYZ of G. With the coprocessor,replacement will not occur, because ABC is not delimited by separators in theoriginal source string G.ABC.Source code after an END-EXEC statementPrecompiler: The DB2 precompiler ignores any code that follows END-EXECstatements on the same line.Coprocessor: The DB2 coprocessor processes code that follows END-EXEC statementson the same line.Multiple definitions of host variablesPrecompiler: The DB2 precompiler does not require that host variable references beunique. The first definition that maps to a valid DB2 data type is used.Coprocessor: The DB2 coprocessor requires that each host variable reference beunique. The coprocessor diagnoses nonunique references to host variables. Youmust fully qualify host variable references to make them unique.EXEC SQL statement continuation linesPrecompiler: The DB2 precompiler requires that EXEC SQL statements start incolumns 12 through 72. Continuation lines of the statements can start anywhere incolumns 8 through 72.Coprocessor: The DB2 coprocessor requires that all lines of an EXEC SQL statement,including continuation lines, be coded in columns 12 through 72.Bit-data host variablesPrecompiler: With the DB2 precompiler, a <strong>COBOL</strong> alphanumeric data item can beused as a host variable to hold DB2 character data that has subtype FOR BIT DATA.An explicit EXEC SQL DECLARE VARIABLE statement that declares that host variableas FOR BIT DATA is not required.428 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Coprocessor: With the DB2 coprocessor, a <strong>COBOL</strong> alphanumeric data item can beused as a host variable to hold DB2 character data that has subtype FOR BIT DATAif an explicit EXEC SQL DECLARE VARIABLE statement <strong>for</strong> that host variable isspecified in the <strong>COBOL</strong> program. For example:EXEC SQL DECLARE :HV1 VARIABLE FOR BIT DATA END-EXEC.As an alternative to adding EXEC SQL DECLARE ...FORBITDATA statements, youcan use the N<strong>OS</strong>QLCCSID compiler option. For details, see the related reference aboutcode-page determination below.SQL-INIT-FLAGPrecompiler: With the DB2 precompiler, if you pass host variables that might belocated at different addresses when the program is called more than once, thecalled program must reset SQL-INIT-FLAG. Resetting this flag indicates to DB2 thatstorage must be initialized when the next SQL statement runs. To reset the flag,insert the statement MOVE ZERO TO SQL-INIT-FLAG in the PROCEDURE DIVISION of thecalled program ahead of any executable SQL statements that use those hostvariables.Coprocessor: With the DB2 coprocessor, the called program does not need to resetSQL-INIT-FLAG. AnSQL-INIT-FLAG is automatically defined in the program to aidprogram portability. However, statements that modify SQL-INIT-FLAG, such as MOVEZERO TO SQL-INIT-FLAG, have no effect on the SQL processing in the program.RELATED CONCEPTS“DB2 coprocessor” on page 419RELATED REFERENCES“Code-page determination <strong>for</strong> string host variables in SQL statements” on page 426“SQLCCSID” on page 347Choosing the DYNAM or NODYNAM compiler optionFor <strong>COBOL</strong> programs that have EXEC SQL statements, your choice of the compileroption DYNAM or NODYNAM depends on the operating environment.When you run under:v TSO or IMS: You can use either the DYNAM or NODYNAM compiler option.Note that IMS and DB2 share a common alias name, DSNHLI, <strong>for</strong> the languageinterface module. You must concatenate your libraries as follows:– If you use IMS with the DYNAM option, concatenate the IMS library first.– If you run your application only under DB2, concatenate the DB2 library first.v CICS or the DB2 call attach facility (CAF): You must use the NODYNAM compileroption.Because stored procedures use CAF, you must also compile <strong>COBOL</strong> storedprocedures with the NODYNAM option.RELATED TASKS“Compiling with the SQL option” on page 423DB2 Application <strong>Programming</strong> and SQL <strong>Guide</strong> (<strong>Programming</strong> <strong>for</strong> the callattachment facility)Chapter 21. <strong>Programming</strong> <strong>for</strong> a DB2 environment 429


RELATED REFERENCES“DYNAM” on page 320430 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 22. Developing <strong>COBOL</strong> programs <strong>for</strong> IMSAlthough much of the coding of a <strong>COBOL</strong> program will be the same whenrunning under IMS, be aware of the following recommendations and restrictions.In <strong>COBOL</strong>, IMS message processing programs (MPPs) do not use non-IMS input oroutput statements such as READ, WRITE, REWRITE, OPEN, and CL<strong>OS</strong>E.With <strong>Enterprise</strong> <strong>COBOL</strong>, you can invoke IMS facilities using the followinginterfaces:v CBLTDLI callv Language Environment callable service CEETDLIYou code calls to CEETDLI the same way as you code calls to CBLTDLI. CEETDLIbehaves essentially the same way as CBLTDLI.You can also run object-oriented <strong>COBOL</strong> programs in a Java dependent region. Youcan mix the object-oriented <strong>COBOL</strong> and Java languages in a single application.RELATED TASKS“Compiling and linking <strong>COBOL</strong> programs <strong>for</strong> running under IMS”“Using object-oriented <strong>COBOL</strong> and Java under IMS” on page 432“Calling a <strong>COBOL</strong> method from a Java application under IMS” on page 432“Building a mixed <strong>COBOL</strong>-Java application that starts with <strong>COBOL</strong>” on page 433“Writing mixed-language IMS applications” on page 434Compiling and linking <strong>COBOL</strong> programs <strong>for</strong> running under IMSFor best per<strong>for</strong>mance in the IMS environment, use the RENT compiler option. RENTcauses <strong>COBOL</strong> to generate reentrant code. You can then run your applicationprograms in either preloaded mode (the programs are always resident in storage) ornonpreload mode without having to recompile using different options.Preloading can boost per<strong>for</strong>mance because subsequent requests <strong>for</strong> a program canbe handled faster when the program is already in storage (rather than beingfetched from a library each time it is needed).For IMS programs, using the RENT compiler option is recommended. You must usethe RENT compiler option <strong>for</strong> a program that is to be run preloaded or bothpreloaded and nonpreloaded. When you preload a load module that contains<strong>COBOL</strong> programs, all of the <strong>COBOL</strong> programs in that load module must becompiled using the RENT option.You can place programs compiled with the RENT option in the z/<strong>OS</strong> link pack area.There they can be shared among the IMS dependent regions.To run above the 16-MB line, an application program must be compiled with eitherRENT or NORENT RMODE(ANY). The data <strong>for</strong> IMS application programs can resideabove the 16-MB line, and you can use DATA(31) RENT or RMODE(ANY) NORENT <strong>for</strong>programs that use IMS services.© Copyright IBM Corp. 1991, 2009 431


For proper execution of <strong>COBOL</strong> programs under IMS, observe the followingguidelines <strong>for</strong> the link-edit attributes:vvTo link load modules that contain only <strong>COBOL</strong> programs compiled with theRENT compiler option, link as RENT.To link load modules that contain a mixture of <strong>COBOL</strong> RENT programs and otherprograms, use the link-edit attributes recommended <strong>for</strong> the other programs.RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Choosing the DYNAM or NODYNAM compiler option” on page 429Language Environment <strong>Programming</strong> <strong>Guide</strong> (Condition handling under IMS)RELATED REFERENCES“DATA” on page 314“RENT” on page 341<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong> (IMS considerations)Using object-oriented <strong>COBOL</strong> and Java under IMSYou can mix object-oriented <strong>COBOL</strong> and Java in an application that runs in a Javadependent region.For example, you can:v Call a <strong>COBOL</strong> method from a Java application. You can build the messagingportion of your application in Java and call <strong>COBOL</strong> methods to access IMSdatabases.v Build a mixed <strong>COBOL</strong> and Java application that starts with the main method ofa <strong>COBOL</strong> class and that invokes Java routines.You must run these applications in either a Java message processing (JMP)dependent region or a Java batch processing (JBP) dependent region. A programthat reads from the message queue (regardless of the language) must run in a JMPdependent region.RELATED TASKS“Defining a factory section” on page 594Chapter 30, “Writing object-oriented programs,” on page 561Chapter 31, “Communicating with Java methods,” on page 607Chapter 16, “Compiling, linking, and running OO applications,” on page 291IMS Application <strong>Programming</strong> <strong>Guide</strong>Calling a <strong>COBOL</strong> method from a Java application under IMSYou can use the object-oriented language support in <strong>Enterprise</strong> <strong>COBOL</strong> to write<strong>COBOL</strong> methods that a Java program can call under IMS.When you define a <strong>COBOL</strong> class and compile it using <strong>Enterprise</strong> <strong>COBOL</strong>, thecompiler generates a Java class definition with native methods and the object codethat implements those native methods. You can then create an instance and invokethe methods of this class from a Java program that runs in a Java dependentregion, just as you would use any other class.432 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


For example, you can define a <strong>COBOL</strong> class that uses the appropriate DL/I calls toaccess an IMS database. To make the implementation of this class available to aJava program, do the following steps:1. Compile the <strong>COBOL</strong> class using <strong>Enterprise</strong> <strong>COBOL</strong>. The compiler generates aJava source file (.java) that contains the class definition, and an object module(.o) that contains the implementation of the native methods.2. Compile the generated Java source file using the Java compiler. The Javacompiler creates a class file (.class).3. Link the object code into a dynamic link library (DLL) in the z/<strong>OS</strong> UNIX filesystem (.so). The directory that contains the <strong>COBOL</strong> DLLs must be listed in theLIBPATH, as specified in the IMS.PROCLIB member that is indicated by theENVIRON= parameter of the IMS region procedure.4. Update the sharable application class path in the master JVM options member(ibm.jvm.sharable.application.class.path in the IMS.PROCLIB member that isspecified by the JVMOPMAS= parameter of the IMS region procedure) toenable the JVM to access the Java class file.A Java program cannot call procedural <strong>COBOL</strong> programs directly. To reuse existing<strong>COBOL</strong> IMS code, use one of the following techniques:v Restructure the <strong>COBOL</strong> code as a method in a <strong>COBOL</strong> class.vWrite a <strong>COBOL</strong> class definition and method that serves as a wrapper <strong>for</strong> theexisting procedural code. The wrapper code can use <strong>COBOL</strong> CALL statements toaccess procedural <strong>COBOL</strong> programs.RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291“Structuring OO applications” on page 603“Wrapping procedure-oriented <strong>COBOL</strong> programs” on page 603IMS Application <strong>Programming</strong> <strong>Guide</strong>Building a mixed <strong>COBOL</strong>-Java application that starts with<strong>COBOL</strong>An application that runs in a Java dependent region must start with the mainmethod of a class.A <strong>COBOL</strong> class definition that has a main factory method meets this requirement;there<strong>for</strong>e, you can use a main factory method as the first routine of a mixed<strong>COBOL</strong> and Java application under IMS.<strong>Enterprise</strong> <strong>COBOL</strong> generates a Java class with a main method, which the Javadependent region can find, instantiate, and invoke. Although you can code theentire application in <strong>COBOL</strong>, you would probably build this type of application tocall a Java routine. When the <strong>COBOL</strong> runtime runs within the JVM of a Javadependent region, it automatically finds and uses this JVM to invoke methods onJava classes.The <strong>COBOL</strong> application should use DL/I calls <strong>for</strong> processing messages (GU and GN)and synchronizing transactions (CHKP).RELATED TASKS“Structuring OO applications” on page 603IMS Application <strong>Programming</strong> <strong>Guide</strong>IBM SDK <strong>for</strong> Java - Tools DocumentationChapter 22. Developing <strong>COBOL</strong> programs <strong>for</strong> IMS 433


Writing mixed-language IMS applicationsWhen you write mixed-language IMS applications, you need to be aware of theeffects of the STOP RUN statement. You also need to understand how to processmessages and synchronize transactions, access databases, and use the applicationinterface block (AIB).RELATED TASKS“Using the STOP RUN statement”“Processing messages and synchronizing transactions”“Accessing databases”“Using the application interface block” on page 435Using the STOP RUN statementIf you use the STOP RUN statement in the <strong>COBOL</strong> portion of your application, thestatement terminates all <strong>COBOL</strong> and Java routines (including the JVM).Control is returned immediately to IMS. The program and the transaction are leftin a stopped state.Processing messages and synchronizing transactionsIMS message-processing applications must do all message processing andtransaction synchronization either in <strong>COBOL</strong> or Java, rather than distributing thislogic between application components written in both languages.<strong>COBOL</strong> components use CALL statements to DL/I services to process messages (GUand GN) and synchronize transactions (CHKP). Java components use Java classes <strong>for</strong>IMS to do these functions. You can use object instances of classes derived fromIMSFieldMessage to communicate entire IMS messages between the <strong>COBOL</strong> andJava components of the application.RELATED TASKSIMS Application <strong>Programming</strong> <strong>Guide</strong>RELATED REFERENCESIMS Application <strong>Programming</strong> API ReferenceAccessing databasesYou can use either Java, <strong>COBOL</strong>, or a mixture of the two languages to access IMSdatabases.Limitation: EXEC SQL statements <strong>for</strong> DB2 database access are not supported in<strong>COBOL</strong> routines that run in a Java dependent region.Recommendation: Do not access the same database program communication block(PCB) from both Java and <strong>COBOL</strong>. The Java and <strong>COBOL</strong> parts of the applicationshare the same database position. Changes in database position from calls in onepart of the application affect the database position in another part of theapplication. (This problem occurs whether the affected parts of an application arewritten in the same language or in different languages.)Suppose that a Java component of a mixed application builds an SQL SELECT clauseand uses Java Database Connectivity (JDBC) to query and retrieve results from an434 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


IMS database. The Java class libraries <strong>for</strong> IMS construct the appropriate request toIMS to establish the correct position in the database. If you then invoke a <strong>COBOL</strong>method that builds a segment search argument (SSA) and issues a GU (Get Unique)request to IMS against the same database PCB, the request probably altered theposition in the database <strong>for</strong> that PCB. If so, subsequent JDBC requests to retrievemore records by using the initial SQL SELECT clause are incorrect because thedatabase position changed. If you must access the same PCB from multiplelanguages, reestablish the database position after an interlanguage call be<strong>for</strong>e youaccess more records in the database.RELATED TASKSIMS Application <strong>Programming</strong> <strong>Guide</strong>Using the application interface block<strong>COBOL</strong> applications that run in a Java dependent region normally must use theAIB interface because the Java dependent region does not provide PCB addressesto its application.To use the AIB interface, specify the PCB requested <strong>for</strong> the call by placing the PCBname (which must be defined as part of the PSBGEN) in the resource name field ofthe AIB. (The AIB requires that all PCBs in a program specification block (PSB)definition have a name.) You do not specify the PCB address directly, and yourapplication does not need to know the relative PCB position in the PCB list. Uponthe completion of the call, the AIB returns the PCB address that corresponds to thePCB name that the application passed.Alternatively, you can obtain PCB addresses by making an IMS INQY call usingsubfunction FIND, and the PCB name as the resource name. The call returns theaddress of the PCB, which you can then pass to a <strong>COBOL</strong> program. (This approachstill requires that the PCB name be defined as part of the PSBGEN, but theapplication does not have to use the AIB interface.)“Example: using the application interface block”RELATED TASKSIMS Application <strong>Programming</strong> <strong>Guide</strong>Example: using the application interface block:||The following example shows how you can use the AIB interface in a <strong>COBOL</strong>application.Local-storage section.copy AIB....Linkage section.01 IOPCB.05 logtterm pic x(08).05 pic x(02).05 tpstat pic x(02).05 iodate pic s9(7) comp-3.05 iotime pic s9(7) comp-3.05 pic x(02).05 seqnum pic x(02).05 mod pic x(08).Procedure division.Move spaces to input-areaMove spaces to AIBMove "DFSAIB" to AIBRIDChapter 22. Developing <strong>COBOL</strong> programs <strong>for</strong> IMS 435


Move length of AIB to AIBRLENMove "IOPCB" to AIBRSNM1Move length of input-area to AIBOALENCall "CEETDLI" using GU, AIB, input-areaSet address of IOPCB to AIBRESA1If tpstat = spaces* . . process input message436 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 23. Running <strong>COBOL</strong> programs under z/<strong>OS</strong> UNIXTo run <strong>COBOL</strong> programs in the z/<strong>OS</strong> UNIX environment, compile them using<strong>Enterprise</strong> <strong>COBOL</strong> or <strong>COBOL</strong> <strong>for</strong> <strong>OS</strong>/390 & VM. The programs must be reentrant,so use the compiler and linker option RENT.If you are going to run the programs from the z/<strong>OS</strong> UNIX file system, use thelinker option AMODE 31. Any AMODE 24 program that you call from within a z/<strong>OS</strong>UNIX application must reside in an MVS PDS or PDSE.The following restrictions apply to running under z/<strong>OS</strong> UNIX:v SORT and MERGE statements are not supported.v You cannot use the old <strong>COBOL</strong> interfaces <strong>for</strong> preinitialization (runtime optionRTEREUS and functions IGZERRE and ILB<strong>OS</strong>TP0) to establish a reusableenvironment.v You cannot run a <strong>COBOL</strong> program compiled with the NOTHREAD option in morethan one thread. If you start a <strong>COBOL</strong> application in a second thread, you get asoftware condition from the <strong>COBOL</strong> run time. You can run NOTHREAD <strong>COBOL</strong>programs in the initial process thread (IPT) or in one non-IPT that you createfromaCorPL/I routine.You can run a <strong>COBOL</strong> program in more than one thread when you compile allthe <strong>COBOL</strong> programs in the application with the THREAD option.You can use Debug Tool to debug z/<strong>OS</strong> UNIX programs in remote debug mode,<strong>for</strong> example, by using the Debug Perspective of Rational Developer <strong>for</strong> System z,or in full-screen mode (MFI) using a VTAM ® terminal.RELATED TASKSChapter 15, “Compiling under z/<strong>OS</strong> UNIX,” on page 283“Running OO applications under z/<strong>OS</strong> UNIX” on page 293“Running in z/<strong>OS</strong> UNIX environments”“Setting and accessing environment variables” on page 438“Calling UNIX/P<strong>OS</strong>IX APIs” on page 440“Accessing main program parameters” on page 442Language Environment <strong>Programming</strong> <strong>Guide</strong>RELATED REFERENCES“RENT” on page 341Running in z/<strong>OS</strong> UNIX environmentsYou can run <strong>COBOL</strong> programs in any of the z/<strong>OS</strong> UNIX execution environments,either from within a z/<strong>OS</strong> UNIX shell or from outside a shell.vYou can run programs in either the OMVS shell (OMVS) or the ISPF shell(ISHELL).Enter the program-name at the shell prompt. The program must be in thecurrent directory or in your search path.You can specify runtime options only by setting the environment variable_CEE_RUNOPTS be<strong>for</strong>e starting the program.© Copyright IBM Corp. 1991, 2009 437


vYou can run programs that reside in a cataloged MVS data set from a shell byusing the tso utility. For example:tso "call 'my.loadlib(myprog)'"The ISPF shell can direct stdout and stderr only to a z/<strong>OS</strong> UNIX file, not toyour terminal.From outside a shell, you can run programs either under TSO/E or in batch.To call a <strong>COBOL</strong> program that resides in a z/<strong>OS</strong> UNIX file from the TSO/Eprompt, use the BPXBATCH utility or a spawn() syscall in a REXX exec.To call a <strong>COBOL</strong> program that resides in a z/<strong>OS</strong> UNIX file with the EXEC JCLstatement, use the BPXBATCH utility.RELATED TASKS“Running OO applications under z/<strong>OS</strong> UNIX” on page 293“Setting and accessing environment variables”“Calling UNIX/P<strong>OS</strong>IX APIs” on page 440“Accessing main program parameters” on page 442“Defining and allocating QSAM files” on page 166“Defining and allocating line-sequential files” on page 209“Allocating VSAM files” on page 200“Displaying values on a screen or in a file (DISPLAY)” on page 38Language Environment <strong>Programming</strong> <strong>Guide</strong> (Running P<strong>OS</strong>IX-enabled programs)RELATED REFERENCES“TEST” on page 349UNIX System Services User’s <strong>Guide</strong> (The BPXBATCH utility)Language Environment <strong>Programming</strong> ReferenceSetting and accessing environment variablesYou can set environment variables <strong>for</strong> z/<strong>OS</strong> UNIX <strong>COBOL</strong> programs either fromthe shell with commands export and set, or from the program.Although setting and resetting environment variables from the shell be<strong>for</strong>e youbegin to run a program is a typical procedure, you can set, reset, and accessenvironment variables from the program while it is running.If you are running a program with BPXBATCH, you can set environment variablesby using an STDENV DD statement.To reset an environment variable as if it had not been set, use the z/<strong>OS</strong> UNIX shellcommand unset. To reset an environment variable from a <strong>COBOL</strong> program, callthe setenv() function.To see the values of all environment variables, use the export command with noparameters. To access the value of an environment variable from a <strong>COBOL</strong>program, call the getenv() function.“Example: setting and accessing environment variables” on page 440RELATED TASKS“Running in z/<strong>OS</strong> UNIX environments” on page 437“Setting environment variables that affect execution” on page 439“Accessing main program parameters” on page 442438 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Running OO applications under z/<strong>OS</strong> UNIX” on page 293“Setting environment variables under z/<strong>OS</strong> UNIX” on page 283RELATED REFERENCES“Runtime environment variables”Language Environment <strong>Programming</strong> ReferenceMVS Program Management: User’s <strong>Guide</strong> and ReferenceSetting environment variables that affect executionTo set environment variables <strong>for</strong> UNIX <strong>COBOL</strong> programs from a shell, use theexport or set command. To set environment variables from within the program,call P<strong>OS</strong>IX functions setenv() or putenv().For example, to set the environment variable MYFILE:export MYFILE=/usr/mystuff/notes.txt“Example: setting and accessing environment variables” on page 440RELATED TASKS“Calling UNIX/P<strong>OS</strong>IX APIs” on page 440“Setting environment variables under z/<strong>OS</strong> UNIX” on page 283RELATED REFERENCES“Runtime environment variables”Runtime environment variablesSeveral runtime variables are of interest <strong>for</strong> <strong>COBOL</strong> programs.These are the runtime environment variables:_CEE_ENVFILESpecifies a file from which to read environment variables._CEE_RUNOPTSSpecifies runtime options.CLASSPATHSpecifies directory paths of Java .class files required <strong>for</strong> an OO application.COBJVMINITOPTIONSSpecifies Java virtual machine (JVM) options used when <strong>COBOL</strong> initializesa JVM._IGZ_SYSOUTSpecifies where to direct DISPLAY output. stdout and stderr are the onlyallowable values.LIBPATHSpecifies directory paths of dynamic link libraries.PATH Specifies directory paths of executable programs.STEPLIBSpecifies location of programs that are not in the LNKLST.RELATED TASKS“Displaying data on the system logical output device” on page 39Chapter 23. Running <strong>COBOL</strong> programs under z/<strong>OS</strong> UNIX 439


RELATED REFERENCESXL C/C++ <strong>Programming</strong> <strong>Guide</strong> (_CEE_ENVFILE)Language Environment <strong>Programming</strong> ReferenceExample: setting and accessing environment variablesCalling UNIX/P<strong>OS</strong>IX APIsThe following example shows how you can access and set environment variablesfrom a <strong>COBOL</strong> program by calling the standard P<strong>OS</strong>IX functions getenv() andputenv().Because getenv() and putenv() are C functions, you must pass arguments BY VALUE.Pass character strings as BY VALUE pointers that point to null-terminated strings.Compile programs that call these functions with the NODYNAM andPGMNAME(LONGMIXED) options.CBL pgmname(longmixed),nodynamIdentification division.Program-id. "envdemo".Data division.Working-storage section.01 P pointer.01 PATH pic x(5) value Z"PATH".01 var-ptr pointer.01 var-len pic 9(4) binary.01 putenv-arg pic x(14) value Z"MYVAR=ABCDEFG".01 rc pic 9(9) binary.Linkage section.01 var pic x(5000).Procedure division.* Retrieve and display the PATH environment variableSet P to address of PATHCall "getenv" using by value P returning var-ptrIf var-ptr = null thenDisplay "PATH not set"ElseSet address of var to var-ptrMove 0 to var-lenInspect var tallying var-len<strong>for</strong> characters be<strong>for</strong>e initial X"00"Display "PATH = " var(1:var-len)End-if* Set environment variable MYVAR to ABCDEFGSet P to address of putenv-argCall "putenv" using by value P returning rcIf rc not = 0 thenDisplay "putenv failed"Stop runEnd-ifGoback.You can call standard UNIX/P<strong>OS</strong>IX functions from z/<strong>OS</strong> UNIX programs andfrom traditional z/<strong>OS</strong> <strong>COBOL</strong> programs by using the CALL literal statement. Thesefunctions are part of Language Environment.Because these are C functions, you must pass arguments BY VALUE. Pass characterstrings as BY VALUE pointers that point to null-terminated strings. You must use thecompiler options NODYNAM and PGMNAME(LONGMIXED) when you compile programsthat call these functions.440 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


You can call the <strong>for</strong>k(), exec(), and spawn() functions from a <strong>COBOL</strong> program orfrom a non-<strong>COBOL</strong> program in the same process as <strong>COBOL</strong> programs. However,be aware of these restrictions:vvvFrom a <strong>for</strong>ked process you cannot access any <strong>COBOL</strong> sequential, indexed, orrelative files that were open when you issued the <strong>for</strong>k. File status code 92 isreturned if you attempt such access (CL<strong>OS</strong>E, READ, WRITE, REWRITE, DELETE, orSTART). You can access line-sequential files that were open at the time of a <strong>for</strong>k.You cannot use the <strong>for</strong>k() function in a process in which any of the followingconditions are true:– A <strong>COBOL</strong> SORT or MERGE is running.– A declarative is running.– The process has more than one Language Environment enclave (<strong>COBOL</strong> rununit).– The process has used any of the <strong>COBOL</strong> reusable environment interfaces.– The process has ever run an <strong>OS</strong>/VS <strong>COBOL</strong> or VS <strong>COBOL</strong> II program.With one exception, DD allocations are not inherited from a parent process to achild process. The exception is the local spawn, which creates a child process inthe same address space as the parent process. You request a local spawn bysetting the environment variable _BPX_ SHAREAS=YES be<strong>for</strong>e you invoke thespawn() function.The exec() and spawn() functions start a new Language Environment enclave inthe new UNIX process. There<strong>for</strong>e the target program of the exec() or spawn()function is a main program, and all <strong>COBOL</strong> programs in the process start in initialstate with all files closed.Sample code <strong>for</strong> calling some of the P<strong>OS</strong>IX routines is provided in the SIGYSAMPdata set.Table 63. Samples with P<strong>OS</strong>IX function callsPurpose Sample Functions usedShows how to use someof the file and directoryroutinesShows how to use theiconv routines to convertdataShows the use of theexec() routine to run anew program along withother process-relatedroutinesShows how to get theerrno valueIGYTFL1 v getcwd()v mkdir()v rmdir()v access()IGYTCNV v iconv_open()v iconv()v iconv_close()IGYTEXC, IGYTEXC1 v <strong>for</strong>k()v getpid()v getppid()v execl()v perror()v wait()IGYTERNO, IGYTGETE v perror()v fopen()Chapter 23. Running <strong>COBOL</strong> programs under z/<strong>OS</strong> UNIX 441


Table 63. Samples with P<strong>OS</strong>IX function calls (continued)Purpose Sample Functions usedShows the use of the IGYTMSQ, IGYTMSQ2 v ftok()interprocessv msgget()communication messageroutinesv msgsnd()v perror()v fopen()v fclose()v msgrcv()v msgctl()v perror()RELATED TASKS“Running in z/<strong>OS</strong> UNIX environments” on page 437“Setting and accessing environment variables” on page 438“Accessing main program parameters”Language Environment <strong>Programming</strong> <strong>Guide</strong>RELATED REFERENCESXL C/C++ Run-Time Library ReferenceUNIX System Services <strong>Programming</strong>: Assembler Callable Services ReferenceAccessing main program parametersWhen you run a <strong>COBOL</strong> program from the z/<strong>OS</strong> UNIX shell command line orwith an exec() or spawn() function, the parameter list consists of three parameterspassed by reference. You can access these parameters with standard <strong>COBOL</strong>coding.argument countA binary fullword integer that contains the number of elements in each ofthe arrays that are passed in the second and third parameters.argument length listAn array of pointers. The nth entry in the array is the address of afullword binary integer that contains the length of the nth entry in theargument list.argument listAn array of pointers. The nth entry in the array is the address of the nthcharacter string passed as an argument in the spawn() or exec() function orin the command invocation. Each character string is null-terminated.This array is never empty. The first argument is the character string thatrepresents the name of the file associated with the process being started.“Example: accessing main program parameters” on page 443RELATED TASKS“Running in z/<strong>OS</strong> UNIX environments” on page 437“Setting and accessing environment variables” on page 438“Calling UNIX/P<strong>OS</strong>IX APIs” on page 440442 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Example: accessing main program parametersThe following example shows the three parameters that are passed by reference.Identification division.Program-id. "EXECED".***************************************************************** This sample program displays arguments received via exec() ** function of z/<strong>OS</strong> UNIX *****************************************************************Data division.Working-storage section.01 curr-arg-count pic 9(9) binary value zero.Linkage section.01 arg-count pic 9(9) binary. (1)01 arg-length-list. (2)05 arg-length-addr pointer occurs 1 to 99999depending on curr-arg-count.01 arg-list. (3)05 arg-addr pointer occurs 1 to 99999depending on curr-arg-count.01 arg-length pic 9(9) binary.01 arg pic X(65536).Procedure division using arg-count arg-length-list arg-list.****************************************************************** Display number of arguments received ******************************************************************Display "Number of arguments received: " arg-count****************************************************************** Display each argument passed to this program ******************************************************************Per<strong>for</strong>m arg-count timesAdd 1 to curr-arg-count* ******************************************************** * Set address of arg-length to address of current ** * argument length and display ** *******************************************************Set Address of arg-lengthto arg-length-addr(curr-arg-count)Display"Length of Arg " curr-arg-count "="arg-length* ******************************************************** * Set address of arg to address of current argument ** * and display ** *******************************************************Set Address of arg to arg-addr(curr-arg-count)Display "Arg " curr-arg-count "="arg(1:arg-length)End-Per<strong>for</strong>mDisplay "Display of arguments complete."Goback.(1) This count contains the number of elements in the arrays that are passed inthe second and third parameters.(2) This array includes a pointer to the length of the nth entry in the argumentlist.(3) This array includes a pointer to the nth character string passed as anargument on the spawn() or exec() function or the command invocation.Chapter 23. Running <strong>COBOL</strong> programs under z/<strong>OS</strong> UNIX 443


444 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 4. Structuring complex applicationsChapter 24. Using subprograms . . . . . . 447Main programs, subprograms, and calls . . . . 447Ending and reentering main programs orsubprograms . . . . . . . . . . . . . 448Transferring control to another program . . . . 449Making static calls. . . . . . . . . . . 450Making dynamic calls . . . . . . . . . 451Canceling a subprogram. . . . . . . . 452When to use a dynamic call withsubprograms . . . . . . . . . . . 452AMODE switching . . . . . . . . . . 453Per<strong>for</strong>mance considerations of static anddynamic calls . . . . . . . . . . . . 455Making both static and dynamic calls . . . . 455Examples: static and dynamic CALL statements 456Calling nested <strong>COBOL</strong> programs . . . . . . 458Nested programs . . . . . . . . . . 458Example: structure of nested programs . . . 459Scope of names. . . . . . . . . . . 460Making recursive calls . . . . . . . . . . 461Calling to and from object-oriented programs . . 461Using procedure and function pointers . . . . . 462Deciding which type of pointer to use . . . . 463Calling alternate entry points . . . . . . . 463Making programs reentrant . . . . . . . . 464Prelinking certain DLLs . . . . . . . . . . 485Using CALL identifier with DLLs . . . . . . 485Search order <strong>for</strong> DLLs in the HFS . . . . . 486Using DLL linkage and dynamic calls together . . 486Using procedure or function pointers with DLLs 488Calling DLLs from non-DLLs . . . . . . . 488Example: calling DLLs from non-DLLs . . . . 489Using <strong>COBOL</strong> DLLs with C/C++ programs . . . 490Using DLLs in OO <strong>COBOL</strong> applications . . . . 491Chapter 27. Preparing <strong>COBOL</strong> programs <strong>for</strong>multithreading . . . . . . . . . . . . 493Multithreading . . . . . . . . . . . . . 494Choosing THREAD to support multithreading . . 495Transferring control to multithreaded programs 495Ending multithreaded programs . . . . . . . 496Processing files with multithreading . . . . . . 496File-definition (FD) storage . . . . . . . . 497Serializing file access with multithreading . . . 497Example: usage patterns of file input andoutput with multithreading. . . . . . . . 498Handling <strong>COBOL</strong> limitations with multithreading 499Chapter 25. Sharing data . . . . . . . . . 465Passing data. . . . . . . . . . . . . . 465Describing arguments in the calling program 467Describing parameters in the called program 468Testing <strong>for</strong> OMITTED arguments . . . . . . 468Coding the LINKAGE SECTION . . . . . . . 469Coding the PROCEDURE DIVISION <strong>for</strong> passingarguments . . . . . . . . . . . . . . 469Grouping data to be passed . . . . . . . 470Handling null-terminated strings . . . . . . 470Using pointers to process a chained list . . . 471Example: using pointers to process a chainedlist . . . . . . . . . . . . . . . 472Passing return-code in<strong>for</strong>mation . . . . . . . 474Understanding the RETURN-CODE specialregister . . . . . . . . . . . . . . 474Using PROCEDURE DIVISION RETURNING . ... . . . . . . . . . . . . . . . . 474Specifying CALL . . . RETURNING . . . . . 475Sharing data by using the EXTERNAL clause. . . 475Sharing files between programs (external files) . . 475Example: using external files . . . . . . . 476Input-output using external files . . . . . 476Chapter 26. Creating a DLL or a DLL application 481Dynamic link libraries (DLLs) . . . . . . . . 481Compiling programs to create DLLs . . . . . . 482Linking DLLs . . . . . . . . . . . . . 483Example: sample JCL <strong>for</strong> a procedural DLLapplication . . . . . . . . . . . . . . 484© Copyright IBM Corp. 1991, 2009 445


446 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 24. Using subprogramsMany applications consist of several separately compiled programs linked together.A run unit (the <strong>COBOL</strong> term that is synonymous with the Language Environmentterm enclave) includes one or more object programs and can include objectprograms written in other Language Environment member languages.Language Environment provides interlanguage support that lets your <strong>Enterprise</strong><strong>COBOL</strong> programs call and be called by programs that meet the requirements ofLanguage Environment.Name prefix alert: Do not use program-names that start with prefixes used by IBMproducts. If you use programs whose names start with such prefixes, CALLstatements might resolve to IBM library or compiler routines rather than to theintended program. For a list of prefixes to avoid, see the related task aboutidentifying a program.RELATED CONCEPTS“Main programs, subprograms, and calls”RELATED TASKS“Identifying a program” on page 5“Ending and reentering main programs or subprograms” on page 448“Transferring control to another program” on page 449“Making recursive calls” on page 461“Calling to and from object-oriented programs” on page 461“Using procedure and function pointers” on page 462“Making programs reentrant” on page 464“Handling <strong>COBOL</strong> limitations with multithreading” on page 499Language Environment Writing ILC Communication ApplicationsRELATED REFERENCESLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (Register conventions)Main programs, subprograms, and callsIf a <strong>COBOL</strong> program is the first program in a run unit, that <strong>COBOL</strong> program is themain program. Otherwise, it and all other <strong>COBOL</strong> programs in the run unit aresubprograms. No specific source-code statements or options identify a <strong>COBOL</strong>program as a main program or subprogram.Whether a <strong>COBOL</strong> program is a main program or subprogram can be significant<strong>for</strong> either of two reasons:v Effect of program termination statementsv State of the program when it is reentered after returningIn the PROCEDURE DIVISION, a program can call another program (generally called asubprogram), and this called program can itself call other programs. The programthat calls another program is referred to as the calling program, and the program itcalls is referred to as the called program. When the processing of the calledprogram is completed, the called program can either transfer control back to thecalling program or end the run unit.© Copyright IBM Corp. 1991, 2009 447


The called <strong>COBOL</strong> program starts running at the top of the PROCEDURE DIVISION.RELATED TASKS“Ending and reentering main programs or subprograms”“Transferring control to another program” on page 449“Making recursive calls” on page 461RELATED REFERENCESLanguage Environment <strong>Programming</strong> <strong>Guide</strong>Ending and reentering main programs or subprogramsWhether a program is left in its last-used state or its initial state, and to what callerit returns, can depend on the termination statements that you use.You can use any of three termination statements in a program, but they havedifferent effects, as shown in the table below.Table 64. Effects of termination statementsTerminationstatement Main program SubprogramEXIT PROGRAM No action takenReturn to calling program withoutending the run unit. An implicit EXITPROGRAM statement is generated if thecalled program has no next executablestatement.STOP RUNGOBACKReturn to calling program. 1 (Mightbe the operating system, andapplication will end.)STOP RUN terminates the run unit,and deletes all dynamically calledprograms in the run unit and allprograms link-edited with them. (Itdoes not delete the main program.)In a threaded environment, theentire Language Environmentenclave is terminated, including allthreads running within theenclave.Return to calling program. 1 (Mightbe the operating system, andapplication will end.)GOBACK terminates the run unit,and deletes all dynamically calledprograms in the run unit and allprograms link-edited with them. (Itdoes not delete the main program.)In a threaded environment, the threadis not terminated unless the program isthe first (oldest) one in the thread.Return directly to the program thatcalled the main program. 1 (Might bethe operating system, and applicationwill end.)STOP RUN terminates the run unit, anddeletes all dynamically called programsin the run unit and all programslink-edited with them. (It does notdelete the main program.)In a threaded environment, the entireLanguage Environment enclave isterminated, including all threadsrunning within the enclave.Return to calling program.In a threaded environment, if theprogram is the first program in athread, the thread is terminated. 2In a threaded environment, thethread is terminated. 2448 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 64. Effects of termination statements (continued)Terminationstatement Main program Subprogram1. If the main program is called by a program written in another language that does notfollow Language Environment linkage conventions, return is to this calling program.2. If the thread is the initial thread of execution in an enclave, the enclave is terminated.A subprogram is usually left in its last-used state when it terminates with EXITPROGRAM or GOBACK. The next time the subprogram is called in the run unit, itsinternal values are as they were left, except that return values <strong>for</strong> PERFORMstatements are reset to their initial values. (In contrast, a main program isinitialized each time it is called.)There are some cases where programs will be in their initial state:v A subprogram that is dynamically called and then canceled will be in the initialstate the next time it is called.v A program that has the INITIAL attribute will be in the initial state each time itis called.v Data items defined in the LOCAL-STORAGE SECTION will be reset to the initial statespecified by their VALUE clauses each time the program is called.RELATED CONCEPTS“Comparison of WORKING-STORAGE and LOCAL-STORAGE” on page 16Language Environment <strong>Programming</strong> <strong>Guide</strong> (What happens during termination:thread termination)RELATED TASKS“Calling nested <strong>COBOL</strong> programs” on page 458“Making recursive calls” on page 461Transferring control to another programYou can use several different methods to transfer control to another program: staticcalls, dynamic calls, calls to nested programs, and calls to dynamic link libraries(DLLs).In addition to making calls between <strong>Enterprise</strong> <strong>COBOL</strong> programs, you can alsomake static and dynamic calls between <strong>Enterprise</strong> <strong>COBOL</strong> and programs compiledwith older compilers in all environments including CICS.When you use <strong>OS</strong>/VS <strong>COBOL</strong> with <strong>Enterprise</strong> <strong>COBOL</strong>, there are differences insupport between non-CICS and CICS:In a non-CICS environmentYou can make static and dynamic calls between <strong>Enterprise</strong> <strong>COBOL</strong> andother <strong>COBOL</strong> programs.Exception: You cannot call VS <strong>COBOL</strong> II or <strong>OS</strong>/VS <strong>COBOL</strong> programs inthe UNIX environment.|In a CICS environmentYou cannot run <strong>OS</strong>/VS <strong>COBOL</strong> programs in the CICS environment.Chapter 24. Using subprograms 449


Calling nested programs lets you create applications using structuredprogramming techniques. You can use nested programs in place of PERFORMprocedures to prevent unintentional modification of data items. Call nestedprograms using either the CALL literal or CALL identifier statement.Calls to dynamic link libraries (DLLs) are an alternative to <strong>COBOL</strong> dynamic CALL,and are well suited to object-oriented <strong>COBOL</strong> applications, UNIX programs, andapplications that interoperate with C/C++.Under z/<strong>OS</strong>, linking two load modules together results logically in a singleprogram with a primary entry point and an alternate entry point, each with itsown name. Each name by which a subprogram is to be dynamically called must beknown to the system. You must specify each such name in linkage-editor or bindercontrol statements as either a NAME or an ALIAS of the load module that contains thesubprogram.RELATED CONCEPTS“AMODE switching” on page 453“Per<strong>for</strong>mance considerations of static and dynamic calls” on page 455“Nested programs” on page 458RELATED TASKS“Making static calls”“Making dynamic calls” on page 451“Making both static and dynamic calls” on page 455“Calling nested <strong>COBOL</strong> programs” on page 458Making static callsWhen you use the CALL literal statement in a program that is compiled using theNODYNAM and NODLL compiler options, a static call occurs. With these options, allCALL literal calls are handled as static calls.With static calls statement, the <strong>COBOL</strong> program and all called programs are part ofthe same load module. When control is transferred, the called program alreadyresides in storage, and a branch to it takes place. Subsequent executions of the CALLstatement make the called program available in its last-used state unless the calledprogram has the INITIAL attribute. In that case, the called program and eachprogram directly or indirectly contained within it are placed into their initial stateeach time the called program is called within a run unit.If you specify alternate entry points, a static CALL statement can use any alternateentry point to enter the called subprogram.“Examples: static and dynamic CALL statements” on page 456RELATED CONCEPTS“Per<strong>for</strong>mance considerations of static and dynamic calls” on page 455RELATED TASKS“Making dynamic calls” on page 451“Making both static and dynamic calls” on page 455“Calling to and from object-oriented programs” on page 461RELATED REFERENCES“DLL” on page 318450 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“DYNAM” on page 320CALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Making dynamic callsWhen you use a CALL literal statement in a program that is compiled using theDYNAM and the NODLL compiler options, or when you use the CALL identifierstatement in a program that is compiled using the NODLL compiler option, adynamic call occurs.In these <strong>for</strong>ms of the CALL statement, the called <strong>COBOL</strong> subprogram is notlink-edited with the main program. Instead, it is link-edited into a separate loadmodule, and is loaded at run time only when it is required (that is, when called).The program-name in the PROGRAM-ID paragraph or ENTRY statement must beidentical to the corresponding load module name or load module alias of the loadmodule that contains the program.Each subprogram that you call with a dynamic CALL statement can be part of adifferent load module that is a member of either the system link library or aprivate library that you supply. In either case it must be in an MVS load library; itcannot reside in the hierarchical file system. When a dynamic CALL statement callsa subprogram that is not resident in storage, the subprogram is loaded fromsecondary storage into the region or partition that contains the main program, anda branch to the subprogram is per<strong>for</strong>med.The first dynamic call to a subprogram within a run unit obtains a fresh copy ofthe subprogram. Subsequent calls to the same subprogram (by either the originalcaller or any other subprogram within the same run unit) result in a branch to thesame copy of the subprogram in its last-used state, provided the subprogram doesnot possess the INITIAL attribute. There<strong>for</strong>e, the reinitialization of either of thefollowing items is your responsibility:v GO TO statements that have been alteredv Data itemsIf you call the same <strong>COBOL</strong> program in different run units, a separate copy ofWORKING-STORAGE is allocated <strong>for</strong> each run unit.Restrictions: You cannot make dynamic calls to:v <strong>COBOL</strong> DLL programsv <strong>COBOL</strong> programs compiled with the PGMNAME(LONGMIXED) option, unless theprogram-name is less than or equal to eight characters in length and is alluppercasev <strong>COBOL</strong> programs compiled with the PGMNAME(LONGUPPER) option, unless theprogram-name is less than or equal to eight characters in lengthv More than one entry point in the same <strong>COBOL</strong> program (unless an interveningCANCEL statement was executed)“Examples: static and dynamic CALL statements” on page 456RELATED CONCEPTS“When to use a dynamic call with subprograms” on page 452“Per<strong>for</strong>mance considerations of static and dynamic calls” on page 455Chapter 24. Using subprograms 451


RELATED TASKS“Canceling a subprogram”“Making static calls” on page 450“Making both static and dynamic calls” on page 455RELATED REFERENCES“DLL” on page 318“DYNAM” on page 320ENTRY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Language Environment <strong>Programming</strong> ReferenceCanceling a subprogramWhen you issue a CANCEL statement <strong>for</strong> a subprogram, the storage that is occupiedby the subprogram is freed. A subsequent call to the subprogram functions asthough it were the first call. You can cancel a subprogram from a program otherthan the original caller.If the called subprogram has more than one entry point, ensure that an interveningCANCEL statement is issued be<strong>for</strong>e you specify different entry points in a dynamicCALL statement to that subprogram.After a CANCEL statement is processed <strong>for</strong> a dynamically called contained program,the program will be in its first-used state. However, the program is not loadedwith the initial call, and storage is not freed after the program is canceled.“Examples: static and dynamic CALL statements” on page 456RELATED CONCEPTS“Per<strong>for</strong>mance considerations of static and dynamic calls” on page 455When to use a dynamic call with subprogramsYour decision to use dynamic calls with subprograms depends on factors such aslocation of the load module, frequency of calls to the subprograms, size of thesubprograms, ease of maintenance, the need to call subprograms in their unusedstate, the need <strong>for</strong> AMODE switching, and when the program-names are known.The load module that you want to dynamically call must be in an MVS loadlibrary rather than in the hierarchical file system.If subprograms are called in only a few conditions, you can use dynamic calls tobring in the subprograms only when needed.If the subprograms are very large or there are many of them, using static callsmight require too much main storage. Less total storage might be required to calland cancel one, then call and cancel another, than to statically call both.If you are concerned about ease of maintenance, dynamic calls can help.Applications do not have to be link-edited again when dynamically calledsubprograms are changed.When you cannot use the INITIAL attribute to ensure that a subprogram is placedin its unused state each time that it is called, you can set the unused state by usinga combination of dynamic CALL and CANCEL statements. When you cancel a452 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


subprogram that was first called by a <strong>COBOL</strong> program, the next call causes thesubprogram to be reinitialized to its unused state.Using the CANCEL statement to explicitly cancel a subprogram that was dynamicallyloaded and branched to by a non-<strong>COBOL</strong> program does not result in any actionbeing taken to release the subprogram’s storage or to delete the subprogram.Suppose you have an <strong>OS</strong>/VS <strong>COBOL</strong> or other AMODE 24 program in the same rununit with <strong>Enterprise</strong> <strong>COBOL</strong> programs that you want to run in 31-bit addressingmode. <strong>COBOL</strong> dynamic call processing includes AMODE switching <strong>for</strong> AMODE 24programs that call AMODE 31 programs, and vice versa. To have this implicit AMODEswitching done, you must use the Language Environment runtime optionALL31(OFF). AMODE switching is not per<strong>for</strong>med when ALL31(ON) is set.When AMODE switching is per<strong>for</strong>med, control is passed from the caller to aLanguage Environment library routine. After the switching is per<strong>for</strong>med, controlpasses to the called program; the save area <strong>for</strong> the library routine will bepositioned between the save area <strong>for</strong> the caller program and the save area <strong>for</strong> thecalled program.If you do not know the program-name to be called until run time, use the <strong>for</strong>matCALL identifier, where identifier is a data item that will contain the name of thecalled program at run time. For example, you could use CALL identifier when theprogram to be called varies depending on conditional processing in your program.CALL identifier is always dynamic, even if you use the NODYNAM compiler option.“Examples: static and dynamic CALL statements” on page 456RELATED CONCEPTS“AMODE switching”“Per<strong>for</strong>mance considerations of static and dynamic calls” on page 455RELATED TASKS“Making dynamic calls” on page 451RELATED REFERENCES“DYNAM” on page 320CALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Language Environment <strong>Programming</strong> ReferenceAMODE switchingWhen you have an application that has <strong>COBOL</strong> subprograms, some of the <strong>COBOL</strong>subprograms can be AMODE 31 and some can be AMODE 24.If your application consists of only <strong>COBOL</strong> programs, and you are using onlystatic and dynamic calls, each <strong>COBOL</strong> subprogram will always be entered in theproper AMODE. For example, if you are using a dynamic call from an AMODE 31<strong>COBOL</strong> program to an AMODE 24 <strong>COBOL</strong> program, the AMODE is automaticallyswitched.However, if you are using procedure pointers, function pointers, or otherlanguages that call <strong>COBOL</strong> subprograms, you must ensure that when a <strong>COBOL</strong>program is called more than once in an enclave, it is entered in the same AMODEeach time that it is called. The AMODE is not automatically switched in this case.Chapter 24. Using subprograms 453


The following scenario shows that AMODE problems can arise when procedurepointers are used to call <strong>COBOL</strong> subprograms. This scenario is not supportedbecause the <strong>COBOL</strong> program <strong>COBOL</strong>Y is not entered in the same AMODE each timethat it is called.1. <strong>COBOL</strong>X is AMODE 31. It uses the SET statement to set a procedure pointer to<strong>COBOL</strong>Z. <strong>COBOL</strong>Z is a reentrant load module and is AMODE 31 and RMODE 24.<strong>COBOL</strong>X calls <strong>COBOL</strong>Z using the procedure pointer. <strong>COBOL</strong>Z is entered inAMODE 31.2. <strong>COBOL</strong>Z returns to <strong>COBOL</strong>X.3. <strong>COBOL</strong>X dynamically calls <strong>COBOL</strong>Y, passing the procedure pointer <strong>for</strong><strong>COBOL</strong>Z. <strong>COBOL</strong>Y is a reentrant load module, and is AMODE 24 and RMODE 24.<strong>COBOL</strong>Y is entered in AMODE 24.4. <strong>COBOL</strong>Y calls <strong>COBOL</strong>Z using the procedure pointer. This call causes <strong>COBOL</strong>Zto be entered in AMODE 24, which is not the same AMODE in which <strong>COBOL</strong>Z wasentered when it was called the first time.The following scenario uses a mix of <strong>COBOL</strong> and assembler language. Thisscenario is not supported because the <strong>COBOL</strong> program <strong>COBOL</strong>B is not entered inthe same AMODE each time that it is called.454 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


1. <strong>COBOL</strong>A is AMODE 31. <strong>COBOL</strong>A dynamically calls <strong>COBOL</strong>B. <strong>COBOL</strong>B is areentrant load module and is AMODE 31 and RMODE 24. <strong>COBOL</strong>B is entered inAMODE 31.2. <strong>COBOL</strong>B returns to <strong>COBOL</strong>A.3. <strong>COBOL</strong>A dynamically calls ASSEM10, which is in assembler language.ASSEM10 is a reentrant load module, and is AMODE 24 and RMODE 24. ASSEM10is entered in AMODE 24.4. ASSEM10 loads <strong>COBOL</strong>B. ASSEM10 does a BALR instruction to <strong>COBOL</strong>B.<strong>COBOL</strong>B is entered in AMODE 24, which is not the same AMODE in which<strong>COBOL</strong>B was entered when it was called the first time.RELATED CONCEPTS“Storage and its addressability” on page 42“When to use a dynamic call with subprograms” on page 452RELATED TASKS“Making dynamic calls” on page 451RELATED REFERENCESLanguage Environment <strong>Programming</strong> Reference (ALL31)Per<strong>for</strong>mance considerations of static and dynamic callsBecause a statically called program is link-edited into the same load module as thecalling program, a static call is faster than a dynamic call. A static call is thepreferred method if your application does not require the services of the dynamiccall.Statically called programs cannot be deleted using CANCEL, so static calls might takemore main storage. If storage is a concern, think about using dynamic calls.Storage usage of calls depends on whether:vvThe subprogram is called only a few times. Regardless of whether it is called, astatically called program is loaded into storage; a dynamically called program isloaded only when it is called.You subsequently delete the dynamically called subprogram with a CANCELstatement.You cannot delete a statically called program, but you can delete a dynamicallycalled program. Using a dynamic call and then a CANCEL statement to delete thedynamically called program after it is no longer needed in the application (andnot after each call to it) might require less storage than using a static call.RELATED CONCEPTS“When to use a dynamic call with subprograms” on page 452RELATED TASKS“Making static calls” on page 450“Making dynamic calls” on page 451Making both static and dynamic callsYou can use both static and dynamic CALL statements in the same program if youcompile the program with the NODYNAM compiler option.Chapter 24. Using subprograms 455


In this case, with the CALL literal statement, the called subprogram will belink-edited with the main program into one load module. The CALL identifierstatement results in the dynamic invocation of a separate load module.When a dynamic CALL statement and a static CALL statement to the samesubprogram are issued within one program, a second copy of the subprogram isloaded into storage. Because this arrangement does not guarantee that thesubprogram will be left in its last-used state, results can be unpredictable.RELATED REFERENCES“DYNAM” on page 320Examples: static and dynamic CALL statementsThis example shows how you can code static and dynamic calls.The example has three parts:v Code that uses a static call to call a subprogramv Code that uses a dynamic call to call the same subprogramv The subprogram that is called by the two types of callsThe following example shows how you would code static calls:PROCESS NODYNAM NODLLIDENTIFICATION DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.01 RECORD-2 PIC X. (6)01 RECORD-1. (2)05 PAY PICTURE S9(5)V99.05 HOURLY-RATE PICTURE S9V99.05 HOURS PICTURE S99V9....PROCEDURE DIVISION.CALL "SUBPROG" USING RECORD-1. (1)CALL "PAYMASTR" USING RECORD-1 RECORD-2. (5)STOP RUN.The following example shows how you would code dynamic calls:DATA DIVISION.WORKING-STORAGE SECTION.77 PGM-NAME PICTURE X(8).01 RECORD-2 PIC x. (6)01 RECORD-1. (2)05 PAY PICTURE S9(5)V99.05 HOURLY-RATE PICTURE S9V99.05 HOURS PICTURE S99V9....PROCEDURE DIVISION....MOVE "SUBPROG" TO PGM-NAME.CALL PGM-NAME USING RECORD-1. (1)CANCEL PGM-NAME.MOVE "PAYMASTR" TO PGM-NAME. (4)CALL PGM-NAME USING RECORD-1 RECORD-2. (5)STOP RUN.The following example shows a called subprogram that is called by each of thetwo preceding calling programs:456 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


IDENTIFICATION DIVISION.PROGRAM-ID. SUBPROG.DATA DIVISION.LINKAGE SECTION.01 PAYREC. (2)10 PAY PICTURE S9(5)V99.10 HOURLY-RATE PICTURE S9V99.10 HOURS PICTURE S99V9.77 PAY-CODE PICTURE 9. (6)PROCEDURE DIVISION USING PAYREC. (1)...EXIT PROGRAM. (3)ENTRY "PAYMASTR" USING PAYREC PAY-CODE. (5)...GOBACK. (7)(1) Processing begins in the calling program. When the first CALL statement isexecuted, control is transferred to the first statement of the PROCEDUREDIVISION in SUBPROG, which is the called program.In each of the CALL statements, the operand of the first USING option isidentified as RECORD-1.(2) When SUBPROG receives control, the values within RECORD-1 are madeavailable to SUBPROG; however, in SUBPROG they are referred to as PAYREC.The PICTURE character-strings within PAYREC and PAY-CODE contain the samenumber of characters as RECORD-1 and RECORD-2, although the descriptionsare not identical.(3) When processing within SUBPROG reaches the EXIT PROGRAM statement,control is returned to the calling program. Processing continues in thatprogram until the second CALL statement is issued.(4) In the example of a dynamically called program, because the second CALLstatement refers to another entry point within SUBPROG, aCANCEL statementis issued be<strong>for</strong>e the second CALL statement.(5) With the second CALL statement in the calling program, control is againtransferred to SUBPROG, but this time processing begins at the statementfollowing the ENTRY statement in SUBPROG.(6) The values within RECORD-1 are again made available to PAYREC. Inaddition, the value in RECORD-2 is now made available to SUBPROG throughthe corresponding USING operand, PAY-CODE.When control is transferred the second time from the statically linkedprogram, SUBPROG is made available in its last-used state (that is, if anyvalues in SUBPROG storage were changed during the first execution, thosechanged values are still in effect). When control is transferred from thedynamically linked program, however, SUBPROG is made available in itsinitial state, because of the CANCEL statement that has been executed.(7) When processing reaches the GOBACK statement, control is returned to thecalling program at the statement immediately after the second CALLstatement.In any given execution of the called program and either of the two callingprograms, if the values within RECORD-1 are changed between the time of the firstCALL and the second, the values passed at the time of the second CALL statementwill be the changed, not the original, values. If you want to use the original values,you must save them.Chapter 24. Using subprograms 457


Calling nested <strong>COBOL</strong> programsBy calling nested programs, you can create applications that use structuredprogramming techniques. You can also call nested programs instead of PERFORMprocedures to prevent unintentional modification of data items. Use either CALLliteral or CALL identifier statements to make calls to nested programs.You can call a contained program only from its directly containing program unlessyou identify the contained program as COMMON in its PROGRAM-ID paragraph. In thatcase, you can call the common program from any program that is contained (directlyor indirectly) in the same program as the common program. Only containedprograms can be identified as COMMON. Recursive calls are not allowed.Follow these guidelines when using nested program structures:v Code an IDENTIFICATION DIVISION in each program. All other divisions areoptional.v Optionally make the name of each contained program unique. Although thenames of contained programs are not required to be unique (as described in therelated reference about scope of names), making the names unique could helpmake your application more maintainable. You can use any valid user-definedword or an alphanumeric literal as the name of a contained program.v In the outermost program, code any CONFIGURATION SECTION entries that mightbe required. Contained programs cannot have a CONFIGURATION SECTION.v Include each contained program in the containing program immediately be<strong>for</strong>ethe END PROGRAM marker of the containing program.v Use an END PROGRAM marker to terminate contained and containing programs.You cannot use the THREAD option when compiling programs that contain nestedprograms.RELATED CONCEPTS“Nested programs”RELATED REFERENCES“Scope of names” on page 460Nested programsA <strong>COBOL</strong> program can nest, or contain, other <strong>COBOL</strong> programs. The nestedprograms can themselves contain other programs. A nested program can bedirectly or indirectly contained in a program.There are four main advantages to nesting called programs:v Nested programs provide a method <strong>for</strong> creating modular functions andmaintaining structured programming techniques. They can be used analogouslyto per<strong>for</strong>m procedures (using the PERFORM statement), but with more structuredcontrol flow and with the ability to protect local data items.v Nested programs let you debug a program be<strong>for</strong>e including it in an application.v Nested programs enable you to compile an application with a single invocationof the compiler.v Calls to nested programs have the best per<strong>for</strong>mance of all the <strong>for</strong>ms of <strong>COBOL</strong>CALL statements.458 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The following example describes a nested structure that has directly and indirectlycontained programs:“Example: structure of nested programs”RELATED TASKS“Calling nested <strong>COBOL</strong> programs” on page 458RELATED REFERENCES“Scope of names” on page 460Example: structure of nested programsThe following example shows a nested structure with some contained programsthat are identified as COMMON.Chapter 24. Using subprograms 459


The following table describes the calling hierarchy <strong>for</strong> the structure that is shownin the example above. Programs A12, A2, and A3 are identified as COMMON, and thecalls associated with them differ.This programCan call these programsAnd can be called by theseprogramsA A1, A2, A3 NoneA1 A11, A12, A2, A3 AA11 A111, A12, A2, A3 A1A111 A12, A2, A3 A11A12 A2, A3 A1, A11, A111A2 A3 A, A1, A11, A111, A12, A3A3 A2 A, A1, A11, A111, A12, A2In this example, note that:v A2 cannot call A1 because A1 is not common and is not contained in A2.v A1 can call A2 because A2 is common.Scope of namesNames in nested structures are divided into two classes: local and global. The classdetermines whether a name is known beyond the scope of the program thatdeclares it. A specific search sequence locates the declaration of a name after it isreferenced in a program.Local names:Names (except the program-name) are local unless declared to be otherwise. Localnames are visible or accessible only within the program in which they are declared.They are not visible or accessible to contained and containing programs.Global names:A name that is global (indicated by using the GLOBAL clause) is visible andaccessible to the program in which it is declared and to all the programs that aredirectly and indirectly contained in that program. There<strong>for</strong>e, the containedprograms can share common data and files from the containing program simply byreferencing the names of the items.460 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Making recursive callsAny item that is subordinate to a global item (including condition-names andindexes) is automatically global.You can declare the same name with the GLOBAL clause more than one time,provided that each declaration occurs in a different program. Be aware that youcan mask, or hide, a name in a nested structure by having the same name occur indifferent programs in the same containing structure. However, such masking couldcause problems during a search <strong>for</strong> a name declaration.Searches <strong>for</strong> name declarations:When a name is referenced in a program, a search is made to locate the declaration<strong>for</strong> that name. The search begins in the program that contains the reference andcontinues outward to the containing programs until a match is found. The searchfollows this process:1. Declarations in the program are searched.2. If no match is found, only global declarations are searched in successive outercontaining programs.3. The search ends when the first matching name is found. If no match is found,an error exists.The search is <strong>for</strong> a global name, not <strong>for</strong> a particular type of object associated withthe name such as a data item or file connector. The search stops when any match isfound, regardless of the type of object. If the object declared is of a different typethan that expected, an error condition exists.A called program can directly or indirectly execute its caller. For example, programX calls program Y, program Y calls program Z, and program Z then calls programX. This type of call is recursive.To make a recursive call, you must code the RECURSIVE clause in the PROGRAM-IDparagraph of the recursively called program. If you try to recursively call a<strong>COBOL</strong> program that does not have the RECURSIVE clause in the PROGRAM-IDparagraph, a condition is signaled. If the condition remains unhandled, the rununit will end.RELATED TASKS“Identifying a program as recursive” on page 6RELATED REFERENCESPROGRAM-ID paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Calling to and from object-oriented programsWhen you create applications that contain object-oriented (OO) programs, the OO<strong>COBOL</strong> programs are DLL programs and can be in one or more dynamic linklibraries (DLLs). Each class definition must be in a separate DLL, however.Calls to or from <strong>COBOL</strong> DLL programs must either use DLL linkage or be staticcalls. <strong>COBOL</strong> dynamic calls to or from <strong>COBOL</strong> DLL programs are not supported.Chapter 24. Using subprograms 461


If you must call a <strong>COBOL</strong> DLL program from a <strong>COBOL</strong> non-DLL program, othermeans to ensure that the DLL linkage mechanism is followed are available.Using procedure and function pointersYou can set procedure-pointer and function-pointer data items only by using<strong>for</strong>mat 6 of the SET statement.Procedure pointers are data items defined with the USAGE IS PROCEDURE-POINTERclause. Function pointers are data items defined with the USAGE ISFUNCTION-POINTER clause. In this in<strong>for</strong>mation, “pointer” refers to either aprocedure-pointer data item or a function-pointer data item. You can set either ofthese data items to contain entry addresses of, or pointers to, these entry points:vvvAnother <strong>COBOL</strong> program that is not nested. For example, to have a user-writtenerror-handling routine take control when an exception condition occurs, youmust first pass the entry address of the routine to CEEHDLR, acondition-management Language Environment callable service, so that theroutine is registered.A program written in another language. For example, to receive the entryaddress of a C function, call the function with the CALL RETURNING statement. Itwill return a pointer that you can either use as a function pointer or convert to aprocedure pointer by using a <strong>for</strong>m of the SET statement.An alternate entry point in another <strong>COBOL</strong> program (as defined in an ENTRYstatement).The SET statement sets the pointer to refer either to an entry point in the same loadmodule as your program, to a separate load module, or to an entry point that isexported from a DLL, depending on the DYNAM|NODYNAM and DLL|NODLL compileroptions. There<strong>for</strong>e, consider these factors when using these pointer data items:vvvvIf you compile a program with the NODYNAM and NODLL options and set a pointeritem to a literal value (to an actual name of an entry point), the value must referto an entry point in the same load module. Otherwise the reference cannot beresolved.If you compile a program with the NODLL option and either set a pointer item toan identifier that will contain the name of the entry point at run time or set thepointer item to a literal and compile with the DYNAM option, then the pointeritem, whether a literal or variable, must point to an entry point in a separateload module. The entry point can be either the primary entry point or analternate entry point named in an ALIAS linkage-editor or binder statement.If you compile with the NODYNAM and DLL options and set a pointer item to aliteral value (the actual name of an entry point), the value must refer to an entrypoint in the same load module or to an entry-point name that is exported from aDLL module. In the latter case you must include the DLL side file <strong>for</strong> the targetDLL module in the link edit of your program load module.If you compile with the NODYNAM and DLL options and set a pointer item to anidentifier (a data item that contains the entry point name at run time), theidentifier value must refer to the entry-point name that is exported from a DLLmodule. In this case the DLL module name must match the name of theexported entry point.If you set a pointer item to an entry address in a dynamically called load module,and your program subsequently cancels that dynamically called module, then thatpointer item becomes undefined. Reference to it thereafter is not reliable.462 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Deciding which type of pointer to use”“Calling alternate entry points”“Using procedure or function pointers with DLLs” on page 488RELATED REFERENCES“DLL” on page 318“DYNAM” on page 320CANCEL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Format 6: SET <strong>for</strong> procedure-pointer and function-pointer data items(<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)ENTRY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Deciding which type of pointer to useUse procedure pointers to call other <strong>COBOL</strong> programs and to call LanguageEnvironment callable services. Use function pointers to communicate with C/C++programs or with services provided by the Java Native Interface.Procedure pointers are more efficient than function pointers <strong>for</strong> <strong>COBOL</strong>-to-<strong>COBOL</strong>calls, and are required <strong>for</strong> calls to Language Environment condition-handlingservices.Many callable services written in C return function pointers. You can call such a Cfunction pointer from your <strong>COBOL</strong> program by using <strong>COBOL</strong> function pointers asshown below.IDENTIFICATION DIVISION.PROGRAM-ID. DEMO.ENVIRONMENT DIVISION.DATA DIVISION.*WORKING-STORAGE SECTION.01 FP USAGE FUNCTION-POINTER.*PROCEDURE DIVISION.CALL "c-function" RETURNING FP.CALL FP.RELATED TASKS“Using procedure or function pointers with DLLs” on page 488“Accessing JNI services” on page 607Calling alternate entry pointsStatic calls to alternate entry points work without restriction.Dynamic calls to alternate entry points require the following elements:v Either explicitly specified NAME or ALIAS linkage-editor or binder controlstatements, or use of the NAME compiler option which generates themautomatically.v An intervening CANCEL <strong>for</strong> any dynamic call to the same module at a differententry point. CANCEL causes the program to be invoked in initial state when it iscalled at a new entry point.Chapter 24. Using subprograms 463


You can specify another entry point at which a program will begin running byusing the ENTRY label in the called program. However, this method is notrecommended in a structured program.“Examples: static and dynamic CALL statements” on page 456Making programs reentrantRELATED REFERENCES“NAME” on page 331CANCEL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)ENTRY statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)MVS Program Management: User’s <strong>Guide</strong> and ReferenceIf more than one user will run an application program at the same time (<strong>for</strong>example, users in different address spaces accessing a program that resides in thelink pack area), you must make the program reentrant by compiling with the RENToption.You do not need to worry about multiple copies of variables. The compiler createsthe necessary reentrancy controls in the object module.The following <strong>Enterprise</strong> <strong>COBOL</strong> programs must be reentrant:v Programs to be used with CICSv Programs to be preloaded with IMSv Programs to be used as DB2 stored proceduresv Programs to be run in the z/<strong>OS</strong> UNIX environmentv Programs that are enabled <strong>for</strong> DLL supportv Programs that use object-oriented syntaxFor reentrant programs, use the DATA compiler option and the HEAP and ALL31runtime options to control whether dynamic data areas, such as WORKING-STORAGE,are obtained from storage below or above the 16-MB line.RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Compiling programs to create DLLs” on page 482Chapter 16, “Compiling, linking, and running OO applications,” on page 291RELATED REFERENCES“RENT” on page 341“DATA” on page 314Language Environment <strong>Programming</strong> Reference (ALL31, HEAP)464 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 25. Sharing dataWhen a run unit consists of several separately compiled programs that call eachother, the programs must be able to communicate with each other. They alsousually need access to common data.This in<strong>for</strong>mation describes how you can write programs that share data with otherprograms. In this in<strong>for</strong>mation, a subprogram is any program that is called byanother program.Passing dataRELATED TASKS“Passing data”“Coding the LINKAGE SECTION” on page 469“Coding the PROCEDURE DIVISION <strong>for</strong> passing arguments” on page 469“Passing return-code in<strong>for</strong>mation” on page 474“Specifying CALL . . . RETURNING” on page 475“Sharing data by using the EXTERNAL clause” on page 475“Sharing files between programs (external files)” on page 475“Sharing data with Java” on page 612You can choose among three ways of passing data between programs: BYREFERENCE, BY CONTENT, orBY VALUE.BY REFERENCEThe subprogram refers to and processes the data items in the storage of thecalling program rather than working on a copy of the data. BY REFERENCE isthe assumed passing mechanism <strong>for</strong> a parameter if none of the three waysis specified or implied <strong>for</strong> the parameter.BY CONTENTThe calling program passes only the contents of the literal or identifier. Thecalled program cannot change the value of the literal or identifier in thecalling program, even if it modifies the data item in which it received theliteral or identifier.BY VALUEThe calling program or method passes the value of the literal or identifier,not a reference to the sending data item. The called program or invokedmethod can change the parameter. However, because the subprogram ormethod has access only to a temporary copy of the sending data item, anychange does not affect the argument in the calling program.The following figure shows the differences in values passed BY REFERENCE, BYCONTENT, and BY VALUE:© Copyright IBM Corp. 1991, 2009 465


Determine which of these data-passing methods to use based on what you wantyour program to do with the data.Table 65. Methods <strong>for</strong> passing data in the CALL statementCode Purpose CommentsCALL...BYREFERENCEidentifierCALL...BYREFERENCEADDRESS OF identifierCALL...BYREFERENCEfile-nameCALL...BYCONTENT ADDRESSOF identifierCALL...BYCONTENT identifierCALL...BYCONTENT literalCALL...BYCONTENT LENGTHOF identifierA combination of BY REFERENCEand BY CONTENT such as:CALL 'ERRPROC'USING BY REFERENCE ABY CONTENT LENGTH OF A.CALL...BYVALUE identifierTo have the definition of the argumentof the CALL statement in the callingprogram and the definition of theparameter in the called program sharethe same memoryTo pass the address of identifier to acalled program, where identifier is anitem in the LINKAGE SECTIONTo pass a Data Control Block (DCB) toassembler programsTo pass a copy of the address ofidentifier to a called programTo pass a copy of the identifier to thesubprogramTo pass a copy of a literal value to acalled programTo pass a copy of the length of a dataitemTo pass both a data item and a copy ofits length to a subprogramTo pass data to a program, such as aC/C++ program, that uses BY VALUEparameter linkage conventionsAny changes made by the subprogramto the parameter affect the argument inthe calling program.Any changes made by the subprogramto the address affect the address in thecalling program.The file-name must reference a QSAMsequential file. 1Any changes to the copy of the addresswill not affect the address of identifier,but changes to identifier using the copyof the address will cause changes toidentifier.Changes to the parameter by thesubprogram will not affect the caller’sidentifier.The calling program passes the lengthof the identifier from its LENGTH specialregister.A copy of the identifier is passeddirectly in the parameter list.466 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 65. Methods <strong>for</strong> passing data in the CALL statement (continued)Code Purpose CommentsCALL...BYVALUE literal To pass data to a program, such as aC/C++ program, that uses BY VALUEparameter linkage conventionsA copy of the literal is passed directlyin the parameter list.CALL...BYVALUE ADDRESS OFidentifierCALL...RETURNINGTo pass the address of identifier to acalled program. This is therecommended way to pass data to aC/C++ program that expects a pointerto the data.To call a C/C++ function with afunction return valueAny changes to the copy of the addresswill not affect the address of identifier,but changes to identifier using the copyof the address will cause changes toidentifier.1. File-names as CALL operands are allowed as an IBM extension to <strong>COBOL</strong>. Any use of the extension generallydepends on the specific internal implementation of the compiler. Control block field settings might change infuture releases. Any changes made to the control block are the user’s responsibility and are not supported byIBM.RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Describing arguments in the calling program”“Describing parameters in the called program” on page 468“Testing <strong>for</strong> OMITTED arguments” on page 468“Specifying CALL . . . RETURNING” on page 475“Sharing data by using the EXTERNAL clause” on page 475“Sharing files between programs (external files)” on page 475“Sharing data with Java” on page 612RELATED REFERENCESCALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The USING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)INVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Describing arguments in the calling programIn the calling program, describe arguments in the DATA DIVISION in the samemanner as other data items in the DATA DIVISION.Storage <strong>for</strong> arguments is allocated only in the highest outermost program. Forexample, program A calls program B, which calls program C. Data items areallocated in program A. They are described in the LINKAGE SECTION of programs Band C, making the one set of data available to all three programs.If you reference data in a file, the file must be open when the data is referenced.Code the USING phrase of the CALL statement to pass the arguments. If you pass adata item BY VALUE, it must be an elementary item.Do not pass parameters allocated in storage above the 16-MB line to AMODE 24subprograms. Use the DATA(24) option if the RENT option is in effect, or theRMODE(24) option if the NORENT option is in effect.Chapter 25. Sharing data 467


RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Coding the LINKAGE SECTION” on page 469“Coding the PROCEDURE DIVISION <strong>for</strong> passing arguments” on page 469RELATED REFERENCESThe USING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Describing parameters in the called programYou must know what data is being passed from the calling program and describeit in the LINKAGE SECTION of each program that is called directly or indirectly bythe calling program.Code the USING phrase after the PROCEDURE DIVISION header to name theparameters that receive the data that is passed from the calling program.When arguments are passed to the subprogram BY REFERENCE, it is invalid <strong>for</strong> thesubprogram to specify any relationship between its parameters and any fieldsother than those that are passed and defined in the main program. Thesubprogram must not:vvvvDefine a parameter to be larger in total number of bytes than the correspondingargument.Use subscript references to refer to elements beyond the limits of tables that arepassed as arguments by the calling program.Use reference modification to access data beyond the length of definedparameters.Manipulate the address of a parameter in order to access other data items thatare defined in the calling program.If any of the rules above are violated, unexpected results might occur.RELATED TASKS“Coding the LINKAGE SECTION” on page 469RELATED REFERENCESThe USING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Testing <strong>for</strong> OMITTED argumentsYou can specify that one or more BY REFERENCE arguments are not to be passed to acalled program by coding the OMITTED keyword in place of those arguments in theCALL statement.For example, to omit the second argument when calling program sub1, code thisstatement:Call 'sub1' Using PARM1, OMITTED, PARM3The arguments in the USING phrase of the CALL statement must match theparameters of the called program in number and position.468 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In a called program, you can test whether an argument was passed as OMITTED bycomparing the address of the corresponding parameter to NULL. For example:Program-ID. sub1....Procedure Division Using RPARM1, RPARM2, RPARM3.If Address Of RPARM2 = Null ThenDisplay 'No 2nd argument was passed this time'ElsePer<strong>for</strong>m Process-Parm-2End-IfRELATED REFERENCESCALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The USING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Coding the LINKAGE SECTIONCode the same number of data-names in the identifier list of the called program asthe number of arguments in the calling program. Synchronize by position, becausethe compiler passes the first argument from the calling program to the firstidentifier of the called program, and so on.You will introduce errors if the number of data-names in the identifier list of acalled program is greater than the number of arguments passed from the callingprogram. The compiler does not try to match arguments and parameters.The following figure shows a data item being passed from one program to another(implicitly BY REFERENCE):In the calling program, the code <strong>for</strong> parts (PARTCODE) and the part number (PARTNO)are distinct data items. In the called program, by contrast, the code <strong>for</strong> parts andthe part number are combined into one data item (PART-ID). In the called program,a reference to PART-ID is the only valid reference to these items.Coding the PROCEDURE DIVISION <strong>for</strong> passing argumentsIf you pass an argument BY VALUE, code the USING BY VALUE clause in thePROCEDURE DIVISION header of the subprogram. If you pass an argument BYREFERENCE or BY CONTENT, you do not need to indicate in the header how theargument was passed.Chapter 25. Sharing data 469


PROCEDURE DIVISION USING BY VALUE. . .PROCEDURE DIVISION USING. . .PROCEDURE DIVISION USING BY REFERENCE. . .The first header above indicates that the data items are passed BY VALUE; thesecond or third headers indicate that the items are passed BY REFERENCE or BYCONTENT.RELATED REFERENCESThe procedure division header (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The USING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Grouping data to be passedConsider grouping all the data items that you need to pass between programs andputting them under one level-01 item. If you do so, you can pass a single level-01record.Note that if you pass a data item BY VALUE, it must be an elementary item.To lessen the possibility of mismatched records, put the level-01 record into a copylibrary and copy it into both programs. That is, copy it in the WORKING-STORAGESECTION of the calling program and in the LINKAGE SECTION of the called program.RELATED TASKS“Coding the LINKAGE SECTION” on page 469RELATED REFERENCESCALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Handling null-terminated strings<strong>COBOL</strong> supports null-terminated strings when you use string-handling verbstogether with null-terminated literals and the hexadecimal literal X'00'.You can manipulate null-terminated strings (passed from aCprogram, <strong>for</strong>example) by using string-handling mechanisms such as those in the followingcode:01 L pic X(20) value z'ab'.01 M pic X(20) value z'cd'.01 N pic X(20).01 N-Length pic 99 value zero.01 Y pic X(13) value 'Hello, World!'.To determine the length of a null-terminated string, and display the value of thestring and its length, code:Inspect N tallying N-length <strong>for</strong> characters be<strong>for</strong>e initial X'00'Display 'N: ' N(1:N-length) ' Length: ' N-lengthTo move a null-terminated string to an alphanumeric string, but delete the null,code:Unstring N delimited by X'00' into XTo create a null-terminated string, code:470 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


String Y delimited by sizeX'00' delimited by sizeinto N.To concatenate two null-terminated strings, code:String L delimited by x'00'M delimited by x'00'X'00' delimited by sizeinto N.RELATED TASKS“Manipulating null-terminated strings” on page 106RELATED REFERENCESNull-terminated alphanumeric literals (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using pointers to process a chained listWhen you need to pass and receive addresses of record areas, you can use pointerdata items, which are either data items that are defined with the USAGE IS POINTERclause or are ADDRESS OF special registers.A typical application <strong>for</strong> using pointer data items is in processing a chained list, aseries of records in which each record points to the next.When you pass addresses between programs in a chained list, you can use NULL toassign the value of an address that is not valid (nonnumeric 0) to a pointer item ineither of two ways:v Use a VALUE IS NULL clause in its data definition.v Use NULL as the sending field in a SET statement.In the case of a chained list in which the pointer data item in the last recordcontains a null value, you can use this code to check <strong>for</strong> the end of the list:IF PTR-NEXT-REC = NULL...(logic <strong>for</strong> end of chain)If the program has not reached the end of the list, the program can process therecord and move on to the next record.The data passed from a calling program might contain header in<strong>for</strong>mation that youwant to ignore. Because pointer data items are not numeric, you cannot directlyper<strong>for</strong>m arithmetic on them. However, to bypass header in<strong>for</strong>mation, you can usethe SET statement to increment the passed address.“Example: using pointers to process a chained list” on page 472RELATED TASKS“Coding the LINKAGE SECTION” on page 469“Coding the PROCEDURE DIVISION <strong>for</strong> passing arguments” on page 469RELATED REFERENCESSET statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 25. Sharing data 471


Example: using pointers to process a chained listThe following example shows how you might process a linked list, that is, achained list of data items.For this example, picture a chained list of data that consists of individual salaryrecords. The following figure shows one way to visualize how the records arelinked in storage. The first item in each record except the last points to the nextrecord. The first item in the last record contains a null value (instead of a validaddress) to indicate that it is the last record.The high-level pseudocode <strong>for</strong> an application that processes these records mightbe:Obtain address of first record in chained list from routineCheck <strong>for</strong> end of the listDo until end of the listProcess recordTraverse to the next recordEndThe following code contains an outline of the calling program, LISTS, used in thisexample of processing a chained list.IDENTIFICATION DIVISION.PROGRAM-ID. LISTS.ENVIRONMENT DIVISION.DATA DIVISION.******WORKING-STORAGE SECTION.77 PTR-FIRST POINTER VALUE IS NULL. (1)77 DEPT-TOTAL PIC 9(4) VALUE IS 0.******LINKAGE SECTION.01 SALARY-REC.02 PTR-NEXT-REC POINTER. (2)02 NAME PIC X(20).02 DEPT PIC 9(4).02 SALARY PIC 9(6).01 DEPT-X PIC 9(4).******PROCEDURE DIVISION USING DEPT-X.******* FOR EVERYONE IN THE DEPARTMENT RECEIVED AS DEPT-X,* GO THROUGH ALL THE RECORDS IN THE CHAINED LIST BASED ON THE* ADDRESS OBTAINED FROM THE PROGRAM CHAIN-ANCH* AND CUMULATE THE SALARIES.* IN EACH RECORD, PTR-NEXT-REC IS A POINTER TO THE NEXT RECORD* IN THE LIST; IN THE LAST RECORD, PTR-NEXT-REC IS NULL.* DISPLAY THE TOTAL.******CALL "CHAIN-ANCH" USING PTR-FIRST (3)SET ADDRESS OF SALARY-REC TO PTR-FIRST (4)******PERFORM WITH TEST BEFORE UNTIL ADDRESS OF SALARY-REC = NULL (5)472 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


IF DEPT = DEPT-XTHEN ADD SALARY TO DEPT-TOTALELSE CONTINUEEND-IFSET ADDRESS OF SALARY-REC TO PTR-NEXT-REC (6)END-PERFORM******DISPLAY DEPT-TOTALGOBACK.(1) PTR-FIRST is defined as a pointer data item with an initial value of NULL.On a successful return from the call to CHAIN-ANCH, PTR-FIRST contains theaddress of the first record in the chained list. If something goes wrongwith the call, and PTR-FIRST never receives the value of the address of thefirst record in the chain, a null value remains in PTR-FIRST and, accordingto the logic of the program, the records will not be processed.(2) The LINKAGE SECTION of the calling program contains the description of therecords in the chained list. It also contains the description of thedepartment code that is passed, using the USING clause of the CALLstatement.(3) To obtain the address of the first SALARY-REC record area, the LISTSprogram calls the program CHAIN-ANCH:(4) The SET statement bases the record description SALARY-REC on the addresscontained in PTR-FIRST.(5) The chained list in this example is set up so that the last record contains anaddress that is not valid. This check <strong>for</strong> the end of the chained list isaccomplished with a do-while structure where the value NULL is assignedto the pointer data item in the last record.(6) The address of the record in the LINKAGE-SECTION is set equal to theaddress of the next record by means of the pointer data item sent as thefirst field in SALARY-REC. The record-processing routine repeats, processingthe next record in the chained list.To increment addresses received from another program, you could set up theLINKAGE SECTION and PROCEDURE DIVISION like this:LINKAGE SECTION.01 RECORD-A.02 HEADER PIC X(12).02 REAL-SALARY-REC PIC X(30)....01 SALARY-REC.02 PTR-NEXT-REC POINTER.02 NAME PIC X(20).02 DEPT PIC 9(4).02 SALARY PIC 9(6)....PROCEDURE DIVISION USING DEPT-X....SET ADDRESS OF SALARY-REC TO ADDRESS OF REAL-SALARY-RECThe address of SALARY-REC is now based on the address of REAL-SALARY-REC, orRECORD-A + 12.RELATED TASKS“Using pointers to process a chained list” on page 471Chapter 25. Sharing data 473


Passing return-code in<strong>for</strong>mationUse the RETURN-CODE special register to pass return codes between programs.(Methods do not return in<strong>for</strong>mation in the RETURN-CODE special register, but theycan check the register after a call to a program.)You can also use the RETURNING phrase in the PROCEDURE DIVISION header of amethod to return in<strong>for</strong>mation to an invoking program or method. If you usePROCEDURE DIVISION ...RETURNING with CALL...RETURNING, the RETURN-CODEregister will not be set.Understanding the RETURN-CODE special registerWhen a <strong>COBOL</strong> program returns to its caller, the contents of the RETURN-CODEspecial register are stored into register 15.When control is returned to a <strong>COBOL</strong> program or method from a call, the contentsof register 15 are stored into the RETURN-CODE special register of the calling programor method. When control is returned from a <strong>COBOL</strong> program to the operatingsystem, the special register contents are returned as a user return code.You might need to think about this handling of the RETURN-CODE special registerwhen control is returned to a <strong>COBOL</strong> program from a non-<strong>COBOL</strong> program. If thenon-<strong>COBOL</strong> program does not use register 15 to pass back the return code, theRETURN-CODE special register of the <strong>COBOL</strong> program might be updated with aninvalid value. Unless you set this special register to a meaningful value be<strong>for</strong>eyour <strong>Enterprise</strong> <strong>COBOL</strong> program returns to the operating system, a return codethat is invalid will be passed to the system.For equivalent function between <strong>COBOL</strong> and C programs, have your <strong>COBOL</strong>program call the C program with the RETURNING phrase. If the C program(function) correctly declares a function value, the RETURNING value of the calling<strong>COBOL</strong> program will be set.You cannot set the RETURN-CODE special register by using the INVOKE statement.Using PROCEDURE DIVISION RETURNING ...Use the RETURNING phrase in the PROCEDURE DIVISION header of a program to returnin<strong>for</strong>mation to the calling program.PROCEDURE DIVISION RETURNING dataname2When the called program in the example above successfully returns to its caller,the value in dataname2 is stored into the identifier that you specified in theRETURNING phrase of the CALL statement:CALL...RETURNING dataname2CEEPIPI: The results of specifying PROCEDURE DIVISION RETURNING in programs thatare called with the Language Environment preinitialization service (CEEPIPI) areundefined.474 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Specifying CALL . . . RETURNINGYou can specify the RETURNING phrase of the CALL statement <strong>for</strong> calls to C/C++functions or to <strong>COBOL</strong> subroutines.The RETURNING phrase has the following <strong>for</strong>mat.CALL...RETURNING dataname2The return value of the called program is stored into dataname2. You must definedataname2 in the DATA DIVISION of the calling program. The data type of the returnvalue that is declared in the target function must be identical to the data type ofdataname2.Sharing data by using the EXTERNAL clauseUse the EXTERNAL clause to allow separately compiled programs and methods(including programs in a batch sequence) to share data items. Code EXTERNAL in thelevel-01 data description in the WORKING-STORAGE SECTION.The following rules apply:v Items that are subordinate to an EXTERNAL group item are themselves EXTERNAL.v You cannot use the name of an EXTERNAL data item as the name <strong>for</strong> anotherEXTERNAL item in the same program.v You cannot code the VALUE clause <strong>for</strong> any group item or subordinate item that isEXTERNAL.In the run unit, any <strong>COBOL</strong> program or method that has the same data description<strong>for</strong> the item as the program that contains the item can access and process that item.For example, suppose program A has the following data description:01 EXT-ITEM1 EXTERNAL PIC 99.Program B can access that data item if it has the identical data description in itsWORKING-STORAGE SECTION.Any program that has access to an EXTERNAL data item can change the value of thatitem. There<strong>for</strong>e do not use this clause <strong>for</strong> data items that you need to protect.Sharing files between programs (external files)To enable separately compiled programs or methods in a run unit to access a fileas a common file, use the EXTERNAL clause <strong>for</strong> the file.It is recommended that you follow these guidelines:v Use the same data-name in the FILE STATUS clause of all the programs thatcheck the file status code.v For each program that checks the same file status field, code the EXTERNAL clauseon the level-01 data definition <strong>for</strong> the file status field.Using an external file has these benefits:v Even though the main program does not contain any input or output statements,it can reference the record area of the file.Chapter 25. Sharing data 475


vvEach subprogram can control a single input or output function, such as OPEN orREAD.Each program has access to the file.“Example: using external files”RELATED TASKS“Using data in input and output operations” on page 13RELATED REFERENCESEXTERNAL clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: using external filesThe following example shows the use of an external file in several programs. COPYstatements ensure that each subprogram contains an identical description of thefile.The table below describes the main program and subprograms.Nameef1ef1openoef1writeef1openief1readef1closeFunctionThe main program, which calls all the subprograms and then verifies thecontents of a record areaOpens the external file <strong>for</strong> output and checks the file status codeWrites a record to the external file and checks the file status codeOpens the external file <strong>for</strong> input and checks the file status codeReads a record from the external file and checks the file status codeCloses the external file and checks the file status codeEach program uses three copybooks:v efselect is placed in the FILE-CONTROL paragraph.vvSelect ef1Assign To ef1File Status Is efs1Organization Is Sequential.effile is placed in the FILE SECTION.Fd ef1 Is ExternalRecord Contains 80 CharactersRecording Mode F.01 ef-record-1.02 ef-item-1 Pic X(80).efwrkstg is placed in the WORKING-STORAGE SECTION.01 efs1 Pic 99 External.Input-output using external filesIdentification Division.Program-Id.ef1.** This main program controls external file processing.*Environment Division.Input-Output Section.File-Control.476 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Copy efselect.Data Division.File Section.Copy effile.Working-Storage Section.Copy efwrkstg.Procedure Division.Call "ef1openo"Call "ef1write"Call "ef1close"Call "ef1openi"Call "ef1read"If ef-record-1 = "First record" ThenDisplay "First record correct"ElseDisplay "First record incorrect"Display "Expected: " "First record"Display "Found : " ef-record-1End-IfCall "ef1close"Goback.End Program ef1.Identification Division.Program-Id.ef1openo.** This program opens the external file <strong>for</strong> output.*Environment Division.Input-Output Section.File-Control.Copy efselect.Data Division.File Section.Copy effile.Working-Storage Section.Copy efwrkstg.Procedure Division.Open Output ef1If efs1 Not = 0Display "file status " efs1 " on open output"Stop RunEnd-IfGoback.End Program ef1openo.Identification Division.Program-Id.ef1write.** This program writes a record to the external file.*Environment Division.Input-Output Section.File-Control.Copy efselect.Data Division.File Section.Copy effile.Working-Storage Section.Copy efwrkstg.Procedure Division.Move "First record" to ef-record-1Write ef-record-1If efs1 Not = 0Display "file status " efs1 " on write"Stop RunEnd-IfChapter 25. Sharing data 477


Goback.End Program ef1write.Identification Division.Program-Id.ef1openi.** This program opens the external file <strong>for</strong> input.*Environment Division.Input-Output Section.File-Control.Copy efselect.Data Division.File Section.Copy effile.Working-Storage Section.Copy efwrkstg.Procedure Division.Open Input ef1If efs1 Not = 0Display "file status " efs1 " on open input"Stop RunEnd-IfGoback.End Program ef1openi.Identification Division.Program-Id.ef1read.** This program reads a record from the external file.*Environment Division.Input-Output Section.File-Control.Copy efselect.Data Division.File Section.Copy effile.Working-Storage Section.Copy efwrkstg.Procedure Division.Read ef1If efs1 Not = 0Display "file status " efs1 " on read"Stop RunEnd-IfGoback.End Program ef1read.Identification Division.Program-Id.ef1close.** This program closes the external file.*Environment Division.Input-Output Section.File-Control.Copy efselect.Data Division.File Section.Copy effile.Working-Storage Section.Copy efwrkstg.Procedure Division.Close ef1If efs1 Not = 0Display "file status " efs1 " on close"478 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Stop RunEnd-IfGoback.End Program ef1close.Chapter 25. Sharing data 479


480 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 26. Creating a DLL or a DLL applicationCreating a dynamic link library (DLL) or a DLL application is similar to creating aregular <strong>COBOL</strong> application. It involves writing, compiling, and linking your sourcecode.Special considerations when writing a DLL or a DLL application include:v Determining how the parts of the load module or the application relate to eachother or to other DLLsv Deciding what linking or calling mechanisms to useDepending on whether you want to create a DLL load module or a load modulethat references a separate DLL, you need to use slightly different compiler andlinkage-editor or binder options.RELATED CONCEPTS“Dynamic link libraries (DLLs)”Dynamic link libraries (DLLs)RELATED TASKS“Creating a DLL under z/<strong>OS</strong> UNIX” on page 286“Compiling programs to create DLLs” on page 482“Linking DLLs” on page 483“Using CALL identifier with DLLs” on page 485“Using DLL linkage and dynamic calls together” on page 486“Using <strong>COBOL</strong> DLLs with C/C++ programs” on page 490“Using DLLs in OO <strong>COBOL</strong> applications” on page 491“Using procedure or function pointers with DLLs” on page 488A DLL is a load module or a program object that can be accessed from otherseparate load modules.A DLL differs from a traditional load module in that it exports definitions ofprograms, functions, or variables to DLLs, DLL applications, or non-DLLs.There<strong>for</strong>e, you do not need to link the target routines into the same load moduleas the referencing routine. When an application references a separate DLL <strong>for</strong> thefirst time, the system automatically loads the DLL into memory. In other words,calling a program in a DLL is similar to calling a load module with a dynamicCALL.© Copyright IBM Corp. 1991, 2009 481


A DLL application is an application that references imported definitions ofprograms, functions, or variables.Although some functions of z/<strong>OS</strong> DLLs overlap the functions provided by <strong>COBOL</strong>dynamic CALL statements, DLLs have several advantages over regular z/<strong>OS</strong> loadmodules and dynamic calls:vvDLLs are common across <strong>COBOL</strong> and C/C++, thus providing betterinteroperation <strong>for</strong> applications that use multiple programming languages.Reentrant <strong>COBOL</strong> and C/C++ DLLs can also interoperate smoothly.You can make calls to programs in separate DLL modules that have longprogram-names. (Dynamic call resolution truncates program-names to eightcharacters.) Using the <strong>COBOL</strong> option PGMNAME(LONGUPPER) or PGMNAME(LONGMIXED)and the <strong>COBOL</strong> DLL support, you can make calls between load modules withnames of up to 160 characters.DLLs are supported by IBM z/<strong>OS</strong> Language Environment, based on functionprovided by the z/<strong>OS</strong> program management binder. DLL support is available <strong>for</strong>applications running under z/<strong>OS</strong> in batch or in TSO, CICS, UNIX, or IMSenvironments.RELATED REFERENCES“PGMNAME” on page 338MVS Program Management: User’s <strong>Guide</strong> and Reference (Binder support <strong>for</strong> DLLs)Compiling programs to create DLLsWhen you compile a <strong>COBOL</strong> program with the DLL option, it becomes enabled <strong>for</strong>DLL support. Applications that use DLL support must be reentrant. There<strong>for</strong>e, youmust compile them with the RENT compiler option and link them with the RENTbinder option.In an application with DLL support, use the following compiler options dependingon where the programs or classes are:Table 66. Compiler options <strong>for</strong> DLL applicationsPrograms or classes in:Root load moduleDLL load modules used by other loadmodulesCompile with:DLL, RENT, NOEXPORTALLDLL, RENT, EXPORTALL482 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If a DLL load module includes some programs that are used only from within theDLL module, you can hide these routines by compiling them with NOEXPORTALL.“Example: sample JCL <strong>for</strong> a procedural DLL application” on page 484RELATED TASKS“Creating a DLL under z/<strong>OS</strong> UNIX” on page 286“Linking DLLs”“Prelinking certain DLLs” on page 485Chapter 26, “Creating a DLL or a DLL application,” on page 481RELATED REFERENCES“DLL” on page 318“EXPORTALL” on page 321“RENT” on page 341Linking DLLsYou can link DLL-enabled object modules into separate DLL load modules, or youcan link them together statically. You can decide whether to package theapplication as one module or as several DLL modules at link time.The DLL support in the z/<strong>OS</strong> binder is recommended <strong>for</strong> linking DLLapplications. The binder can directly receive the output of <strong>COBOL</strong> compilers, thuseliminating the prelink step. However, you must use the Language Environmentprelinker be<strong>for</strong>e standard linkage editing if your DLL must reside in a PDS loadlibrary.A binder-based DLL must reside in a PDSE or in an HFS file rather than in a PDS.When using the binder to link a DLL application, use the following options:Table 67. Binder options <strong>for</strong> DLL applicationsType of codeLink using binder parameters:DLL applicationsDYNAM(DLL), RENTApplications that use mixed-case exported CASE(MIXED)program-namesClass definitions or INVOKE statementsYou must specify a SYSDEFSD DD statement to indicate the data set in which thebinder should create a DLL definition side file. This side file contains IMPORTcontrol statements <strong>for</strong> each symbol exported by a DLL. The binder SYSLIN input(the binding code that references the DLL code) must include the DLL definitionside files <strong>for</strong> DLLs that are to be referenced from the module being linked.If there are programs in the module that you do not want to make available withDLL linkage, you can edit the definition side file to remove these programs.“Example: sample JCL <strong>for</strong> a procedural DLL application” on page 484Chapter 26. Creating a DLL or a DLL application 483


RELATED TASKS“Creating a DLL under z/<strong>OS</strong> UNIX” on page 286Chapter 26, “Creating a DLL or a DLL application,” on page 481“Compiling programs to create DLLs” on page 482“Prelinking certain DLLs” on page 485RELATED REFERENCESMVS Program Management: User’s <strong>Guide</strong> and Reference (Binder support <strong>for</strong> DLLs)Example: sample JCL <strong>for</strong> a procedural DLL applicationThe following example shows how to create an application that consists of a mainprogram that calls a DLL subprogram.The first step creates the DLL load module that contains the subprogramDemoDLLSubprogram. The second step creates the main load module that containsthe program MainProgram. The third step runs the application.//DLLSAMP JOB ,// TIME=(1),MSGLEVEL=(1,1),MSGCLASS=H,CLASS=A,// NOTIFY=&SYSUID,USER=&SYSUID// SET LEPFX='SYS1'//*---------------------------------------------------------------------//* Compile <strong>COBOL</strong> subprogram, bind to <strong>for</strong>m a DLL.//*---------------------------------------------------------------------//STEP1 EXEC IGYWCL,REGION=80M,GOPGM=DEMODLL,// PARM.<strong>COBOL</strong>='RENT,PGMN(LM),DLL,EXPORTALL',// PARM.LKED='RENT,LIST,XREF,LET,MAP,DYNAM(DLL),CASE(MIXED)'//<strong>COBOL</strong>.SYSIN DD *Identification division.Program-id. "DemoDLLSubprogram".Procedure division.Display "Hello from DemoDLLSubprogram!".End program "DemoDLLSubprogram"./*//LKED.SYSDEFSD DD DSN=&&SIDEDECK,UNIT=SYSDA,DISP=(NEW,PASS),// SPACE=(TRK,(1,1))//LKED.SYSLMOD DD DSN=&&G<strong>OS</strong>ET(&GOPGM),DSNTYPE=LIBRARY,DISP=(MOD,PASS)//LKED.SYSIN DD DUMMY//*---------------------------------------------------------------------//* Compile and bind <strong>COBOL</strong> main program//*---------------------------------------------------------------------//STEP2 EXEC IGYWCL,REGION=80M,GOPGM=MAINPGM,// PARM.<strong>COBOL</strong>='RENT,PGMNAME(LM),DLL',// PARM.LKED='RENT,LIST,XREF,LET,MAP,DYNAM(DLL),CASE(MIXED)'//<strong>COBOL</strong>.SYSIN DD *Identification division.Program-id. "MainProgram".Procedure division.Call "DemoDLLSubprogram"Stop Run.End program "MainProgram"./*//LKED.SYSIN DD DSN=&&SIDEDECK,DISP=(OLD,DELETE)//*---------------------------------------------------------------------//* Execute the main program, calling the subprogram DLL.//*---------------------------------------------------------------------//STEP3 EXEC PGM=MAINPGM,REGION=80M//STEPLIB DD DSN=&&G<strong>OS</strong>ET,DISP=(OLD,DELETE)// DD DSN=&LEPFX..SCEERUN,DISP=SHR//SYSOUT DD SYSOUT=*//CEEDUMP DD SYSOUT=*484 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Prelinking certain DLLsYou must use the Language Environment prelinker be<strong>for</strong>e standard linkage editingif a DLL must reside in a PDS load library rather than in a PDSE or an HFS file.After compiling the DLL source, prelink the object modules to <strong>for</strong>m a single objectmodule:1. Specify a SYSDEFSD DD statement <strong>for</strong> the prelink step to indicate the data set inwhich the prelinker should create a DLL definition side file. The side filecontains IMPORT prelinker control statements <strong>for</strong> each symbol exported by theDLL. The prelinker uses this side file to prelink other modules that referencethe new DLL.2. Specify the DLLNAME(xxx) prelinker option to indicate the DLL load modulename <strong>for</strong> the prelinker to use in constructing the IMPORT control statements inthe side file. Alternatively, the prelinker can obtain the DLL load module namefrom the NAME prelinker control statement or from the PDS member name in theSYSMOD DD statement <strong>for</strong> the prelink step.3. If the new DLL references any other DLLs, include the definition side files <strong>for</strong>these DLLs together with the object decks that are input to this prelink step.These side files instruct the prelinker to resolve the symbolic references in thecurrent module to the symbols exported from the other DLLs.Use the linkage editor or binder as usual to create the DLL load module from theobject module produced by the prelinker. Specify the RENT option of the linkageeditor or binder.RELATED TASKS“Compiling programs to create DLLs” on page 482“Linking DLLs” on page 483Using CALL identifier with DLLsIn a <strong>COBOL</strong> program that has been compiled with the DLL option, you can useCALL identifier and CALL literal statements to make calls to DLLs. However, there area few additional considerations <strong>for</strong> the CALL identifier case.For the content of the identifier or <strong>for</strong> the literal, use the name of either of thefollowing programs:vvA nested program in the same compilation unit that is eligible to be called fromthe program that contains the CALL identifier statement.A program in a separately bound DLL module. The target program-name mustbe exported from the DLL, and the DLL module name must match the exportedname of the target program.In the nonnested case, the runtime environment interprets the program-name inthe identifier according to the setting of the PGMNAME compiler option of the programthat contains the CALL statement, and interprets the program-name that is exportedfrom the target DLL according to the setting of the PGMNAME option used when thetarget program was compiled.The search <strong>for</strong> the target DLL in the hierarchical file system (HFS) is case sensitive.If the target DLL is a PDS or PDSE member, the DLL member name must be eightChapter 26. Creating a DLL or a DLL application 485


characters or less. For the purpose of the search <strong>for</strong> the DLL as a PDS or PDSEmember, the run time automatically converts the name to uppercase.If the runtime environment cannot resolve the CALL statement in either of thesecases, control is transferred to the ON EXCEPTION or ON OVERFLOW phrase of the CALLstatement. If the CALL statement does not specify one of these phrases in thissituation, Language Environment raises a severity-3 condition.RELATED TASKS“Using DLL linkage and dynamic calls together”“Compiling programs to create DLLs” on page 482“Linking DLLs” on page 483RELATED REFERENCES“DLL” on page 318“PGMNAME” on page 338CALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)“Search order <strong>for</strong> DLLs in the HFS”Search order <strong>for</strong> DLLs in the HFSWhen you use the hierarchical file system (HFS), the search order <strong>for</strong> resolving aDLL reference in a CALL statement depends on the setting of the LanguageEnvironment P<strong>OS</strong>IX runtime option.If the P<strong>OS</strong>IX runtime option is ON, the search order is as follows:1. The runtime environment looks <strong>for</strong> the DLL in the HFS. If the LIBPATHenvironment variable is set, the run time searches each directory listed.Otherwise, it searches just the current directory. The search <strong>for</strong> the DLL in theHFS is case sensitive.2. If the runtime environment does not find the DLL in the HFS, it tries to loadthe DLL from the MVS load library search order of the caller. In this case, theDLL name must be eight characters or less. The run time automaticallyconverts the DLL name to uppercase <strong>for</strong> this search.If the P<strong>OS</strong>IX runtime option is set to OFF, the search order is reversed:1. The runtime environment tries to load the DLL from the search order <strong>for</strong> theload library of the caller.2. If the runtime environment cannot load the DLL from this load library, it triesto load the DLL from the HFS.RELATED TASKS“Using CALL identifier with DLLs” on page 485RELATED REFERENCESLanguage Environment <strong>Programming</strong> Reference (P<strong>OS</strong>IX)Using DLL linkage and dynamic calls togetherFor applications (that is, Language Environment enclaves) that are structured asmultiple, separately bound modules, you should use exclusively one <strong>for</strong>m oflinkage between modules: either dynamic call linkage or DLL linkage.486 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


DLL linkage refers to a call in a program that is compiled with the DLL and NODYNAMoptions in which the call resolves to an exported name in a separate module. DLLlinkage can also refer to an invocation of a method that is defined in a separatemodule.However, some applications require more flexibility. If so, you can use both DLLlinkage and <strong>COBOL</strong> dynamic call linkage within a Language Environment enclaveif the programs are compiled as follows:Program A Program B Compile both with:Contains dynamic call Target of dynamic call NODLLUses DLL linkageContains target program ormethodDLLIf a program contains a CALL statement <strong>for</strong> a separately compiled program and youcompile one program with the DLL compiler option and the other program withNODLL, then the call is supported only if you bind the two programs together in thesame module.The following diagram shows several separately bound modules that mix dynamiccalls and DLL linkage.All components of a DLL application must have the same AMODE. The automaticAMODE switching normally provided by <strong>COBOL</strong> dynamic calls is not available<strong>for</strong> DLL linkages.You cannot cancel programs that are called using DLL linkage.RELATED CONCEPTS“Dynamic link libraries (DLLs)” on page 481RELATED TASKS“Compiling programs to create DLLs” on page 482“Linking DLLs” on page 483“Using procedure or function pointers with DLLs” on page 488“Calling DLLs from non-DLLs” on page 488Chapter 26. Creating a DLL or a DLL application 487


RELATED REFERENCES“DLL” on page 318“EXPORTALL” on page 321Using procedure or function pointers with DLLsIn run units that contain both DLLs and non-DLLs, use procedure- andfunction-pointer data items with care.When you use the SET procedure-pointer-1 TO ENTRY entry-name or SETfunction-pointer-1 TO ENTRY entry-name statement in a program that is compiled withthe NODLL option, you must not pass the pointer to a program that is compiledwith the DLL option. However, when you use this statement in a program that iscompiled with the DLL option, you can pass the pointer to a program that is in aseparately bound DLL module.If you compile with the NODYNAM and DLL options, and entry-name is an identifier,the identifier value must refer to the entry-point name that is exported from a DLLmodule. The DLL module name must match the name of the exported entry point.In this case, note also that:vvvvThe program-name that is contained in the identifier is interpreted according tothe setting of the PGMNAME(COMPAT|LONGUPPER|LONGMIXED) compiler option of theprogram that contains the CALL statement.The program-name that is exported from the target DLL is interpreted accordingto the setting of the PGMNAME option used when compiling the target program.The search <strong>for</strong> the target DLL in the HFS is case sensitive.If the target DLL is a PDS or PDSE member, the DLL member name must haveeight characters or less. For the purpose of the search <strong>for</strong> the DLL as a PDS orPDSE member, the name is automatically converted to uppercase.RELATED TASKS“Using CALL identifier with DLLs” on page 485“Using procedure and function pointers” on page 462“Compiling programs to create DLLs” on page 482“Linking DLLs” on page 483RELATED REFERENCES“DLL” on page 318“EXPORTALL” on page 321Calling DLLs from non-DLLsIt is possible to call a DLL from a <strong>COBOL</strong> program that is compiled with the NODLLoption, but there are restrictions.You can use the following methods to ensure that the DLL linkage is followed:v Put the <strong>COBOL</strong> DLL programs that you want to call from the <strong>COBOL</strong> non-DLLprograms in the load module that contains the main program. Use static callsfrom the <strong>COBOL</strong> non-DLL programs to call the <strong>COBOL</strong> DLL programs.The <strong>COBOL</strong> DLL programs in the load module that contains the main programcan call <strong>COBOL</strong> DLL programs in other DLLs.v Put the <strong>COBOL</strong> DLL programs in DLLs and call them from <strong>COBOL</strong> non-DLLprograms with CALL function-pointer, where function-pointer is set to a function488 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


descriptor of the target program. You can obtain the address of the functiondescriptor <strong>for</strong> the program in the DLL by calling aCroutine that uses dllloadand dllqueryfn.“Example: calling DLLs from non-DLLs”RELATED TASKS“Using procedure and function pointers” on page 462Example: calling DLLs from non-DLLsThe following example shows how a <strong>COBOL</strong> program that is not in a DLL(<strong>COBOL</strong>1) can call a <strong>COBOL</strong> program that is in a DLL (program ooc05R in DLLOOC05R).CBL NODYNAMIDENTIFICATION DIVISION.PROGRAM-ID. '<strong>COBOL</strong>1'.ENVIRONMENT DIVISION.CONFIGURATION SECTION.INPUT-OUTPUT SECTION.FILE-CONTROL.DATA DIVISION.FILE SECTION.WORKING-STORAGE SECTION.01 DLL-INFO.03 DLL-LOADMOD-NAME PIC X(12).03 DLL-PROGRAM-NAME PIC X(160).03 DLL-PROGRAM-HANDLE FUNCTION-POINTER.77 DLL-RC PIC S9(9) BINARY.77 DLL-STATUS PIC X(1) VALUE 'N'.88 DLL-LOADED VALUE 'Y'.88 DLL-NOT-LOADED VALUE 'N'.PROCEDURE DIVISION.IF DLL-NOT-LOADEDTHEN* Move the names in. They must be null terminated.MOVE Z'OOC05R' TO DLL-LOADMOD-NAMEMOVE Z'ooc05r' TO DLL-PROGRAM-NAME* Call the C routine to load the DLL and to get the* function descriptor address.CALL 'A1CCDLGT' USING BY REFERENCE DLL-INFOBY REFERENCE DLL-RCIF DLL-RC = 0THENSET DLL-LOADED TO TRUEELSEDISPLAY 'A1CCLDGT failed with rc = 'DLL-RCMOVE 16 TO RETURN-CODESTOP RUNEND-IFEND-IF* Use the function pointer on the call statement to call the* program in the DLL.* Call the program in the DLL.CALL DLL-PROGRAM-HANDLEGOBACK.Chapter 26. Creating a DLL or a DLL application 489


#include #include #pragma linkage (A1CCDLGT,<strong>COBOL</strong>)typedef struct dll_lm {char dll_loadmod_name[(12]);char dll_func_name[(160]);void (*fptr) (void); /* function pointer */} dll_lm;void A1CCDLGT (dll_lm *dll, int *rc){dllhandle *handle;void (*fptr1)(void);*rc=0;/* Load the DLL */handle = dllload(dll->dll_loadmod_name);if (handle == NULL) {perror("A1CCDLGT failed on call to load DLL./n");*rc=1;return;}/* Get the address of the function */fptr1 = (void (*)(void))dllqueryfn(handle,dll->dll_func_name);if (fptr1 == NULL) {perror("A1CCDLGT failed on retrieving function./n");*rc=2;return;}/* Return the function pointer */dll->fptr = fptr1;return;}Using <strong>COBOL</strong> DLLs with C/C++ programs<strong>COBOL</strong> support <strong>for</strong> DLLs interoperates with the DLL support in the z/<strong>OS</strong> C/C++products, except <strong>for</strong> <strong>COBOL</strong> EXTERNAL data. In particular, <strong>COBOL</strong> applications cancall functions that are exported from C/C++ DLLs, and C/C++ applications cancall <strong>COBOL</strong> programs that are exported from <strong>COBOL</strong> DLLs.<strong>COBOL</strong> data items that are declared with the EXTERNAL attribute are independent ofDLL support. These data items are accessible by name from any <strong>COBOL</strong> programin the run unit that declares them, regardless of whether the programs are in DLLs.The <strong>COBOL</strong> options DLL, RENT, and EXPORTALL work much the same way as theC/C++ DLL, RENT, and EXPORTALL options. (The DLL option applies only to C.)However, the C/C++ compiler produces DLL-enabled code by default.You can pass a C/C++ DLL function pointer to <strong>COBOL</strong> and use it within <strong>COBOL</strong>,receiving the C/C++ function pointer as a function-pointer data item. Thefollowing example shows a <strong>COBOL</strong> call to a C function that returns a functionpointer to a service, followed by a <strong>COBOL</strong> call to the service.Identification Division.Program-id. Demo.Data Division.Working-Storage section.490 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


01 fp usage function-pointer.Procedure Division.Call "c-function" returning fp.Call fp.RELATED TASKS“Compiling programs to create DLLs” on page 482“Linking DLLs” on page 483RELATED REFERENCES“DLL” on page 318“EXPORTALL” on page 321“RENT” on page 341EXTERNAL clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Using DLLs in OO <strong>COBOL</strong> applicationsYou must compile each <strong>COBOL</strong> class definition using the DLL, THREAD, RENT, andDBCS compiler options, and link-edit it into a separate DLL module using the RENTbinder option.RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291“Compiling programs to create DLLs” on page 482“Linking DLLs” on page 483RELATED REFERENCES“DLL” on page 318“THREAD” on page 352“RENT” on page 341“DBCS” on page 317Chapter 26. Creating a DLL or a DLL application 491


492 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 27. Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreadingYou can run <strong>COBOL</strong> programs in multiple threads within a process under batch,TSO, IMS, or UNIX.There is no explicit <strong>COBOL</strong> language to use <strong>for</strong> multithreaded execution; rather,you compile with the THREAD compiler option.<strong>COBOL</strong> does not directly support managing program threads. However, you canrun <strong>COBOL</strong> programs that you compile with the THREAD compiler option inmultithreaded application servers, in applications that use a C/C++ driverprogram to create the threads, in programs that interoperate with Java and useJava threads, and in applications that use PL/I tasking. In other words, otherprograms can call <strong>COBOL</strong> programs in such a way that the <strong>COBOL</strong> programs runin multiple threads within a process or as multiple program invocation instanceswithin a thread. Your threaded application must run within a single LanguageEnvironment enclave.Choosing LOCAL-STORAGE or WORKING-STORAGE: Because you must code yourmultithreaded programs as recursive, the persistence of data is that of anyrecursive program:vvData items in the LOCAL-STORAGE SECTION are automatically allocated <strong>for</strong> eachinstance of a program invocation. When a program runs in multiple threadssimultaneously, each invocation has a separate copy of LOCAL-STORAGE data.Data items in the WORKING-STORAGE SECTION are allocated once <strong>for</strong> each programand are thus available in their last-used state to all invocations of the program.For the data that you want to isolate to an individual program invocation instance,define the data in the LOCAL-STORAGE SECTION. In general, this choice is appropriate<strong>for</strong> working data in threaded programs. If you declare data in WORKING-STORAGEand your program changes the contents of the data, you must take one of thefollowing actions:vvStructure your application so that you do not access data in WORKING-STORAGEsimultaneously from multiple threads.If you do access data simultaneously from separate threads, write appropriateserialization code.RELATED CONCEPTS“Multithreading” on page 494RELATED TASKS“Choosing THREAD to support multithreading” on page 495“Transferring control to multithreaded programs” on page 495“Ending multithreaded programs” on page 496“Processing files with multithreading” on page 496“Handling <strong>COBOL</strong> limitations with multithreading” on page 499RELATED REFERENCES“THREAD” on page 352PROGRAM-ID paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)© Copyright IBM Corp. 1991, 2009 493


MultithreadingTo use <strong>COBOL</strong> support <strong>for</strong> multithreading, you need to understand how processes,threads, run units, and program invocation instances relate to each other.The operating system and multithreaded applications can handle execution flowwithin a process, which is the course of events when all or part of a program runs.Programs that run within a process can share resources. Processes can bemanipulated. For example, they can have a high or low priority in terms of theamount of time that the system devotes to running the process.Within a process, an application can initiate one or more threads, each of which is astream of computer instructions that controls that thread. A multithreaded processbegins with one stream of instructions (one thread) and can later create otherinstruction streams to per<strong>for</strong>m tasks. These multiple threads can run concurrently.Within a thread, control is transferred between executing programs.In a multithreaded environment, a <strong>COBOL</strong> run unit is the portion of the processthat includes threads that have actively executing <strong>COBOL</strong> programs. The <strong>COBOL</strong>run unit continues until no <strong>COBOL</strong> program is active in the execution stack <strong>for</strong>any of the threads. For example, a called <strong>COBOL</strong> program contains a GOBACKstatement and returns control to aCprogram. Within the run unit, <strong>COBOL</strong>programs can call non-<strong>COBOL</strong> programs, and vice versa.Within a thread, control is transferred between separate <strong>COBOL</strong> and non-<strong>COBOL</strong>programs. For example, a <strong>COBOL</strong> program can call another <strong>COBOL</strong> program or aC program. Each separately called program is a program invocation instance.Program invocation instances of a particular program can exist in multiple threadswithin a given process.The following illustration shows these relationships between processes, threads,run units, and program invocation instances.RELATED CONCEPTSLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (Program management model,Understanding the basics: threads)494 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Choosing THREAD to support multithreading”“Transferring control to multithreaded programs”“Ending multithreaded programs” on page 496“Processing files with multithreading” on page 496“Handling <strong>COBOL</strong> limitations with multithreading” on page 499RELATED REFERENCES“THREAD” on page 352Choosing THREAD to support multithreadingUse the THREAD compiler option <strong>for</strong> multithreading support. Use THREAD if yourprogram will be called in more than one thread in a single process by anapplication. However, THREAD might adversely affect per<strong>for</strong>mance because of theserialization logic that is automatically generated.In order to run <strong>COBOL</strong> programs in more than one thread, you must compile allof the <strong>COBOL</strong> programs in the application using the THREAD compiler option. Youmust also compile them with the RENT compiler option and link them with theRENT option of the binder or linkage editor.Use the THREAD option when you compile object-oriented (OO) clients and classes.Language restrictions: When you use the THREAD option, you cannot use certainlanguage elements. For details, see the related reference below.Recursion: Be<strong>for</strong>e you compile a program using the THREAD compiler option, youmust specify the RECURSIVE phrase in the PROGRAM-ID paragraph. If you do not doso, an error will occur.RELATED TASKS“Sharing data in recursive or multithreaded programs” on page 19“Compiling OO applications under z/<strong>OS</strong> UNIX” on page 291RELATED REFERENCES“THREAD” on page 352Transferring control to multithreaded programsWhen you write <strong>COBOL</strong> programs <strong>for</strong> a multithreaded environment, chooseappropriate program linkage statements.As in single-threaded environments, a called program is in its initial state when itis first called within a run unit and when it is first called after a CANCEL to thecalled program. Ensure that the program that you name on a CANCEL statement isnot active on any thread. If you try to cancel an active program, a severity-3Language Environment condition occurs.If your threaded application requires preinitialization, use the LanguageEnvironment services (CEEPIPI interface). You cannot use the <strong>COBOL</strong>-specificinterfaces <strong>for</strong> preinitialization (runtime option RTEREUS and functions IGZERRE andILB<strong>OS</strong>TP0) to establish a reusable environment from any program that has beencompiled with the THREAD option.Chapter 27. Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading 495


RELATED CONCEPTSLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (What happens during termination:enclave termination)RELATED TASKS“Ending multithreaded programs”“Ending and reentering main programs or subprograms” on page 448Ending multithreaded programsYou can end a multithreaded program by using GOBACK, EXIT PROGRAM, orSTOP RUN.Use GOBACK to return to the caller of the program. When you use GOBACK from thefirst program in a thread, the thread is terminated. If that thread is the initialthread in an enclave, the entire enclave is terminated.Use EXIT PROGRAM as you would GOBACK, except from a main program where it hasno effect.Use STOP RUN to terminate the entire Language Environment enclave and to returncontrol to the caller of the main program (which might be the operating system).All threads that are executing within the enclave are terminated.RELATED CONCEPTSLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (What happens during termination:enclave termination)RELATED TASKS“Ending and reentering main programs or subprograms” on page 448Processing files with multithreadingIn threaded applications, you can code <strong>COBOL</strong> statements <strong>for</strong> input and output inQSAM, VSAM, and line-sequential files.Each file definition (FD) has an implicit serialization lock. This lock is used withautomatic serialization logic during the input or output operation that is associatedwith the execution of the following statements:v OPENv CL<strong>OS</strong>Ev READv WRITEv REWRITEv STARTv DELETEAutomatic serialization also occurs <strong>for</strong> the implicit MOVE that is associated with thefollowing statements:WRITE record-name FROM identifierREAD file-name INTO identifierAutomatic serialization is not applied to any statements specified within thefollowing conditional phrases:496 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvvvvvAT ENDNOT AT ENDINVALID KEYNOT INVALID KEYAT END-OF-PAGENOT AT END-OF-PAGERELATED CONCEPTS“File-definition (FD) storage”RELATED TASKS“Closing QSAM files” on page 165“Closing VSAM files” on page 194“Coding ERROR declaratives” on page 238“Serializing file access with multithreading”File-definition (FD) storageOn all program invocations, the storage that is associated with a file definition(such as FD records and the record area that is associated with the SAME RECORDAREA clause) is allocated and available in its last-used state.All threads of execution share this storage. You can depend on automaticserialization <strong>for</strong> this storage during the execution of the OPEN, CL<strong>OS</strong>E, READ, WRITE,REWRITE, START, and DELETE statements, but not between uses of these statements.RELATED TASKS“Serializing file access with multithreading”Serializing file access with multithreadingTo take full advantage of automatic serialization and to avoid explicitly writingyour own serialization logic, use one of the recommended file organizations andusage patterns when you access files in threaded programs.Use one of the following file organizations:v Sequential organizationv Line-sequential organizationv Relative organization with sequential accessv Indexed organization with sequential accessUse the following pattern <strong>for</strong> input:OPEN INPUT fn...READ fn INTO local-storage-item...* Process the record from the local-storage item...CL<strong>OS</strong>E fnUse the following pattern <strong>for</strong> output:OPEN OUTPUT fn...* Construct output record in local-storage itemChapter 27. Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading 497


...WRITE rec FROM local-storage-item...CL<strong>OS</strong>E fnWith other usage patterns, you must take one of the following actions:v Verify the safety of your application logic. Ensure that two instances of theprogram are never simultaneously active on different threads.v Code explicit serialization logic by using calls to P<strong>OS</strong>IX services.To avoid serialization problems when you access a file from multiple threads,define the data items that are associated with the file (such as file-status data itemsand key arguments) in the LOCAL-STORAGE SECTION.“Example: usage patterns of file input and output with multithreading”RELATED TASKS“Calling UNIX/P<strong>OS</strong>IX APIs” on page 440Example: usage patterns of file input and output withmultithreadingThe following examples show the need <strong>for</strong> explicit serialization logic when youdeviate from the recommended usage pattern <strong>for</strong> file input and output in yourmultithreaded applications. These examples also explain the unexpected behaviorthat might result if you fail to handle serialization properly.In each example, two instances of a program that contains the sample operationsare running within one run unit on two different threads.READ F1...REWRITE R1In the example above, the second thread might execute the READ statement after theREAD statement is executed on the first thread but be<strong>for</strong>e the REWRITE statement isexecuted on the first thread. The REWRITE statement might not update the recordthat you intended. To ensure the results that you want, write explicit serializationlogic.READ F1...* Process the data in the FD record description entry <strong>for</strong> F1...In the example above, the second thread might execute the READ statement whilethe first thread is still processing a record in the FD record description entry. Thesecond READ statement would overlay the record that the first thread is processing.To avoid this problem, use the recommended technique:READ F1 INTO LOCAL-STORAGE-itemOther cases: You must give similar consideration to other usage patterns thatinvolve a sequence of related input and output operations, such as START followedby READ NEXT, orREAD followed by DELETE. Take appropriate steps to ensure thecorrect processing of file input and output.498 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Handling <strong>COBOL</strong> limitations with multithreadingSome <strong>COBOL</strong> applications depend on subsystems or other applications. In amultithreaded environment, these dependencies and others result in somelimitations on <strong>COBOL</strong> programs.In general, you must synchronize access to resources that are visible to theapplication within a run unit. Exceptions to this requirement are DISPLAY andACCEPT, which you can use from multiple threads, and supported <strong>COBOL</strong> file I/Ostatements that have the recommended usage pattern; all synchronization isprovided <strong>for</strong> these by the runtime environment.CICS: You cannot run multithreaded applications in the CICS environment. In theCICS environment you can run a <strong>COBOL</strong> program that has been compiled withthe THREAD option and that is part of an application that has no multiple threads orPL/I tasks.Recursive: Because you must code the programs in a multithreaded application asrecursive, you must adhere to all the restrictions and programming considerationsthat apply to recursive programs, such as not coding nested programs.Reentrancy: You must compile your multithreading programs with the RENTcompiler option and link them with the RENT option of the binder or linkage editor.P<strong>OS</strong>IX and PL/I: If you use P<strong>OS</strong>IX threads in your multithreaded application, youmust specify the Language Environment runtime option P<strong>OS</strong>IX(ON). Iftheapplication uses PL/I tasking, you must specify P<strong>OS</strong>IX(OFF). You cannot mixP<strong>OS</strong>IX threads and PL/I tasks in the same application.PL/I tasking: To include <strong>COBOL</strong> programs in applications that contain multiplePL/I tasks, follow these guidelines:vvvvCompile all <strong>COBOL</strong> programs that you run in multiple PL/I tasks with theTHREAD option. If you compile any <strong>COBOL</strong> program with the NOTHREAD option, allof the <strong>COBOL</strong> programs must run in one PL/I task.You can call <strong>COBOL</strong> programs compiled with the THREAD option from one ormore PL/I tasks. However, calls from PL/I programs to <strong>COBOL</strong> programscannot include the TASK or EVENT option. The PL/I tasking call must first call aPL/I program or function that in turn calls the <strong>COBOL</strong> program. Thisindirection is required because you cannot specify the <strong>COBOL</strong> program directlyas the target of a PL/I CALL statement that includes the TASK or EVENT option.Be aware that issuing a STOP RUN statement from a <strong>COBOL</strong> program or a STOPstatement from a PL/I program terminates the entire Language Environmentenclave, including all the tasks of execution.Do not code explicit P<strong>OS</strong>IX threading (calls to pthread_create()) in any run unitthat includes PL/I tasking.C and Language Environment-enabled assembler: You can combine yourmultithreaded <strong>COBOL</strong> programs with C programs and LanguageEnvironment-enabled assembler programs in the same run unit when thoseprograms are also appropriately coded <strong>for</strong> multithreaded execution.AMODE: You must run your multithreaded applications with AMODE 31. You canrun a <strong>COBOL</strong> program that has been compiled with the THREAD option with AMODE24 as part of an application that does not have multiple threads or PL/I tasks.Chapter 27. Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading 499


Asynchronous signals: In a threaded application your <strong>COBOL</strong> program might beinterrupted by an asynchronous signal or interrupt. If your program contains logicthat cannot tolerate such an interrupt, you must disable the interrupts <strong>for</strong> theduration of that logic. Call a C/C++ function to set the signal mask appropriately.Older <strong>COBOL</strong> programs: To run your <strong>COBOL</strong> programs on multiple threads of amultithreaded application, you must compile them with <strong>Enterprise</strong> <strong>COBOL</strong> anduse the THREAD option. If you run programs that have been compiled with oldercompilers, you must follow these restrictions:vvRun applications that contain <strong>OS</strong>/VS <strong>COBOL</strong> programs only on the initialthread (IPT).Run applications that contain programs compiled by other older compilers onlyon one thread, although it can be a thread other than the initial thread.IGZBRDGE, IGZETUN, and IGZEOPT: Do not use IGZBRDGE, the macro <strong>for</strong>converting static calls to dynamic calls, with programs that have been compiledwith the THREAD option; this macro is not supported. Do not use the modulesIGZETUN (<strong>for</strong> storage tuning) or IGZEOPT (<strong>for</strong> runtime options) <strong>for</strong> applicationsin which the main program has been compiled with the THREAD option; theseCSECTs are ignored.UPSI switches: All programs and all threads in an application share a single copyof UPSI switches. If you modify switches in a threaded application, you must codeappropriate serialization logic.RELATED TASKS“Making recursive calls” on page 461“Serializing file access with multithreading” on page 497XL C/C++ <strong>Programming</strong> <strong>Guide</strong> (Using threads in z/<strong>OS</strong> UNIX System Servicesapplications)Language Environment Writing ILC Communication Applications500 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 5. Using XML and <strong>COBOL</strong> together||||||Chapter 28. Processing XML input . . . . . 503XML parser in <strong>COBOL</strong> . . . . . . . . . . 504Accessing XML documents . . . . . . . . . 506Parsing XML documents . . . . . . . . . 506Writing procedures to process XML . . . . . 508XML events . . . . . . . . . . . . . 510XML-CODE . . . . . . . . . . . . 511XML-TEXT and XML-NTEXT . . . . . . 512XML-NAMESPACE andXML-NNAMESPACE. . . . . . . . . 513XML-NAMESPACE-PREFIX andXML-NNAMESPACE-PREFIX . . . . . . 514Trans<strong>for</strong>ming XML text to <strong>COBOL</strong> data items 514Parsing XML documents with validation . . . 515XML schemas . . . . . . . . . . . 517Parsing XML documents one segment at a time 518The encoding of XML documents. . . . . . . 520XML input document encoding . . . . . . 521Determining the encoding of an input XMLdocument . . . . . . . . . . . . 522Specifying the encoding . . . . . . . . 523EBCDIC code-page-sensitive characters inXML markup . . . . . . . . . . . 524Parsing XML documents encoded in UTF-8 . . 525Handling XML PARSE exceptions . . . . . . 526How the XML parser handles errors. . . . . 528Handling encoding conflicts . . . . . . . 529Terminating XML parsing . . . . . . . . . 530XML PARSE examples . . . . . . . . . . 531Example: parsing a simple document . . . . 531Example: program <strong>for</strong> processing XML . . . . 532Output from parsing with XMLPARSE(XMLSS) 534Output from parsing with XMLPARSE(COMPAT) 534Example: parsing an XML document that usesnamespaces . . . . . . . . . . . . . 535Sample XML document . . . . . . . . 536Results from parsing . . . . . . . . . 536Example: parsing an XML document onesegment at a time . . . . . . . . . . . 537Content of infile . . . . . . . . . . 537Program PARSESEG . . . . . . . . . 537Results from parsing . . . . . . . . . 539Example: parsing XML documents withvalidation . . . . . . . . . . . . . 539Program ValidCk . . . . . . . . . . 540Output from program ValidCk . . . . . 541Chapter 29. Producing XML output . . . . . 543Generating XML output . . . . . . . . . . 543Controlling the encoding of generated XML output 547Handling XML GENERATE exceptions . . . . . 548Example: generating XML . . . . . . . . . 549Program XGFX . . . . . . . . . . . . 549Program Pretty . . . . . . . . . . . . 550Output from program XGFX . . . . . . . 553Enhancing XML output . . . . . . . . . . 553Example: enhancing XML output . . . . . . 554Example: converting hyphens in element orattribute names to underscores . . . . . . 557© Copyright IBM Corp. 1991, 2009 501


502 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 28. Processing XML inputYou can process XML input in a <strong>COBOL</strong> program by using the XML PARSEstatement.|The XML PARSE statement is the <strong>COBOL</strong> language interface to either of twohigh-speed XML parsers. You use the XMLPARSE compiler option to select theappropriate parser <strong>for</strong> your application:v XMLPARSE(XMLSS) selects the z/<strong>OS</strong> XML System Services parser.This option provides enhanced features such as namespace processing,validation of XML documents with respect to an XML schema, and conversionof text fragments to national character representation (Unicode UTF-16).v XMLPARSE(COMPAT) selects the XML parser that is built into the <strong>COBOL</strong> library.This option provides compatibility with XML parsing in <strong>Enterprise</strong> <strong>COBOL</strong>Version 3.Processing XML input involves passing control between the XML parser and aprocessing procedure in which you handle parser events.||||||Use the following <strong>COBOL</strong> facilities to process XML input:v The XML PARSE statement to begin XML parsing and to identify the source XMLdocument and the processing procedure.You can also use the following optional phrases of the XML PARSE statement:– ENCODING to specify the encoding of the XML document– VALIDATING to identify an XML schema against which the XML document is tobe validatedv The processing procedure to control the parsing, that is, receive and processXML events and associated document fragments, and return to the parser <strong>for</strong>continued processingv Special registers to exchange in<strong>for</strong>mation between the parser and the processingprocedure:– XML-CODE to receive the status of XML parsing and, in some cases, to returnin<strong>for</strong>mation to the parser– XML-EVENT to receive the name of each XML event from the parser– XML-NTEXT to receive XML document fragments that are returned as nationalcharacter data– XML-TEXT to receive document fragments that are returned as alphanumericdata– XML-NAMESPACE or XML-NNAMESPACE to receive a namespace identifier <strong>for</strong> aNAMESPACE-DECLARATION XML event, or <strong>for</strong> an element name or attribute namethat is in a namespace– XML-NAMESPACE-PREFIX or XML-NNAMESPACE-PREFIX to receive a namespaceprefix <strong>for</strong> a NAMESPACE-DECLARATION XML event, or <strong>for</strong> an element name orattribute name that is prefixedv The optional RETURNING NATIONAL phrase of the XML PARSE statement to indicatethat the fragments of an XML document in an alphanumeric data item are to beconverted to UTF-16 and returned to the processing procedure in the nationalspecial registers XML-NTEXT, XML-NNAMESPACE, and XML-NNAMESPACE-PREFIX© Copyright IBM Corp. 1991, 2009 503


|You can use the ENCODING, VALIDATING, and RETURNING NATIONAL phrases of the XMLPARSE statement only if XMLPARSE(XMLSS) is in effect.Link-edit consideration: <strong>COBOL</strong> programs that contain the XML PARSE statementmust be link-edited with AMODE 31.RELATED CONCEPTS“XML parser in <strong>COBOL</strong>”RELATED TASKS“Accessing XML documents” on page 506“Parsing XML documents” on page 506“Handling XML PARSE exceptions” on page 526“Terminating XML parsing” on page 530XML parser in <strong>COBOL</strong>RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“The encoding of XML documents” on page 520Appendix D, “XML reference material,” on page 709Extensible Markup Language (XML)<strong>Enterprise</strong> <strong>COBOL</strong> provides an event-based interface that lets you parse XMLdocuments and trans<strong>for</strong>m them to <strong>COBOL</strong> data structures.The XML parser finds fragments within the source XML document, and yourprocessing procedure acts on those fragments. The fragments are associated withXML events; you code the processing procedure to handle each XML event.Execution of the XML PARSE statement begins the parsing and establishes theprocessing procedure with the parser. The parser transfers control to the processingprocedure <strong>for</strong> each XML event that it detects while processing the document. Afterprocessing the event, the processing procedure automatically returns control to theparser. Each normal return from the processing procedure causes the parser tocontinue analyzing the XML document to report the next event. Throughout thisoperation, control passes back and <strong>for</strong>th between the parser and the processingprocedure.In the XML PARSE statement, you can also specify two imperative statements towhich you want control to be passed at the end of the parsing: one if a normal endoccurs, and the other if an exception condition exists.The following figure shows a high-level overview of the basic exchange of controlbetween the parser and your <strong>COBOL</strong> program:504 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Normally, parsing continues until the entire XML document has been parsed.The XML parser checks XML documents <strong>for</strong> most aspects of well <strong>for</strong>medness. Adocument is well <strong>for</strong>med if it adheres to the XML syntax in the XML specificationand follows some additional rules such as proper use of end tags and uniquenessof attribute names.||||||When you parse an XML document with validation against an XML schema, thez/<strong>OS</strong> XML System Services parser additionally verifies that the XML documentadheres to the content and structure prescribed in the schema. For example, theparser checks that there are no unexpected elements or attributes, that no requiredelements or attributes are missing, and that any values of elements or attributes arelegal.RELATED CONCEPTS“XML schemas” on page 517“XML input document encoding” on page 521RELATED TASKS“Parsing XML documents” on page 506“Parsing XML documents with validation” on page 515“Handling XML PARSE exceptions” on page 526“Terminating XML parsing” on page 530RELATED REFERENCES“The encoding of XML documents” on page 520XML specificationChapter 28. Processing XML input 505


Accessing XML documentsBe<strong>for</strong>e you can parse an XML document using an XML PARSE statement, you mustmake the document available to your program. Common methods of acquiring anXML document are by retrieval from a WebSphere MQ message, a CICS transientqueue or communication area, or an IMS message processing queue; or by readingthe document from a file.If the XML document that you want to parse is held in a file, use ordinary <strong>COBOL</strong>facilities to place the document into a data item in your program:v A FILE-CONTROL entry to define the file to your program.v An OPEN statement to open the file.vvREAD statements to read all the records from the file into a data item (either anelementary item of category alphanumeric or national, or an alphanumeric ornational group). You can define the data item in the WORKING-STORAGE SECTION orthe LOCAL-STORAGE SECTION.Optionally, the STRING statement to string all of the separate records togetherinto one continuous stream, to remove extraneous blanks, and to handlevariable-length records.If the XMLPARSE(XMLSS) option is in effect, you can parse an XML document that isin a file by passing the parser one record (or segment) of text from the file at atime. This capability is useful <strong>for</strong> parsing very large XML documents.RELATED TASKS“Coding <strong>COBOL</strong> programs to run under CICS” on page 407Chapter 22, “Developing <strong>COBOL</strong> programs <strong>for</strong> IMS,” on page 431“Parsing XML documents one segment at a time” on page 518Parsing XML documentsRELATED REFERENCES“XMLPARSE” on page 357 (compiler option)To parse XML documents, use the XML PARSE statement, specifying the XMLdocument that is to be parsed and the processing procedure <strong>for</strong> handling XMLevents that occur during parsing, as shown in the following code fragment.XML PARSE xml-documentPROCESSING PROCEDURE xml-event-handlerON EXCEPTIONDISPLAY 'XML document error ' XML-CODESTOP RUNNOT ON EXCEPTIONDISPLAY 'XML document was successfully parsed.'END-XMLIn the XML PARSE statement, you first identify the parse data item (xml-document inthe example above) that contains the XML document character stream. In the DATADIVISION, define the parse data item as an elementary data item of categorynational or as a national group item if the encoding of the document is UnicodeUTF-16; otherwise, define the parse data item as an elementary alphanumeric dataitem or an alphanumeric group item:vIf the parse data item is national, the XML document must be encoded inUTF-16, CCSID 1200.506 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vIf the parse data item is alphanumeric, its content must be encoded in one of thesupported code pages described in the related reference about the encoding ofXML documents.Next, specify the name of the processing procedure (xml-event-handler in theexample above) that is to handle the XML events that occur during parsing of thedocument.||If the XMLPARSE(XMLSS) compiler option is in effect, you can also use any of theseoptional phrases of the XML PARSE statement:v ENCODING, to specify the CCSID of the documentvvRETURNING NATIONAL, to cause the parser to automatically convert UTF-8 orsingle-byte characters to national characters <strong>for</strong> return to the processingprocedureVALIDATING, to cause the parser to validate the document against an XMLschemaIn addition, you can specify either or both of the following optional phrases (asshown in the fragment above) to indicate the action to be taken after parsingfinishes:vvON EXCEPTION, to receive control if an unhandled exception occurs duringparsingNOT ON EXCEPTION, to receive control otherwiseYou can end the XML PARSE statement with the explicit scope terminator END-XML.Use END-XML to nest an XML PARSE statement that uses the ON EXCEPTION or NOT ONEXCEPTION phrase in a conditional statement.The parser passes control to the processing procedure <strong>for</strong> each XML event. Controlreturns to the parser at the end of the processing procedure. This exchange ofcontrol between the XML parser and the processing procedure continues until oneof the following events occurs:vvvvThe entire XML document has been parsed, as indicated by the END-OF-DOCUMENTevent.If XMLPARSE(XMLSS) is in effect, either:– The parser detects an error in the document and signals an EXCEPTION event(regardless of the kind of exception).– The parser signals an END-OF-INPUT event, and the processing procedurereturns to the parser with special register XML-CODE still set to zero, whichindicates that no further XML data will be provided to the parser.If XMLPARSE(COMPAT) is in effect, either:– The parser signals an encoding conflict EXCEPTION event, and the processingprocedure does not reset special register XML-CODE to zero or to the correctCCSID be<strong>for</strong>e returning to the parser.– The parser detects an error in the document and signals an EXCEPTION event(other than an encoding conflict), and the processing procedure does not resetspecial register XML-CODE to zero be<strong>for</strong>e returning to the parser.You terminate the parsing process deliberately by setting the XML-CODE specialregister to -1 be<strong>for</strong>e returning to the parser.Chapter 28. Processing XML input 507


RELATED CONCEPTS“XML events” on page 510“XML-CODE” on page 511“XML schemas” on page 517RELATED TASKS“Writing procedures to process XML”“Parsing XML documents with validation” on page 515“Parsing XML documents one segment at a time” on page 518“Parsing XML documents encoded in UTF-8” on page 525RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“The encoding of XML documents” on page 520“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709“XML PARSE exceptions with XMLPARSE(COMPAT) in effect” on page 711XML PARSE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Writing procedures to process XMLIn your processing procedure, code statements to handle XML events.For each event that the parser encounters, the parser passes in<strong>for</strong>mation to theprocessing procedure in several special registers. Use the content of those specialregisters to populate <strong>COBOL</strong> data structures and to control the processing.|Examine the XML-EVENT special register to determine which event the parser passedto the processing procedure. XML-EVENT contains an event name, such as’START-OF-ELEMENT’. Obtain the text associated with the event from the XML-TEXT orXML-NTEXT special register.If the XMLPARSE(XMLSS) option is in effect, you can use special registerXML-NAMESPACE or XML-NNAMESPACE to determine the namespace identifier, if any,that is associated with the XML event, and examine the XML-NAMESPACE-PREFIX orXML-NNAMESPACE-PREFIX special register to determine the associated prefix, if any.When used in nested programs, the XML special registers are implicitly defined asGLOBAL in the outermost program.For additional details about the XML special registers, see the following table.Table 68. Special registers used by the XML parserSpecial register Implicit definition and usage ContentXML-EVENT 1 PICTURE X(30) USAGE DISPLAY VALUE SPACE The name of the XML eventXML-CODE 2 PICTURE S9(9) USAGE BINARY VALUE ZERO An exception code or zero <strong>for</strong> each XML eventXML-TEXT 1Variable-length elementary categoryalphanumeric itemText (corresponding to the event that the parserencountered) from the XML document if you specifyan alphanumeric item <strong>for</strong> the XML PARSE identifier 3XML-NTEXT 1XML-NAMESPACE 1, 4Variable-length elementary category nationalitemVariable-length elementary categoryalphanumeric itemText (corresponding to the event that the parserencountered) from the XML document if you specify anational item <strong>for</strong> the XML PARSE identifier 3The namespace identifier <strong>for</strong> a NAMESPACE-DECLARATIONXML event or <strong>for</strong> an element or attribute name that isin a namespace, if the XML document is in analphanumeric data item 3508 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 68. Special registers used by the XML parser (continued)Special register Implicit definition and usage ContentXML-NNAMESPACE 1, 4Variable-length elementary category nationalitemThe namespace identifier <strong>for</strong> a NAMESPACE-DECLARATIONXML event or <strong>for</strong> an element or attribute name that isin a namespace, if the XML document is in a nationaldata item or the RETURNING NATIONAL phrase isspecified in the XML PARSE statementXML-NAMESPACE-PREFIX 1, 4XML-NNAMESPACE-PREFIX 1, 4Variable-length elementary category nationalitemVariable-length elementary category nationalitemThe prefix, if any, <strong>for</strong> a NAMESPACE-DECLARATION XMLevent or <strong>for</strong> an element or attribute name that is in anondefault namespace, if the XML document is in analphanumeric data item 3The prefix, if any, <strong>for</strong> a NAMESPACE-DECLARATION XMLevent or <strong>for</strong> an element or attribute name that is in anondefault namespace, if the XML document is in anational data item or the RETURNING NATIONAL phrase isspecified in the XML PARSE statement1. You cannot use this special register as a receiving data item.2. The XML GENERATE statement also uses XML-CODE. There<strong>for</strong>e, if you have an XML GENERATE statement in the processing procedure,save the value of XML-CODE be<strong>for</strong>e the XML GENERATE statement, and restore the saved value after the XML GENERATE statement.3. If you specify the RETURNING NATIONAL phrase in the XML PARSE statement <strong>for</strong> an alphanumeric data item, text is returned in thecorresponding national special register. You can specify the RETURNING NATIONAL phrase only if the XMLPARSE(XMLSS) optionisineffect.4. The parser sets the namespace special registers only if the XMLPARSE(XMLSS) option is in effect.Restrictions:v A processing procedure must not directly execute an XML PARSE statement.However, if a processing procedure passes control to a method or outermostprogram by using an INVOKE or CALL statement, the target method or programcan execute the same or a different XML PARSE statement. You can also executethe same XML statement or different XML statements simultaneously from aprogram that is running on multiple threads.v The range of the processing procedure must not cause the execution of anyGOBACK or EXIT PROGRAM statement, except to return control from a method orprogram to which control was passed by an INVOKE or CALL statement,respectively, that is executed in the range of the processing procedure.You can code a STOP RUN statement in a processing procedure to end the rununit.The compiler inserts a return mechanism after the last statement in each processingprocedure.“Example: program <strong>for</strong> processing XML” on page 532RELATED CONCEPTS“XML events” on page 510“XML-CODE” on page 511“XML-TEXT and XML-NTEXT” on page 512“XML-NAMESPACE and XML-NNAMESPACE” on page 513“XML-NAMESPACE-PREFIX and XML-NNAMESPACE-PREFIX” on page 514RELATED TASKS“Parsing XML documents one segment at a time” on page 518“Parsing XML documents with validation” on page 515“Terminating XML parsing” on page 530Chapter 28. Processing XML input 509


RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)XML-EVENT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)||||XML eventsAn XML event results when the XML parser detects various conditions (such asEND-OF-INPUT or EXCEPTION) or encounters document fragments (such asCONTENT-CHARACTERS or START-OF-CDATA-SECTION) while processing an XMLdocument.For each event that occurs during XML parsing, the parser sets the associatedevent name in the XML-EVENT special register, and passes the XML-EVENT specialregister to the processing procedure. Depending on the event, the parser sets otherspecial registers to contain additional in<strong>for</strong>mation about the event.In most cases, the parser sets the XML-TEXT or XML-NTEXT special register to the XMLfragment that caused the event:vvIf the XMLPARSE(COMPAT) compiler option is in effect, the parser sets XML-NTEXT ifthe XML document is in a national data item, or if the parser finds a characterreference; otherwise, the parser sets XML-TEXT.If XMLPARSE(XMLSS) is in effect, the parser sets XML-NTEXT if the RETURNINGNATIONAL phrase is specified in the XML PARSE statement, or if the XML documentis in a national data item; otherwise, the parser sets XML-TEXT.If XMLPARSE(XMLSS) is in effect, the parser sets the namespace special registers <strong>for</strong> aNAMESPACE-DECLARATION event, or if it encounters a name that is in a namespace.|||||When the parser detects an encoding conflict or a well-<strong>for</strong>medness or validationerror in the document, it sets XML-EVENT to 'EXCEPTION' and provides additionalin<strong>for</strong>mation about the exception in the XML-CODE special register. (You can parsewith validation only if XMLPARSE(XMLSS) is in effect. For further details, see therelated task about parsing with validation.)For a detailed description of the set of XML events, see the related reference aboutXML-EVENT.“Example: parsing a simple document” on page 531RELATED CONCEPTS“XML parser in <strong>COBOL</strong>” on page 504“XML-CODE” on page 511“XML-TEXT and XML-NTEXT” on page 512“XML-NAMESPACE and XML-NNAMESPACE” on page 513“XML-NAMESPACE-PREFIX and XML-NNAMESPACE-PREFIX” on page 514RELATED TASKS“Writing procedures to process XML” on page 508“Parsing XML documents with validation” on page 515RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709“XML PARSE exceptions with XMLPARSE(COMPAT) in effect” on page 711XML-EVENT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)510 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||XML-CODEFor each XML event except an EXCEPTION event, the parser sets the value of theXML-CODE special register to zero. For an EXCEPTION event, the parser sets XML-CODEto a value that identifies the specific exception.For in<strong>for</strong>mation about the possible exception codes, see the related references.||||||||||||||||||||||||||||||||||||When the parser returns control to the XML PARSE statement from your processingprocedure, XML-CODE generally contains the most recent value that was set by theparser. However, <strong>for</strong> any event other than EXCEPTION, if you set XML-CODE to -1 inyour processing procedure, parsing terminates with a user-initiated exceptioncondition when control returns to the parser, and XML-CODE retains the value -1.For an EXCEPTION XML event when XMLPARSE(COMPAT) is in effect, your processingprocedure can, in some cases, set XML-CODE to a meaningful value be<strong>for</strong>e controlreturns to the parser. (For details, see the related tasks about handling XML PARSEexceptions and handling encoding conflicts.) If you set XML-CODE to any othernonzero value or set it <strong>for</strong> any other exception, the parser resets XML-CODE to theoriginal exception code.The following tables show the results of setting XML-CODE to various values. Theleftmost column in each table shows the type of XML event passed to theprocessing procedure; the other column headings show the XML-CODE value set bythe processing procedure. The cell at the intersection of each row and columnshows the action that the parser takes upon return from the processing procedure<strong>for</strong> a given combination of XML event and XML-CODE value.Table 69. Result of processing-procedure changes to XML-CODE with XMLPARSE(XMLSS) in effectXML event type -1 0 1 Other nonzero valueEXCEPTIONIgnores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueEND-OF-INPUTEnds immediately;XML-CODE =-1 1Normal event Ends immediately;XML-CODE =-1 1For more in<strong>for</strong>mation:Next event isEND-OF-DOCUMENT 2[No apparent changeto XML-CODE]1. See the related task about terminating XML parsing.2. See the related task about parsing documents one segment at a time.Next event dependson input 2Fatal runtime error(message 230S)Fatal runtime error(message 230S)Fatal runtime error(message 230S)Table 70. Result of processing-procedure changes to XML-CODE with XMLPARSE(COMPAT) in effectXML event type -1 0 XML-CODE-100,000 Other nonzero valueEncoding-conflictexception (exceptioncodes 50 - 99)Encoding-choiceexception (exceptioncodes > 100,000)Other exceptionIgnores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueChooses encodingdepending on thespecific exceptioncode 1Parses using theCODEPAGE value 2Limited continuationonly <strong>for</strong> exceptioncodes 1-49 3Ignores setting; keepsoriginal XML-CODEvalueParses using thedifference (shownabove) as theencoding value 2Ignores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueIgnores setting; keepsoriginal XML-CODEvalueChapter 28. Processing XML input 511


||||||||||||Table 70. Result of processing-procedure changes to XML-CODE with XMLPARSE(COMPAT) in effect (continued)XML event type -1 0 XML-CODE-100,000 Other nonzero valueNormal event Ends immediately;XML-CODE =-1 4[No apparent changeto XML-CODE]Ends immediately;XML-CODE =-1Ends immediately;XML-CODE =-1For more in<strong>for</strong>mation:1. See the exception codes in the related reference about XML PARSE exceptions with XMLPARSE(COMPAT) in effect.2. See the related task about handling encoding conflicts.3. See the related task about handling XML PARSE exceptions.4. See the related task about terminating XML parsing.XML generation also uses the XML-CODE special register. For details, see the relatedtask about handling XML GENERATE exceptions.RELATED CONCEPTS“How the XML parser handles errors” on page 528RELATED TASKS“Writing procedures to process XML” on page 508“Parsing XML documents one segment at a time” on page 518“Handling XML PARSE exceptions” on page 526“Handling encoding conflicts” on page 529“Terminating XML parsing” on page 530“Handling XML GENERATE exceptions” on page 548RELATED REFERENCES“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709“XML PARSE exceptions with XMLPARSE(COMPAT) in effect” on page 711“XML GENERATE exceptions” on page 718XML-CODE (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)XML-EVENT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)XML-TEXT and XML-NTEXTFor most XML events, the parser sets XML-TEXT or XML-NTEXT to an associateddocument fragment.|Typically, the parser sets XML-TEXT if the XML document is in an alphanumeric dataitem. The parser sets XML-NTEXT if:v The XML document is in a national data item.vvThe XMLPARSE(XMLSS) option is in effect and the RETURNING NATIONAL phrase isspecified in the XML PARSE statement.The ATTRIBUTE-NATIONAL-CHARACTER or CONTENT-NATIONAL-CHARACTER eventoccurs.The special registers XML-TEXT and XML-NTEXT are mutually exclusive. When theparser sets XML-TEXT, XML-NTEXT is empty with length zero. When the parser setsXML-NTEXT, XML-TEXT is empty with length zero.|||To determine the number of character encoding units in XML-NTEXT, use the LENGTHintrinsic function; <strong>for</strong> example FUNCTION LENGTH(XML-NTEXT). To determine thenumber of bytes in XML-NTEXT, use special register LENGTH OF XML-NTEXT. Thenumber of character encoding units differs from the number of bytes.512 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


To determine the number of bytes in XML-TEXT, use either special register LENGTH OFXML-TEXT or the LENGTH intrinsic function; each returns the number of bytes.||The XML-TEXT and XML-NTEXT special registers are undefined outside the processingprocedure.RELATED CONCEPTS“XML events” on page 510“XML-CODE” on page 511RELATED TASKS“Writing procedures to process XML” on page 508RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)XML-TEXT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)XML-NTEXT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)XML-NAMESPACE and XML-NNAMESPACEIf the XMLPARSE(XMLSS) option is in effect, the XML parser sets the XML-NAMESPACEor XML-NNAMESPACE special register to the namespace identifier <strong>for</strong> aNAMESPACE-DECLARATION XML event, or if it encounters an element name orattribute name that is in a namespace.The parser sets XML-NNAMESPACE if the XML document is in a national data item, orif the RETURNING NATIONAL phrase is specified in the XML PARSE statement.Otherwise, the parser sets XML-NAMESPACE.The special registers XML-NAMESPACE and XML-NNAMESPACE are mutually exclusive: Ifthe parser sets XML-NAMESPACE, XML-NNAMESPACE is empty with length zero. If theparser sets XML-NNAMESPACE, XML-NAMESPACE is empty with length zero.|||To determine the number of character encoding units in XML-NNAMESPACE, use theLENGTH intrinsic function; <strong>for</strong> example: FUNCTION LENGTH(XML-NNAMESPACE). Todetermine the number of bytes in XML-NNAMESPACE, use special register LENGTH OFXML-NNAMESPACE. The number of character encoding units differs from the numberof bytes.To determine the number of bytes in XML-NAMESPACE, use either special registerLENGTH OF XML-NAMESPACE or the LENGTH intrinsic function; each returns the numberof bytes.The XML namespace special registers are undefined outside the processingprocedure.RELATED CONCEPTS“XML events” on page 510“XML-CODE” on page 511“XML-NAMESPACE-PREFIX and XML-NNAMESPACE-PREFIX” on page 514“XML-TEXT and XML-NTEXT” on page 512RELATED TASKS“Writing procedures to process XML” on page 508RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)Chapter 28. Processing XML input 513


XML-NAMESPACE-PREFIX and XML-NNAMESPACE-PREFIXIf the XMLPARSE(XMLSS) option is in effect, the XML parser sets theXML-NAMESPACE-PREFIX special register or the XML-NNAMESPACE-PREFIX specialregister <strong>for</strong> a NAMESPACE-DECLARATION XML event that also defines a namespaceprefix, or if an element name or attribute name in a namespace is prefixed.The parser sets XML-NNAMESPACE-PREFIX if the XML document is in a national dataitem, or the RETURNING NATIONAL phrase is specified in the XML PARSE statement.Otherwise, the parser sets XML-NAMESPACE-PREFIX.The special registers XML-NAMESPACE-PREFIX and XML-NNAMESPACE-PREFIX aremutually exclusive: If the parser sets XML-NAMESPACE-PREFIX, XML-NNAMESPACE-PREFIX is empty with length zero. If the parser sets XML-NNAMESPACE-PREFIX,XML-NAMESPACE-PREFIX is empty with length zero.|||||To determine the number of character encoding units in XML-NNAMESPACE-PREFIX,use the LENGTH intrinsic function; <strong>for</strong> example: FUNCTION LENGTH(XML-NNAMESPACE-PREFIX). To determine the number of bytes in XML-NNAMESPACE-PREFIX, use specialregister LENGTH OF XML-NNAMESPACE-PREFIX. The number of character encodingunits differs from the number of bytes.To determine the number of bytes in XML-NAMESPACE-PREFIX, use either specialregister LENGTH OF XML-NAMESPACE-PREFIX or the LENGTH intrinsic function; eachreturns the number of bytes.The XML namespace-prefix special registers are undefined outside the processingprocedure.RELATED CONCEPTS“XML events” on page 510“XML-NAMESPACE and XML-NNAMESPACE” on page 513RELATED TASKS“Writing procedures to process XML” on page 508RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)Trans<strong>for</strong>ming XML text to <strong>COBOL</strong> data itemsBecause XML data is neither fixed length nor fixed <strong>for</strong>mat, you need to use specialtechniques when you move XML data to a <strong>COBOL</strong> data item.For alphanumeric items, decide whether the XML data should go at the left(default) end, or at the right end, of the <strong>COBOL</strong> data item. If the data should go atthe right end, specify the JUSTIFIED RIGHT clause in the declaration of the item.Give special consideration to numeric XML values, particularly “decorated”monetary values such as ’$1,234.00’ or ’$1234’. These two strings might mean thesame thing in XML, but need quite different declarations if used as <strong>COBOL</strong>sending fields.Use one of the following techniques when you move XML data to <strong>COBOL</strong> dataitems:514 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvIf the <strong>for</strong>mat is reasonably regular, code a MOVE to an alphanumeric item that youredefine appropriately as a numeric-edited item. Then do the final move to anumeric (operational) item by moving from, and thus de-editing, thenumeric-edited item. (A regular <strong>for</strong>mat would have the same number of digitsafter the decimal point, a comma separator <strong>for</strong> values greater than 999, and soon.)For simplicity and vastly increased flexibility, use the following intrinsicfunctions <strong>for</strong> alphanumeric XML data:– NUMVAL to extract and decode simple numeric values from XML data thatrepresents plain numbers– NUMVAL-C to extract and decode numeric values from XML data that representsmonetary quantitiesHowever, using these functions is at the expense of per<strong>for</strong>mance.RELATED TASKS“Converting to numbers (NUMVAL, NUMVAL-C)” on page 113“Using national data (Unicode) in <strong>COBOL</strong>” on page 126“Writing procedures to process XML” on page 508||||||||||||||||||||||||||||Parsing XML documents with validationValidating an XML document determines whether the structure and content of thedocument con<strong>for</strong>m to a set of rules. In <strong>Enterprise</strong> <strong>COBOL</strong>, the rules are expressedin an XML schema, which is essentially a blueprint <strong>for</strong> a class of documents.To validate XML documents while parsing, use the VALIDATING phrase of the XMLPARSE statement. To do so, you must compile your program using theXMLPARSE(XMLSS) compiler option.You can validate XML documents only against an XML schema.In <strong>Enterprise</strong> <strong>COBOL</strong>, a schema used <strong>for</strong> XML validation must be in apreprocessed <strong>for</strong>mat known as Optimized Schema Representation, or<strong>OS</strong>R. Togenerate a schema in <strong>OS</strong>R <strong>for</strong>mat from a text-<strong>for</strong>m schema, use the z/<strong>OS</strong> UNIXcommand xsdosrg, which invokes the <strong>OS</strong>R generator provided by z/<strong>OS</strong> SystemServices. (Alternatively, you can call the <strong>OS</strong>R generator programmatically. Fordetails, see the related reference about z/<strong>OS</strong> XML System Services.)For example, to convert the text-<strong>for</strong>m schema in file item.xsd to a schema inpreprocessed <strong>for</strong>mat in file item.osr, you can use the following z/<strong>OS</strong> UNIXcommand:xsdosrg -v -o /u/HLQ/xml/item.osr /u/HLQ/xml/item.xsdUse one of two <strong>for</strong>ms of the VALIDATING phrase, depending on the location of thepreprocessed schema:vvIn one <strong>for</strong>m, you use the FILE keyword and specify an XML schema name. Inthis case, the schema must be in an MVS data set or a z/<strong>OS</strong> UNIX file.In the other <strong>for</strong>m, you specify the identifier of a data item that contains theschema.If you use the FILE keyword and specify an XML schema name, the <strong>COBOL</strong>runtime library automatically retrieves the schema during execution of the XMLPARSE statement. The following code fragment shows this method of specifyingvalidation:Chapter 28. Processing XML input 515


||||||||||||||||||||||||||||||||||||||||||||||||XML PARSE document-itemVALIDATING WITH FILE schema-namePROCESSING PROCEDURE xml-event-handlerON EXCEPTIONDISPLAY 'Document has an error.'GOBACKNOT ON EXCEPTIONDISPLAY 'Document is valid.'END-XMLTo associate an XML schema name with the external file that contains the schema,code the XML-SCHEMA clause in the SPECIAL-NAMES paragraph, specifying either aliteral or a user-defined word to identify the file.For example, you can associate the XML schema name schema-name shown in thefragment above with the ddname DDSCHEMA by coding the ddname as a literal inthe XML-SCHEMA clause as follows:ENVIRONMENT DIVISION.CONFIGURATION SECTION.SPECIAL-NAMES.XML-SCHEMA schema-name IS 'DDSCHEMA'.For running the program, you can associate ddname DDSCHEMA with the z/<strong>OS</strong>UNIX file item.osr by coding a DD statement as follows://GO.DDSCHEMA DD PATH='/u/HLQ/xml/item.osr'Or you can use an analogous TSO ALLOCATE command.Alternatively, DDSCHEMA in the example above could be the name of an environmentvariable that identifies the external file by means of a DSN option that specifies anMVS data set or a PATH option that specifies a z/<strong>OS</strong> UNIX file.If your schema is in an MVS data set, the data set can be any sequential data set(<strong>for</strong> example, QSAM fixed blocked or variable blocked, or VSAM ESDS).For further details about how to associate an XML schema name with the externalfile that contains the schema, see the related reference about the XML-SCHEMA clause.Restriction: XML validation using the FILE keyword is not supported under CICS.The automatic retrieval that occurs when you use the FILE keyword is convenient.But if you have several XML documents of the same type to validate, reading theschema into memory once and then reusing the schema <strong>for</strong> each of the documentsprovides better per<strong>for</strong>mance than automatic retrieval. In this case, you use theother <strong>for</strong>m of the VALIDATING phrase, in which you specify an identifier thatreferences an alphanumeric data item that contains the XML schema. For example:XML PARSE document-itemVALIDATING WITH xmlschemaPROCESSING PROCEDURE xml-event-handlerON EXCEPTIONDISPLAY 'Document has an error.'GOBACKNOT ON EXCEPTIONDISPLAY 'Document is valid.'END-XMLRead the preprocessed schema into the data item, <strong>for</strong> example by using normal<strong>COBOL</strong> statements.516 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||||||||||||||||||||||||||||||||||||||||||||||For more in<strong>for</strong>mation about this <strong>for</strong>m of the VALIDATING phrase, see the relatedreference about the XML PARSE statement.During parsing with validation, normal XML events are returned until anexception occurs due to a validation error or well-<strong>for</strong>medness error. If an XMLdocument is not valid, the parser signals an XML exception and passes control tothe processing procedure with special register XML-EVENT containing ’EXCEPTION’and special register XML-CODE containing return code 24 in the high-order halfwordand a specific validation reason code in the low-order halfword.For in<strong>for</strong>mation about the return code and reason code <strong>for</strong> exceptions that mightoccur when parsing XML documents with validation, see the related referenceabout exceptions with XMLPARSE(XMLSS) in effect.“Example: parsing XML documents with validation” on page 539RELATED CONCEPTS“XML-CODE” on page 511“XML schemas”RELATED TASKS“Handling XML PARSE exceptions” on page 526RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709XML PARSE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)XML-SCHEMA clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and ReferenceXML schemasAn XML schema is a mechanism, defined by the W3C, <strong>for</strong> describing andconstraining the structure and content of XML documents. An XML schema, whichis itself expressed in XML, effectively defines a class of XML documents of a giventype, <strong>for</strong> example, purchase orders.For <strong>Enterprise</strong> <strong>COBOL</strong>, XML schemas used <strong>for</strong> validating XML documents must bein a preprocessed <strong>for</strong>mat known as Optimized Schema Representation (<strong>OS</strong>R). Forin<strong>for</strong>mation about this <strong>for</strong>mat, see the related reference about z/<strong>OS</strong> XML SystemServices.Consider an XML document that describes an item <strong>for</strong> stock-keeping purposes:Stainless steel rope thimbles23The example document above is both well <strong>for</strong>med and valid according to thefollowing schema. (The numbers that precede each line are not part of the schema,but are used in the explanations after the schema.)1. 2.3. 4.5. 6. 7. Chapter 28. Processing XML input 517


||||||||||||||||||||||||||||||||||||||8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.19. 20. 21. 22. 23. 24.25. The schema declares (line 3) that the root element is stockItem, which has amandatory itemNumber attribute (line 16) of type SKU, and includes a sequence(lines 6 - 15) of other elements:v An optional itemName element of type string (line 7)vA required quantityOnHand element that has a constrained range of 1-99basedon the type nonNegativeInteger (lines 8-14)Type declarations can be inline and unnamed, as in lines 9 - 13, which include themaxExclusive facet to specify the legal values <strong>for</strong> the quantityOnHand element.For the itemNumber attribute, by contrast, the named type SKU is declared separatelyin lines 19 - 23, which include a pattern facet that uses regular expression syntax tospecify that the legal values <strong>for</strong> that type consist of (in order): 3 digits, ahyphen-minus, then two uppercase letters.The example referenced below shows a program that parses documents againstthis schema.“Example: parsing XML documents with validation” on page 539RELATED TASKS“Parsing XML documents with validation” on page 515RELATED REFERENCESz/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and ReferenceParsing XML documents one segment at a timeYou can parse XML documents by passing the parser one segment (or record) ofXML text at a time. Processing very large documents, or processing XMLdocuments that reside in a data set, are two possible major applications of thistechnique.To use this feature, compile your program with the XMLPARSE(XMLSS) compileroption in effect.518 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


You parse an XML document a segment at a time by initializing the parse dataitem to the first segment of the XML document, and then executing the XML PARSEstatement. The parser processes the XML text and returns XML events to yourprocessing procedure as usual.At the end of the text segment, the parser signals an END-OF-INPUT XML event,with XML-CODE set to zero. If there is another segment of the document to process,in your processing procedure move the next segment of XML data to the parsedata item, set XML-CODE to one, and return to the parser. To signal the end of XMLsegments to the parser, return to the parser with XML-CODE still set to zero.The length of the parse data item is evaluated <strong>for</strong> each segment, and determinesthe segment length.Variable-length segments: If the XML document segments are variable length,specify a variable-length item <strong>for</strong> the parse data item. For example, <strong>for</strong>variable-length XML segments, you can define the parse data item as one of thefollowing items:v A variable-length group item that contains an OCCURS DEPENDING ON clausev A reference-modified itemvAn FD record that specifies the RECORD IS VARYING DEPENDING ON clause, wherethe depending-on data item is used as the length in a reference modifier or ODOobject <strong>for</strong> the FD recordWhen you send an XML document to the parser in multiple segments, documentcontent is in some cases returned to the processing procedure in multiplefragments by means of multiple events, rather than as one large fragment in asingle event.For example, if the document is split into two segments with the split point in themiddle of a string of content characters, the parser returns the content in twoseparate CONTENT-CHARACTERS events. In the processing procedure, you mustreassemble the string of content as needed by the application.Starting element tags, attribute names, namespace declarations, and endingelement tags are always delivered to the processing procedure in a single event,even if those items are split between two segments of a document.If a segment split occurs between the bytes of a multibyte character, the parserdetects the split and reassembles the character <strong>for</strong> delivery in a single event.QSAM and VSAM files: You can process XML documents stored in a QSAM orVSAM file as follows:1. Open the file and read the first record of the XML document.2. Execute the XML PARSE statement with the FD record as the parse data item.3. In the processing-procedure logic <strong>for</strong> handling the END-OF-INPUT event, read thenext record of the XML document into the parse data item. If not end-of-file(file status code 10), set XML-CODE to one and return to the parser. If end-of-file,return to the parser with XML-CODE still set to zero.4. In your processing procedure logic <strong>for</strong> the END-OF-DOCUMENT event, close the file.Miscellaneous in<strong>for</strong>mation after the root element:Chapter 28. Processing XML input 519


The root element of an XML document might be followed by zero or moreoccurrences of a comment or processing instruction, in any order. If you parse thedocument one segment at a time, the parser signals an END-OF-INPUT XML eventafter processing the end tag of the root element only if the last item in the segmentis incomplete. If the segment ends with a complete XML item (such as the rootelement end tag, or after that tag, a complete comment or processing instruction),the next XML event after the event <strong>for</strong> the item itself is the END-OF-DOCUMENT XMLevent.Tip: To provide successive segments of XML data after the end of the root element,include at least the first nonspace character of an XML item at the end of eachsegment. Include a complete item only on the last segment that you want theparser to process.For instance, in the following example, in which each line represents a segment ofan XML document, the segment that includes the text This comment ends thissegment is the last segment to be parsed:<strong>COBOL</strong> is the language of the future! “Example: parsing an XML document one segment at a time” on page 537RELATED CONCEPTS“XML events” on page 510“XML-CODE” on page 511RELATED REFERENCES“XMLPARSE” on page 357 (Compiler option)The encoding of XML documentsXML documents must be encoded in a supported code page.XML documents generated in or parsed from national data items must be encodedin Unicode UTF-16 in big-endian <strong>for</strong>mat, CCSID 1200.For XML GENERATE statements, documents generated in alphanumeric data itemsmust be encoded in Unicode UTF-8 (CCSID 1208) or one of the single-byteEBCDIC encodings listed in the table below. You can use any CCSID from thattable in the ENCODING phrase of the XML GENERATE statement.For XML PARSE statements, documents in alphanumeric data items must be encodedas follows:v If XMLPARSE(XMLSS) is in effect:– If the RETURNING NATIONAL phrase is specified in the XML PARSE statement, inany EBCDIC or ASCII encoding that is supported by z/<strong>OS</strong> Unicode Services<strong>for</strong> conversion to UTF-16– If the RETURNING NATIONAL phrase is not specified in the XML PARSE statement,in UTF-8 (CCSID 1208) or one of the single-byte EBCDIC encodings listed inthe table below520 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vIf XMLPARSE(COMPAT) is in effect: in one of the single-byte EBCDIC encodingslisted in the table below|If XMLPARSE(XMLSS) is in effect, you can use any supported CCSID (as describedabove <strong>for</strong> XML PARSE) intheENCODING phrase of the XML PARSE statement.Table 71. Coded character sets <strong>for</strong> XML documentsCCSIDDescription1208 UTF-8 11047 Latin 1/OpenSystems1140, 37 USA, Canada, ...EuroCountry Extended Code Page (ECECP),Country Extended Code Page (CECP)1141, 273 Austria, Germany ECECP, CECP1142, 277 Denmark, Norway ECECP, CECP1143, 278 Finland, Sweden ECECP, CECP1144, 280 Italy ECECP, CECP1145, 284 Spain, Latin America (Spanish) ECECP, CECP1146, 285 UK ECECP, CECP1147, 297 France ECECP, CECP1148, 500 International ECECP, CECP1149, 871 Iceland ECECP, CECP|1. Supported <strong>for</strong> the XML PARSE statement in the ENCODING phrase if XMLPARSE(XMLSS) is ineffectRELATED CONCEPTS“XML input document encoding”RELATED TASKS“Specifying the encoding” on page 523“Parsing XML documents encoded in UTF-8” on page 525Chapter 29, “Producing XML output,” on page 543RELATED REFERENCES“CODEPAGE” on page 310“XMLPARSE” on page 357 (compiler option)XML input document encodingTo parse an XML document using the XML PARSE statement, the document must beencoded in a supported encoding.The supported encodings <strong>for</strong> a given parse operation depend on:v The category of the data item that contains the XML documentv The setting of the XMLPARSE compiler optionv The optional phrases that are specified in the XML PARSE statementFor XML documents that are contained in a national data item, the supportedencoding is Unicode UTF-16 in big-endian <strong>for</strong>mat, CCSID 1200.Chapter 28. Processing XML input 521


For XML documents that are contained in an alphanumeric data item, thesupported encodings if the XMLPARSE(XMLSS) compiler option is in effect are asfollows:vvIf the RETURNING NATIONAL phrase is specified in the XML PARSE statement: UTF-8or any EBCDIC or ASCII encoding that is supported by the z/<strong>OS</strong> UnicodeServices <strong>for</strong> conversion to UTF-16If the RETURNING NATIONAL phrase is not specified: UTF-8 or any of thesingle-byte EBCDIC CCSIDs listed in the related reference about the encoding ofXML documentsFor XML documents that are contained in an alphanumeric data item, thesupported CCSIDs if XMLPARSE(COMPAT) is in effect are those specified in the relatedreference about the encoding of XML documents.To parse an XML document that is encoded in an unsupported code page, firstconvert the document to national character data (UTF-16) by using the NATIONAL-OFintrinsic function. You can convert the individual pieces of document text that arepassed to the processing procedure in special register XML-NTEXT back to theoriginal code page by using the DISPLAY-OF intrinsic function.||||||||||||||||XML declaration and white space:XML documents can begin with white space only if they do not have an XMLdeclaration:v If an XML document begins with an XML declaration, the first angle bracket (


v– The ENCODING phrase (if used) of the XML PARSE statement– The CCSID specified in the CODEPAGE compiler optionIf the XMLPARSE(COMPAT) option is in effect:– The data type of the data item that contains the XML document– The actual encoding determined when the parser examines the first few bytesof the document– The encoding declaration specified within the XML document– The CCSID specified in the CODEPAGE compiler optionIf XMLPARSE(XMLSS) is in effect:v Any encoding declaration specified within the XML document is ignored.v For XML documents that are contained in a national data item, the ENCODINGphrase of the XML PARSE statement must be omitted or must specify CCSID 1200.The CCSID specified in the CODEPAGE compiler option is ignored. The parsersignals an XML exception event if the actual document encoding is not UTF-16in big-endian <strong>for</strong>mat.v For XML documents that are contained in an alphanumeric data item, theCCSID specified in the ENCODING phrase overrides the CODEPAGE compiler option.The parser raises an XML exception event at the beginning of the parseoperation if the actual document encoding is not consistent with the specifiedCCSID.RELATED TASKS“Converting to or from national (Unicode) representation” on page 134“Specifying the encoding”“Parsing XML documents encoded in UTF-8” on page 525“Handling XML PARSE exceptions” on page 526RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“The encoding of XML documents” on page 520“EBCDIC code-page-sensitive characters in XML markup” on page 524Specifying the encodingYou can choose how to specify the encoding <strong>for</strong> parsing an XML document that isin an alphanumeric data item.The preferred way is to omit the encoding declaration from the document and tospecify the encoding using one of the following means:vvIf XMLPARSE(XMLSS) is in effect: the ENCODING phrase of the XML PARSE statement,or the CODEPAGE compiler optionIf XMLPARSE(COMPAT) is in effect: the CODEPAGE compiler optionOmitting the encoding declaration makes it possible to more easily transmit anXML document between heterogeneous systems. (If you included an encodingdeclaration, you would need to update it to reflect any code-page translationimposed by the transmission process.)For XMLPARSE(COMPAT):You can instead specify an encoding declaration in the XML declaration withwhich most XML documents begin. For example:Chapter 28. Processing XML input 523


Note that the XML parser generates an exception if it encounters an XMLdeclaration that does not begin in the first byte of an XML document.|If you specify an encoding declaration, do so in one of the following ways:v Specify the CCSID number (with or without any number of leading zeros)prefixed by one of the following strings in any mixture of uppercase andlowercase letters:– IBM-– IBM_– CCSID-– CCSID_v Use one of the aliases listed in the following table. You can code the aliases inany mixture of uppercase and lowercase letters.Table 73. Aliases <strong>for</strong> XML encoding declarationsCCSID Supported aliases037 EBCDIC-CP-US, EBCDIC-CP-CA, EBCDIC-CP-WT, EBCDIC-CP-NL500 EBCDIC-CP-BE, EBCDIC-CP-CH1200 UTF-161208 UTF-8For more in<strong>for</strong>mation about the CCSIDs that are supported <strong>for</strong> XML parsing, seethe related reference about the encoding of XML documents.RELATED CONCEPTS“XML input document encoding” on page 521RELATED TASKS“Parsing XML documents encoded in UTF-8” on page 525“Handling encoding conflicts” on page 529RELATED REFERENCES“The encoding of XML documents” on page 520EBCDIC code-page-sensitive characters in XML markupSeveral special characters that are used in XML markup have different hexadecimalrepresentations in different EBCDIC code pages.The following table shows those special characters and their hexadecimal values<strong>for</strong> various EBCDIC CCSIDs.Table 74. Hexadecimal values of special characters <strong>for</strong> various EBCDIC CCSIDsCharacter 1047 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149[ X’AD’ X’BA’ X’63’ X’9E’ X’B5’ X’90’ X’4A’ X’B1’ X’90’ X’4A’ X’AE’] X’BD’ X’BB’ X’FC’ X’9F’ X’9F’ X’51’ X’5A’ X’BB’ X’B5’ X’5A’ X’9E’! X’5A’ X’5A’ X’4F’ X’4F’ X’4F’ X’4F’ X’BB’ X’5A’ X’4F’ X’4F’ X’4F’| X’4F’ X’4F’ X’BB’ X’BB’ X’BB’ X’BB’ X’4F’ X’4F’ X’BB’ X’BB’ X’BB’# X’7B’ X’7B’ X’7B’ X’4A’ X’63’ X’B1’ X’69’ X’7B’ X’B1’ X’7B’ X’7B’524 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Parsing XML documents encoded in UTF-8If the XMLPARSE(XMLSS) compiler option is in effect, you can parse XML documentsthat are encoded in Unicode UTF-8 in a manner similar to parsing other XMLdocuments. However, some additional requirements apply.To parse a UTF-8 XML document, you must specify CCSID 1208 in the ENCODINGphrase of the XML PARSE statement, as shown in the following code fragment:XML PARSE xml-documentWITH ENCODING 1208PROCESSING PROCEDURE xml-event-handler...END-XMLYou define xml-document as an alphanumeric data item or alphanumeric groupitem in WORKING-STORAGE or LOCAL-STORAGE.|If you do not code the RETURNING NATIONAL phrase in the XML PARSE statement, theparser returns the XML document fragments in the alphanumeric special registersXML-TEXT, XML-NAMESPACE, and XML-NAMESPACE-PREFIX.UTF-8 characters are encoded using a variable number of bytes per character. Most<strong>COBOL</strong> operations on alphanumeric data assume a single-byte encoding, in whicheach character is encoded in 1 byte. When you operate on UTF-8 characters asalphanumeric data, you must ensure that the data is processed correctly. Avoidoperations (such as reference modification and moves that involve truncation) thatcan split a multibyte character between bytes. You cannot reliably use statementssuch as INSPECT to process multibyte characters in alphanumeric data.You can more reliably process UTF-8 document fragments by specifying theRETURNING NATIONAL phrase in the XML PARSE statement. If you use the RETURNINGNATIONAL phrase, XML document fragments are efficiently converted to UTF-16encoding and are returned to the application in the national special registersXML-NTEXT, XML-NNAMESPACE, and XMLNNAMESPACE-PREFIX. Then you can process theXML text fragments in national data items. (The UTF-16 encoding in national dataitems greatly facilitates Unicode processing in <strong>COBOL</strong>.)The following code fragment illustrates the use of both the ENCODING phrase andthe RETURNING NATIONAL phrase <strong>for</strong> parsing a UTF-8 XML document:XML PARSE xml-documentWITH ENCODING 1208 RETURNING NATIONALPROCESSING PROCEDURE xml-event-handlerON EXCEPTIONDISPLAY 'XML document error ' XML-CODESTOP RUNNOT ON EXCEPTIONDISPLAY 'XML document was successfully parsed.'END-XMLRELATED CONCEPTS“XML-TEXT and XML-NTEXT” on page 512“XML-NAMESPACE and XML-NNAMESPACE” on page 513“XML-NAMESPACE-PREFIX and XML-NNAMESPACE-PREFIX” on page 514Chapter 28. Processing XML input 525


RELATED TASKS“Processing UTF-8 data” on page 137“Parsing XML documents” on page 506“Specifying the encoding” on page 523RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“The encoding of XML documents” on page 520XML PARSE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Handling XML PARSE exceptions||If the XML parser encounters an anomaly or error during parsing, it sets anexception code in the XML-CODE special register and signals an XML exceptionevent. The specific exception codes that can occur and the subsequent actions thatyou can take differ depending on the setting of the XMLPARSE compiler option.For XMLPARSE(XMLSS):Return code and reason code: The exception code is <strong>for</strong>med from the return codeand the reason code that the parser generates. The return code and the reason codeare each a halfword binary value. The value in XML-CODE is a concatenation of thesetwo values.As an example, the following XML document is not well <strong>for</strong>med because theelement end tag mmsg does not match the element start tag msg:Hello|||||||The return code is hexadecimal 000C (XRC_NOT_WELL_FORMED), and the reason codeis hexadecimal 3035 (XRSN_ENDTAG_NAME_MISMATCH), if you parse the documentwithout validation. The concatenation of these two values, hexadecimal 000C3035,is returned to the processing procedure in the XML-CODE special register.If you parse a document with validation, the values returned in XML-CODE <strong>for</strong> anywell-<strong>for</strong>medness errors differ from the values returned <strong>for</strong> the same errors whenyou parse without validation. The return code generated by the z/<strong>OS</strong> XML SystemServices parser <strong>for</strong> any validation error is 24 (hexadecimal 0018).For more in<strong>for</strong>mation about the return codes and reason codes that can begenerated, see the related reference about exceptions with XMLPARSE(XMLSS) ineffect.|||||If XMLPARSE(XMLSS) is in effect, processing procedures cannot handle exceptionevents and cannot cause parsing to resume. When a processing procedure returnsto the parser from an exception event, the parser does not signal any furtherevents. The parser transfers control to the statement that is specified in the ONEXCEPTION phrase of the XML PARSE statement. If you did not code an ON EXCEPTIONphrase, control is passed to the end of the XML PARSE statement. XML-CODE containsthe original exception code set by the parser.If no exception occurs during parsing, control is passed to the statement specifiedin the NOT ON EXCEPTION phrase. If you did not code a NOT ON EXCEPTION phrase,control is passed to the end of the XML PARSE statement. XML-CODE contains zero.For XMLPARSE(COMPAT):526 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If the exception code is within a certain range, you might be able to handle theexception event within your processing procedure, and resume parsing.To handle an exception in the processing procedure, do these steps:1. Check the contents of XML-CODE.2. Handle the exception appropriately.3. Set XML-CODE to zero to indicate that you handled the exception.4. Return control to the parser.The exception condition no longer exists.You can handle exceptions in this way only if the exception code that is passed inXML-CODE is within one of the following ranges, which indicates that an encodingconflict was detected:v 50-99v 100,001 - 165,535Exception codes 1-49:In the processing procedure, you can do limited handlingof exceptions <strong>for</strong> which the exception code is within the range 1 - 49. After anexception in this range occurs, the parser does not signal any further normalevents, except the END-OF-DOCUMENT event, even if you set XML-CODE to zero be<strong>for</strong>ereturning. If you set XML-CODE to zero, the parser continues parsing the documentand signals any exceptions that it finds. (Doing so can provide a useful way todiscover multiple errors in the document.)||||At the end of parsing after an exception that has an exception code in the range 1 -49, control is passed to the statement specified in the ON EXCEPTION phrase. If youdid not code an ON EXCEPTION phrase, control is passed to the end of the XML PARSEstatement. XML-CODE contains the code set by the parser <strong>for</strong> the most recentexception.For all exceptions other than those having an exception code within one of theranges described above, the parser does not signal any further events, but passescontrol to the statement specified in the ON EXCEPTION phrase. XML-CODE containsthe original exception code even if you set XML-CODE in the processing procedurebe<strong>for</strong>e returning control to the parser.If you do not want to handle an exception, return control to the parser withoutchanging the value of XML-CODE. The parser transfers control to the statementspecified in the ON EXCEPTION phrase. If you did not code an ON EXCEPTION phrase,control is transferred to the end of the XML PARSE statement.If no unhandled exceptions occur be<strong>for</strong>e the end of parsing, control is passed tothe statement specified in the NOT ON EXCEPTION phrase. If you did not code a NOTON EXCEPTION phrase, control is transferred to the end of the XML PARSE statement.XML-CODE contains zero.RELATED CONCEPTS“XML-CODE” on page 511“XML input document encoding” on page 521“How the XML parser handles errors” on page 528RELATED TASKS“Writing procedures to process XML” on page 508Chapter 28. Processing XML input 527


“Parsing XML documents with validation” on page 515“Handling encoding conflicts” on page 529RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“The encoding of XML documents” on page 520“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709“XML PARSE exceptions with XMLPARSE(COMPAT) in effect” on page 711z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and ReferenceHow the XML parser handles errorsWhen the XML parser detects an error in an XML document, it generates an XMLexception event and passes control to your processing procedure.The parser passes the following in<strong>for</strong>mation in special registers to the processingprocedure:v XML-EVENT contains ’EXCEPTION’.v XML-CODE contains a numeric exception code.The exception codes are described in the related references about XML PARSEexceptions.vvIf XMLPARSE(COMPAT) is in effect, XML-TEXT or XML-NTEXT contains the documenttext up to and including the point where the exception was detected.If XMLPARSE(XMLSS) is in effect, XML-TEXT or XML-NTEXT contains the document textup to the point where the error or anomaly was detected. If you process theXML document one segment at a time, the applicable special register containsonly the current segment.All other XML special registers are empty with length zero.For XMLPARSE(XMLSS):Parsing cannot continue after an exception even if you set XML-CODE to zero in theprocessing procedure. Upon return to the parser from the processing procedure,the parser transfers control to the ON EXCEPTION phrase, if specified; otherwise theparser transfers control to the end of the XML PARSE statement. XML-CODE containsthe original exception code set by the parser.For XMLPARSE(COMPAT):The processing procedure might be able to handle an exception so that parsingcontinues if the exception code is within one of the following ranges:v 1-99v 100,001 - 165,535If the exception code has any other nonzero value, parsing cannot continue.Encoding conflicts: The exceptions <strong>for</strong> encoding conflicts (50 - 99 and 300 - 399)are signaled be<strong>for</strong>e the parsing of the document begins. For these exceptions,XML-TEXT or XML-NTEXT is either length zero or contains only the encodingdeclaration value from the document.Exception codes 1-49:An exception <strong>for</strong> which the exception code is in the range1 - 49 is a fatal error according to the XML specification. There<strong>for</strong>e the parser doesnot continue normal parsing even if the processing procedure handles the528 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


exception. However, the parser does continue scanning <strong>for</strong> further errors until itreaches the end of the document, or until it encounters an error that does notpermit continuation. For these exceptions, the parser does not signal any furthernormal events except the END-OF-DOCUMENT event.RELATED CONCEPTS“XML events” on page 510“XML-CODE” on page 511“XML input document encoding” on page 521RELATED TASKS“Parsing XML documents one segment at a time” on page 518“Handling XML PARSE exceptions” on page 526“Handling encoding conflicts”“Terminating XML parsing” on page 530RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“The encoding of XML documents” on page 520“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709“XML PARSE exceptions with XMLPARSE(COMPAT) in effect” on page 711z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and ReferenceXML specificationHandling encoding conflictsThe way that you handle encoding-conflict exceptions depends on the setting ofthe XMLPARSE compiler option.For XMLPARSE(XMLSS):The parser does not continue after an encoding-conflict exception or after anyother type of exception. Any changes that you make in the processing procedure tothe value of XML-CODE are ignored. The value in XML-CODE when the parser returnsto the XML PARSE statement is the original exception code that the parser set.For XMLPARSE(COMPAT):Your processing procedure might be able to handle exceptions <strong>for</strong> documentencoding conflicts. Exception events in which the parse data item is alphanumericand the exception code in XML-CODE is within the range 100,001 - 165,535 indicatethat the code page of the document (as specified by its encoding declaration)conflicts with the external code-page in<strong>for</strong>mation.In this special case, you can choose to parse using the code page of the documentby subtracting 100,000 from the value in XML-CODE. For instance, if XML-CODEcontains 101,140, the code page of the document is 1140. Alternatively, you canchoose to parse using the external code page by setting XML-CODE to zero be<strong>for</strong>ereturning to the parser.The parser takes one of three actions after returning from a processing procedure<strong>for</strong> an encoding-conflict exception event:vIf you set XML-CODE to zero, the parser uses the external code page: the value ofthe CODEPAGE compiler option.Chapter 28. Processing XML input 529


vvIf you set XML-CODE to the code page of the document (that is, the originalXML-CODE value minus 100,000), the parser uses the code page of the document.This is the only case in which the parser continues when XML-CODE has a nonzerovalue upon returning from a processing procedure.Otherwise, the parser stops processing the document and returns control to theXML PARSE statement with an exception condition. XML-CODE contains theexception code that was originally passed with the exception event.RELATED CONCEPTS“XML-CODE” on page 511“XML input document encoding” on page 521“How the XML parser handles errors” on page 528RELATED TASKS“Handling XML PARSE exceptions” on page 526Terminating XML parsingRELATED REFERENCES“XMLPARSE” on page 357 (compiler option)“The encoding of XML documents” on page 520“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709“XML PARSE exceptions with XMLPARSE(COMPAT) in effect” on page 711z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and ReferenceYou can terminate parsing immediately, without processing any remaining XMLtext, by setting XML-CODE to -1 in your processing procedure be<strong>for</strong>e the procedurereturns to the parser from any normal XML event (that is, any event other thanEXCEPTION).You can use this technique when the processing procedure has examined enoughof the document or has detected some irregularity in the document that precludesfurther meaningful processing.If you terminate parsing in this way, the parser does not signal any further XMLevents, including the exception event. Control transfers to the ON EXCEPTION phraseof the XML PARSE statement, if that phrase was specified.In the imperative statement of the ON EXCEPTION phrase, you can determinewhether parsing was deliberately terminated by testing whether XML-CODE contains-1. If you do not specify the ON EXCEPTION phrase, control transfers to the end ofthe XML PARSE statement.If the XMLPARSE(COMPAT) compiler option is in effect, you can also terminate parsingafter any XML EXCEPTION event by returning to the parser from the processingprocedure without changing the value in XML-CODE. The result is similar to theresult of deliberate termination, except that the parser returns to the XML PARSEstatement with XML-CODE containing the original exception code.If the XMLPARSE(XMLSS) option is in effect, parsing always terminates after anyexception event.RELATED CONCEPTS“XML-CODE” on page 511“How the XML parser handles errors” on page 528530 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


XML PARSE examplesRELATED TASKS“Writing procedures to process XML” on page 508“Handling XML PARSE exceptions” on page 526The examples that are referenced below illustrate various uses of the XML PARSEstatement.||Use these examples to understand the basic use of XML PARSE and, <strong>for</strong>XMLPARSE(XMLSS), specialized uses such as parsing documents that includenamespaces, parsing documents one segment at a time, and parsing documentswith validation against a schema.“Example: parsing a simple document”“Example: program <strong>for</strong> processing XML” on page 532“Example: parsing an XML document that uses namespaces” on page 535“Example: parsing an XML document one segment at a time” on page 537“Example: parsing XML documents with validation” on page 539Example: parsing a simple documentThis example shows the flow of events and the contents of special registerXML-TEXT that result from the parsing of a simple XML document.Assume that the <strong>COBOL</strong> program contains the following XML document in dataitem Doc:Hello, World!The following code fragment shows an XML PARSE statement <strong>for</strong> parsing Doc, and aprocessing procedure, P, <strong>for</strong> handling the XML events:XML Parse DocProcessing procedure P...P. Display XML-Event XML-Text.The processing procedure displays the content of XML-EVENT and XML-TEXT <strong>for</strong> eachevent that the parser signals during parsing. The following table shows the eventsand the text.Table 75. XML events and special registersXML-EVENTXML-TEXTSTART-OF-DOCUMENTVERSION-INFORMATION 1.0START-OF-ELEMENTmsgATTRIBUTE-NAMEtypeATTRIBUTE-CHARACTERSshortCONTENT-CHARACTERSHello, World!END-OF-ELEMENTmsgEND-OF-DOCUMENTChapter 28. Processing XML input 531


RELATED CONCEPTS“XML events” on page 510“XML-TEXT and XML-NTEXT” on page 512Example: program <strong>for</strong> processing XMLThis example shows the parsing of an XML document, and a processing procedurethat reports the various XML events and their associated text fragments.The XML document is shown in the program source to make it easier to follow theflow of the parsing. The output of the program with XMLPARSE(XMLSS) and withXMLPARSE(COMPAT) in effect is shown after the example.To understand the interaction of the parser and the processing procedure, and tomatch events to document fragments, compare the XML document to the output ofthe program.cbl codepage(1047)Identification division.Program-id. XMLSAMPL.Data division.Working-storage section.******************************************************************* XML document, encoded as initial values of data items. *******************************************************************1 xml-document.2 pic x(39) value ''.2 pic x(39) value ''.2 pic x(10) value ''.2 pic x(35) value ' '.2 pic x(41) value ' '.2 pic x(31) value ' Ham &amp; turkey'.2 pic x(40) value ' Cheese, lettuce, tomato, etc.'.2 pic x(10) value ''.2 pic x(35) value ' '.2 pic x(22) value ' element in future!]]>'.2 pic x(31) value ' $4.99 '.2 pic x(27) value ' 0.10'.2 pic x(11) value ''.1 xml-document-length computational pic 999.******************************************************************* Sample data definitions <strong>for</strong> processing numeric XML content. *******************************************************************1 current-element pic x(30).1 xfr-ed pic x(9) justified.1 xfr-ed-1 redefines xfr-ed pic 999999.99.1 list-price computational pic 9v99 value 0.1 discount computational pic 9v99 value 0.1 display-price pic $$9.99.Procedure division.Mainline section.XML parse xml-document processing procedure xml-handlerOn exceptionDisplay 'XML document error ' XML-CodeNot on exceptionDisplay 'XML document successfully parsed'End-XML532 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


******************************************************************* Process the trans<strong>for</strong>med content and calculate promo price. *******************************************************************Display ' 'Display '-----+++++***** Using in<strong>for</strong>mation from XML ''*****+++++-----'Display ' 'Move list-price to display-priceDisplay ' Sandwich list price: ' display-priceCompute display-price = list-price * (1 - discount)Display ' Promotional price: ' display-priceDisplay ' Get one today!'Goback.xml-handler section.Evaluate XML-Event* ==> Order XML events most frequent firstWhen 'START-OF-ELEMENT'Display 'Start element tag: {' XML-Text '}'Move XML-Text to current-elementWhen 'CONTENT-CHARACTERS'Display 'Content characters: {' XML-Text '}'* ==> Trans<strong>for</strong>m XML content to operational <strong>COBOL</strong> data item...evaluate current-elementWhen 'listprice'* ==> Using function NUMVAL-C...Compute list-price = function numval-c(XML-Text)When 'discount'* ==> Using de-editing of a numeric edited item...Move XML-Text to xfr-edMove xfr-ed-1 to discountEnd-evaluateWhen 'END-OF-ELEMENT'Display 'End element tag: {' XML-Text '}'Move spaces to current-elementWhen 'START-OF-DOCUMENT'Display 'Start of document'When 'END-OF-DOCUMENT'Display 'End of document.'When 'VERSION-INFORMATION'Display 'Version: {' XML-Text '}'When 'ENCODING-DECLARATION'Display 'Encoding: {' XML-Text '}'When 'STANDALONE-DECLARATION'Display 'Standalone: {' XML-Text '}'When 'ATTRIBUTE-NAME'Display 'Attribute name: {' XML-Text '}'When 'ATTRIBUTE-CHARACTERS'Display 'Attribute value characters: {' XML-Text '}'When 'ATTRIBUTE-CHARACTER'Display 'Attribute value character: {' XML-Text '}'When 'START-OF-CDATA-SECTION'Display 'Start of CData: {' XML-Text '}'When 'END-OF-CDATA-SECTION'Display 'End of CData: {' XML-Text '}'When 'CONTENT-CHARACTER'Display 'Content character: {' XML-Text '}'When 'PROCESSING-INSTRUCTION-TARGET'Display 'PI target: {' XML-Text '}'When 'PROCESSING-INSTRUCTION-DATA'Display 'PI data: {' XML-Text '}'When 'COMMENT'Display 'Comment: {' XML-Text '}'When 'EXCEPTION'Compute xml-document-length = function length (XML-Text)Display 'Exception ' XML-Code ' at offset 'Chapter 28. Processing XML input 533


xml-document-length '.'When otherDisplay 'Unexpected XML event: ' XML-Event '.'End-evaluate.End program XMLSAMPL.Output from parsing with XMLPARSE(XMLSS)From the following output you can see which fragments of the document wereassociated with the events that occurred during parsing:Start of documentVersion: {1.0}Encoding: {IBM-1047}Standalone: {yes}Comment: {This document is just an example}Start element tag: {sandwich}Content characters: { }Start element tag: {bread}Attribute name: {type}Attribute value characters: {baker's best}End element tag: {bread}Content characters: { }PI target: {spread}PI data: {please use real mayonnaise }Content characters: { }Start element tag: {meat}Content characters: {Ham & turkey}End element tag: {meat}Content characters: { }Start element tag: {filling}Content characters: {Cheese, lettuce, tomato, etc.}End element tag: {filling}Content characters: { }Start of CData: {}Content characters: {We should add a element in future!}End of CData: {}Content characters: { }Start element tag: {listprice}Content characters: {$4.99 }End element tag: {listprice}Content characters: { }Start element tag: {discount}Content characters: {0.10}End element tag: {discount}End element tag: {sandwich}End of document.XML document successfully parsed-----+++++***** Using in<strong>for</strong>mation from XML *****+++++-----Sandwich list price: $4.99Promotional price: $4.49Get one today!Output from parsing with XMLPARSE(COMPAT)From the following output you can see which fragments of the document wereassociated with the events that occurred during parsing:Start of documentVersion: {1.0}Encoding: {IBM-1047}Standalone: {yes}Comment: {This document is just an example}Start element tag: {sandwich}534 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Content characters: { }Start element tag: {bread}Attribute name: {type}Attribute value characters: {baker}Attribute value character: {'}Attribute value characters: {s best}End element tag: {bread}Content characters: { }PI target: {spread}PI data: {please use real mayonnaise }Content characters: { }Start element tag: {meat}Content characters: {Ham }Content character: {&}Content characters: { turkey}End element tag: {meat}Content characters: { }Start element tag: {filling}Content characters: {Cheese, lettuce, tomato, etc.}End element tag: {filling}Content characters: { }Start of CData: { element in future!}End of CData: {]]>}Content characters: { }Start element tag: {listprice}Content characters: {$4.99 }End element tag: {listprice}Content characters: { }Start element tag: {discount}Content characters: {0.10}End element tag: {discount}End element tag: {sandwich}End of document.XML document successfully parsed-----+++++***** Using in<strong>for</strong>mation from XML *****+++++-----Sandwich list price: $4.99Promotional price: $4.49Get one today!RELATED CONCEPTS“XML events” on page 510RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)XML-EVENT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: parsing an XML document that uses namespacesThis example shows the parsing of a document that uses namespaces andnamespace prefixes. The program must be compiled using the XMLPARSE(XMLSS)compiler option.Namespace identifiers and namespace prefixes are used in the program to qualifyelement names and attribute names. This qualification makes it possible to use thesame name in more than one context: title is used both as an author’s title (Mr)and as a book title (Writing <strong>COBOL</strong> <strong>for</strong> Fun and Profit).Chapter 28. Processing XML input 535


Sample XML documentThe sample XML document contains several namespace declarations: a defaultnamespace; then three namespace identifiers with prefixes (bk, pi, and isbn).Notice that the default namespace is set to the empty string <strong>for</strong> the elementcomment (xmlns=''). This setting “undeclares” the default namespace, with theresult that there is no default namespace.Book-Signing EventWhat a great issue!Results from parsingThe following table shows the sequence of events that the processing procedurereceives from the parser, and shows the content of the associated XML specialregisters.Table 76. XML events and special registersXML-EVENT XML-TEXT XML-NAMESPACE-PREFIX XML-NAMESPACESTART-OF-DOCUMENTSTART-OF-ELEMENT section http://www.ibm.com/eventsNAMESPACE-DECLARATIONhttp://www.ibm.com/eventsNAMESPACE-DECLARATION bk urn:loc.gov:booksNAMESPACE-DECLARATION pi urn:personalIn<strong>for</strong>mationNAMESPACE-DECLARATION isbn urn:ISBN:0-395-36341-6START-OF-ELEMENT title http://www.ibm.com/eventsCONTENT-CHARACTERS Book-Signing EventEND-OF-ELEMENT title http://www.ibm.com/eventsSTART-OF-ELEMENT signing http://www.ibm.com/eventsSTART-OF-ELEMENT author bk urn:loc.gov:booksATTRIBUTE-NAME title pi urn:personalIn<strong>for</strong>mationATTRIBUTE-CHARACTERS MrATTRIBUTE-NAME name pi urn:personalIn<strong>for</strong>mationATTRIBUTE-CHARACTERS Jim RossEND-OF-ELEMENT author bk urn:loc.gov:booksSTART-OF-ELEMENT book http://www.ibm.com/eventsATTRIBUTE-NAME title bk urn:loc.gov:booksATTRIBUTE-CHARACTERS Writing <strong>COBOL</strong> <strong>for</strong>Fun and ProfitATTRIBUTE-NAME number isbn urn:ISBN:0-395-36341-6ATTRIBUTE-CHARACTERS 0426070806536 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 76. XML events and special registers (continued)XML-EVENT XML-TEXT XML-NAMESPACE-PREFIX XML-NAMESPACEEND-OF-ELEMENT book http://www.ibm.com/eventsSTART-OF-ELEMENT commentNAMESPACE-DECLARATIONCONTENT-CHARACTERS What a great issue!END-OF-ELEMENTcommentEND-OF-ELEMENT signing http://www.ibm.com/eventsEND-OF-ELEMENT section http://www.ibm.com/eventsEND-OF-DOCUMENTFor a detailed description of the set of XML events, see the related reference aboutXML-EVENT.RELATED CONCEPTS“XML events” on page 510“XML-TEXT and XML-NTEXT” on page 512“XML-NAMESPACE and XML-NNAMESPACE” on page 513“XML-NAMESPACE-PREFIX and XML-NNAMESPACE-PREFIX” on page 514RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)XML-EVENT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: parsing an XML document one segment at a timeThis example shows the parsing of a document one segment at a time. Theprogram must be compiled using the XMLPARSE(XMLSS) compiler option.The example shows the XML content of a file, the program that reads and submitsXML text to the parser, and the sequence of events that results from parsing theinput records.Content of infileThe XML document that will be parsed a segment at a time is contained in fileinfile, shown below.<strong>COBOL</strong> is the language of the future!Program PARSESEGProgram PARSESEG reads a segment (a record) of the XML document from fileinfile, then passes the record to the parser using the XML PARSE statement. Theparser processes the XML text and transfers control to the processing procedure <strong>for</strong>each XML event. The processing procedure handles each event and returns to theparser.Chapter 28. Processing XML input 537


At the end of the segment, the parser sets XML-EVENT to END-OF-INPUT, setsXML-CODE to zero, and transfers control to the processing procedure. The processingprocedure reads the next XML record into the parse data item, sets XML-CODE toone, and returns to the parser.The exchange between the processing procedure and the parser continues until theREAD statement returns the end-of-file status code. The processing procedurereturns to the parser with XML-CODE still set to zero to indicate the end of segmentprocessing.Identification division.Program-id. PARSESEG.Environment division.Input-output section.File-control.Select Input-XMLAssign to infileFile status is Input-XML-status.Data division.File section.FD Input-XMLRecord is varying from 1 to 255 depending on Rec-lengthRecording mode V.1 fdrec.2 pic X occurs 1 to 255 depending on Rec-length .Working-storage section.1 Event-number comp pic 99.1 Rec-length comp-5 pic 9(4).1 Input-XML-status pic 99.Procedure division.Open input Input-XMLIf Input-XML-status not = 0Display 'Open failed, file status: ' Input-XML-statusGobackEnd-ifRead Input-XMLIf Input-XML-status not = 0Display 'Read failed, file status: ' Input-XML-statusGobackEnd-ifMove 0 to Event-numberDisplay 'Starting with: ' fdrecDisplay 'Event number and name Content of XML-text'XML parse fdrec processing procedure Handle-parse-eventsClose Input-XMLGoback.Handle-parse-events.Add 1 to Event-numberDisplay ' ' Event-number ': ' XML-event '{' XML-text '}'Evaluate XML-eventWhen 'END-OF-INPUT'Read Input-XMLEvaluate Input-XML-statusWhen 0Move 1 to XML-codeDisplay 'Continuing with: ' fdrecWhen 10Display 'At EOF; no more input.'When otherDisplay 'Read failed, file status:' Input-XML-statusGobackEnd-evaluateWhen other538 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


ContinueEnd-evaluate.End program PARSESEG.Results from parsingTo show parsing results, the processing procedure displayed each record of input,followed by the sequence of XML events and any associated text fragments inXML-TEXT. The content of XML-TEXT is displayed in braces ({}); empty braces signifythat XML-TEXT is empty.|Notice the extra zero-length CONTENT-CHARACTERS XML event at event number 08.(Such anomalies are typical when supplying XML text piecemeal.)Starting with: Event number and name Content of XML-TEXT01: START-OF-DOCUMENT {}02: VERSION-INFORMATION {1.0}03: END-OF-INPUT {}Continuing with: 04: START-OF-ELEMENT {Tagline}05: END-OF-INPUT {}Continuing with: <strong>COBOL</strong> is the language of the future!06: CONTENT-CHARACTERS {<strong>COBOL</strong> is the language of the future!}07: END-OF-INPUT {}Continuing with: 08: CONTENT-CHARACTERS {}09: END-OF-ELEMENT {Tagline}10: END-OF-DOCUMENT {}For a detailed description of the XML events that were detected, see the relatedreference about XML-EVENT.RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)XML-EVENT (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)||||||||||||||||Example: parsing XML documents with validationThis example shows the parsing of several XML documents with validation againsta schema, and a processing procedure that captures the return code and reasoncode that the parser generates after parsing each document. All of the XMLdocuments are well <strong>for</strong>med but not necessarily valid.The program must be compiled using the XMLPARSE(XMLSS) compiler option.The example uses the schema that was described in the related concept about XMLschemas.Assume that file item.xsd contains the schema in text <strong>for</strong>mat, and that thepreprocessed schema was generated in file item.osr by means of the followingz/<strong>OS</strong> UNIX command:xsdosrg -v -o /u/HLQ/xml/item.osr /u/HLQ/xml/item.xsdThe example uses the XML-SCHEMA clause to associate the XML schema name schemawith the ddname ddschema. The following DD statement associates the ddname withthe external z/<strong>OS</strong> UNIX file that contains the schema://GO.DDSCHEMA DD PATH='/u/HLQ/xml/item.osr'Chapter 28. Processing XML input 539


|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||Program ValidCkIdentification division.Program-id. ValidCk.Environment division.Configuration section.Special-names.xml-schema schema is 'ddschema'.Data division.Working-storage section.1 xml-decode.2 rtn comp pic 9(2).2 rsn comp-5 pic 9(4).1 hv pic x(16) value '0123456789ABCDEF'.1 xml-document-1.2 pic x(52) value''.2 pic x(31) value ''.2 pic x(36) value ' 1'.2 pic x(12) value ''.1 xml-document-2.2 pic x(34) value ''.2 pic x(11) value ''.2 pic x(30) value ' No name'.2 pic x(36) value ' 1'.2 pic x(12) value ''.1 xml-document-3.2 pic x(37) value ''.2 pic x(46) value''.2 pic x(37) value ' 10'.2 pic x(32) value ' Not here!'.2 pic x(12) value ''.1 xml-document-4.2 pic x(40) value ''.2 pic x(31) value ''.2 pic x(33) value ' Paintbrush'.2 pic x(37) value ' 10'.2 pic x(12) value ''.1 xml-document-5.2 pic x(32) value ''.2 pic x(31) value ''.2 pic x(32) value ' Not here!'.2 pic x(12) value ''.1 xml-document-6.2 pic x(36) value ''.2 pic x(31) value ''.2 pic x(33) value ' Paintbrush'.2 pic x(36) value ' 1'.2 pic x(35) value ' Nylon bristles'.2 pic x(12) value ''.1 xml-document-7.2 pic x(43) value''.2 pic x(31) value ''.2 pic x(33) value ' Paintbrush'.2 pic x(38) value ' 100'.2 pic x(12) value ''.Procedure division.m.xml parse xml-document-1 validating with file schemaprocessing procedure pxml parse xml-document-2 validating with file schemaprocessing procedure pxml parse xml-document-3 validating with file schemaprocessing procedure pxml parse xml-document-4 validating with file schema540 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


||||||||||||||||||||||||||||||||||||||||||||||||||||||||processing procedure pxml parse xml-document-5 validating with file schemaprocessing procedure pxml parse xml-document-6 validating with file schemaprocessing procedure pxml parse xml-document-7 validating with file schemaprocessing procedure pgoback.p.evaluate xml-eventwhen 'COMMENT'display ' 'display xml-textwhen 'END-OF-DOCUMENT'display ' Document successfully parsed.'when 'EXCEPTION'move xml-code to xml-decodedisplay ' RC=' rtn ', reason=x'''hv(function mod(rsn / 4096 16) + 1:1)hv(function mod(rsn / 256 16) + 1:1)hv(function mod(rsn / 16 16) + 1:1)hv(function mod(rsn 16) + 1:1) ''''end-evaluate.End program ValidCk.Output from program ValidCkIn the following output, you can see which XML documents in the source programfailed validation against the schema.For those documents that were not valid, the parser signaled an XML exceptionand passed control to the processing procedure with special register XML-EVENTcontaining ’EXCEPTION’ and special-register XML-CODE containing the return code anda specific reason code.Valid: the "itemName" element can be omittedDocument successfully parsed.Invalid: missing attribute itemNumberRC=24, reason=x'8613'Invalid: unexpected attribute warehouseRC=24, reason=x'8612'Invalid: illegal attribute value 123-AbRC=24, reason=x'8809'Invalid: missing element quantityOnHandRC=24, reason=x'8611'Invalid: unexpected element commentRC=24, reason=x'8607'Invalid: out-of-range element value 100RC=24, reason=x'8803'RELATED CONCEPTS“XML-CODE” on page 511“XML schemas” on page 517Chapter 28. Processing XML input 541


|||||RELATED TASKS“Parsing XML documents with validation” on page 515“Handling XML PARSE exceptions” on page 526RELATED REFERENCES“XML PARSE exceptions with XMLPARSE(XMLSS) in effect” on page 709|542 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 29. Producing XML outputYou can produce XML output from a <strong>COBOL</strong> program by using the XML GENERATEstatement.In the XML GENERATE statement, you identify the source and the output data items.You can optionally also identify:v A field to receive a count of the XML characters generatedv A code page in which the generated XML document is to be encodedv A namespace <strong>for</strong> the generated documentvvA namespace prefix to qualify the start and end tag of each element, if youspecify a namespaceA statement to receive control if an exception occursOptionally, you can generate an XML declaration <strong>for</strong> the document, and can causeeligible source data items to be expressed as attributes in the output rather than aselements.You can use the XML-CODE special register to determine the status of XMLgeneration.After you trans<strong>for</strong>m <strong>COBOL</strong> data items to XML, you can use the resulting XMLoutput in various ways, such as deploying it in a Web service, passing it as amessage to WebSphere MQ, or transmitting it <strong>for</strong> subsequent conversion to a CICScommunication area.Link-edit considerations: <strong>COBOL</strong> programs that contain the XML GENERATEstatement must be link-edited with AMODE 31.RELATED TASKS“Generating XML output”“Controlling the encoding of generated XML output” on page 547“Handling XML GENERATE exceptions” on page 548“Enhancing XML output” on page 553Generating XML outputRELATED REFERENCESExtensible Markup Language (XML)XML GENERATE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)To trans<strong>for</strong>m <strong>COBOL</strong> data to XML, use the XML GENERATE statement as in theexample below.XML GENERATE XML-OUTPUT FROM SOURCE-RECCOUNT IN XML-CHAR-COUNTON EXCEPTIONDISPLAY 'XML generation error ' XML-CODESTOP RUNNOT ON EXCEPTIONDISPLAY 'XML document was successfully generated.'END-XML© Copyright IBM Corp. 1991, 2009 543


In the XML GENERATE statement, you first identify the data item (XML-OUTPUT in theexample above) that is to receive the XML output. Define the data item to be largeenough to contain the generated XML output, typically five to 10 times the size ofthe <strong>COBOL</strong> source data depending on the length of its data-name or data-names.In the DATA DIVISION, you can declare the receiving identifier as alphanumeric(either an alphanumeric group item or an elementary item of categoryalphanumeric) or as national (either a national group item or an elementary itemof category national).Next you identify the source data item that is to be trans<strong>for</strong>med to XML <strong>for</strong>mat(SOURCE-REC in the example). The source data item can be an alphanumeric groupitem, national group item, or elementary data item of class alphanumeric ornational.Some <strong>COBOL</strong> data items are not trans<strong>for</strong>med to XML, but are ignored. Subordinatedata items of an alphanumeric group item or national group item that youtrans<strong>for</strong>m to XML are ignored if they:v Specify the REDEFINES clause, or are subordinate to such a redefining itemv Specify the RENAMES clauseThese items in the source data item are also ignored when you generate XML:v Elementary FILLER (or unnamed) data itemsv Slack bytes inserted <strong>for</strong> SYNCHRONIZED data itemsNo extra white space (<strong>for</strong> example, new lines or indentation) is inserted to makethe generated XML more readable.Optionally, you can code the COUNT IN phrase to obtain the number of XMLcharacter encoding units that are filled during generation of the XML output. If thereceiving identifier has category national, the count is in UTF-16 characterencoding units. For all other encodings (including UTF-8), the count is in bytes.You can use the count field as a reference modification length to obtain only thatportion of the receiving data item that contains the generated XML output. Forexample, XML-OUTPUT(1:XML-CHAR-COUNT) references the first XML-CHAR-COUNTcharacter positions of XML-OUTPUT.Consider the following program excerpt:01 doc pic x(512).01 docSize pic 9(9) binary.01 G.05 A pic x(3) value "aaa".05 B.10 C pic x(3) value "ccc".10 D pic x(3) value "ddd".05 E pic x(3) value "eee"....XML Generate Doc from GThe code above generates the following XML document, in which A, B, and E areexpressed as child elements of element G, and C and D become child elements ofelement B:aaacccdddeee544 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Alternatively, you can specify the ATTRIBUTES phrase of the XML GENERATEstatement. The ATTRIBUTES phrase causes each elementary data item included inthe generated XML document (provided that such a data item has a name otherthan FILLER and does not have an OCCURS clause in its data description entry) to beexpressed as an attribute of the XML element that corresponds to its immediatelysuperordinate data item, rather than as a child element.For example, suppose that the XML GENERATE statement in the program excerptabove had instead been coded as follows:XML Generate Doc from G with attributesThe code would then generate the following XML document, in which A and E areexpressed as attributes of element G, and C and D become attributes of element B:Optionally, you can code the ENCODING phrase of the XML GENERATE statement tospecify the CCSID of the generated XML document. If you do not use the ENCODINGphrase, the document encoding is determined by the category of the receiving dataitem and by the CODEPAGE compiler option. For further details, see the related taskbelow about controlling the encoding of generated XML output.Optionally, you can code the XML-DECLARATION phrase to cause the generated XMLdocument to have an XML declaration that includes version in<strong>for</strong>mation and anencoding declaration. If the receiving data item is of category:v National: The encoding declaration has the value UTF-16 (encoding="UTF-16").vAlphanumeric: The encoding declaration is derived from the ENCODING phrase, ifspecified, or from the CODEPAGE compiler option in effect <strong>for</strong> the program if theENCODING phrase is not specified.For example, the program excerpt below specifies the XML-DECLARATION phrase ofXML GENERATE, and specifies encoding with CCSID 1208 (UTF-8):01 Greeting.05 msg pic x(80) value 'Hello, world!'....XML Generate Doc from Greetingwith Encoding 1208with XML-declarationEnd-XMLThe code above generates the following XML document:Hello, world!If you do not code the XML-DECLARATION phrase, an XML declaration is notgenerated.Optionally, you can code the NAMESPACE phrase to specify a namespace <strong>for</strong> thegenerated XML document. The namespace value must be a valid Uni<strong>for</strong>m ResourceIdentifier (URI), <strong>for</strong> example, a URL (Uni<strong>for</strong>m Resource Locator); <strong>for</strong> further details,see the related concept about URI syntax below.Specify the namespace in an identifier or literal of either category national oralphanumeric.If you specify a namespace, but do not specify a namespace prefix (describedbelow), the namespace becomes the default namespace <strong>for</strong> the document. That is, theChapter 29. Producing XML output 545


namespace declared on the root element applies by default to each element namein the document, including the root element.For example, consider the following data definitions and XML GENERATE statement:01 Greeting.05 msg pic x(80) value 'Hello, world!'.01 NS pic x(20) value 'http://example'....XML Generate Doc from Greetingnamespace is NSThe resulting XML document has a default namespace (http://example), asfollows:Hello, world!If you do not specify a namespace, the element names in the generated XMLdocument are not in any namespace.Optionally, you can code the NAMESPACE-PREFIX phrase to specify a prefix to beapplied to the start and end tag of each element in the generated document. Youcan specify a prefix only if you have specified a namespace as described above.When the XML GENERATE statement is executed, the prefix value must be a validXML name, but without the colon (:); see the related reference below aboutnamespaces <strong>for</strong> details. The value can have trailing spaces, which are removedbe<strong>for</strong>e the prefix is used.Specify the namespace prefix in an identifier or literal of either category national oralphanumeric.It is recommended that the prefix be short, because it qualifies the start and endtag of each element.For example, consider the following data definitions and XML GENERATE statement:01 Greeting.05 msg pic x(80) value 'Hello, world!'.01 NS pic x(20) value 'http://example'.01 NP pic x(5) value 'pre'....XML Generate Doc from Greetingnamespace is NSnamespace-prefix is NPThe resulting XML document has an explicit namespace (http://example), and theprefix pre is applied to the start and end tag of the elements Greeting and msg, asfollows:Hello, world!In addition, you can specify either or both of the following phrases to receivecontrol after generation of the XML document:v ON EXCEPTION, to receive control if an error occurs during XML generationv NOT ON EXCEPTION, to receive control if no error occursYou can end the XML GENERATE statement with the explicit scope terminatorEND-XML. Code END-XML to nest an XML GENERATE statement that has the ONEXCEPTION or NOT ON EXCEPTION phrase in a conditional statement.546 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


XML generation continues until either the <strong>COBOL</strong> source record has beentrans<strong>for</strong>med to XML or an error occurs. If an error occurs, the results are asfollows:v The XML-CODE special register contains a nonzero exception code.vControl is passed to the ON EXCEPTION phrase, if specified, otherwise to the endof the XML GENERATE statement.If no error occurs during XML generation, the XML-CODE special register containszero, and control is passed to the NOT ON EXCEPTION phrase if specified or to theend of the XML GENERATE statement otherwise.“Example: generating XML” on page 549RELATED CONCEPTSUni<strong>for</strong>m Resource Identifier (URI): Generic SyntaxRELATED TASKS“Controlling the encoding of generated XML output”“Handling XML GENERATE exceptions” on page 548“Processing UTF-8 data” on page 137RELATED REFERENCESXML GENERATE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Extensible Markup Language (XML)Namespaces in XML 1.0Controlling the encoding of generated XML outputWhen you generate XML output by using the XML GENERATE statement, you cancontrol the encoding of the output by the category of the data item that receivesthe output, and by identifying the code page using the WITH ENCODING phrase ofthe XML GENERATE statement.If you specify the WITH ENCODING codepage phrase to designate the coded characterset identifer (CCSID) of the output document, codepage must specify an unsignedinteger data item or unsigned integer literal that identifies one of the code pagessupported <strong>for</strong> <strong>COBOL</strong> XML processing as described in the related reference belowabout the encoding of XML documents:vvIf the data item that receives the generated XML is of category national, the WITHENCODING phrase must specify 1200, the CCSID <strong>for</strong> Unicode UTF-16.If the receiving identifier is of category alphanumeric, the WITH ENCODING phrasemust specify CCSID 1208 or the CCSID of a supported EBCDIC code page.If you do not code the WITH ENCODING phrase, the generated XML output isencoded as shown in the table below.Table 77. Encoding of generated XML if the ENCODING phrase is omittedIf you define the receiving XMLidentifier as:The generated XML output is encoded in:AlphanumericThe code page specified by the CODEPAGEcompiler option in effect when the source wascompiledNational UTF-16 big-endian (UTF-16BE, CCSID 1200)Chapter 29. Producing XML output 547


A byte order mark is not generated.For details about how data items are converted to XML and how the XML elementnames and attributes names are <strong>for</strong>med from the <strong>COBOL</strong> data-names, see therelated reference below about the operation of the XML GENERATE statement.RELATED REFERENCES“CODEPAGE” on page 310“The encoding of XML documents” on page 520XML GENERATE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Operation of XML GENERATE (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Handling XML GENERATE exceptionsWhen an error is detected during generation of XML output, an exceptioncondition exists. You can write code to check the XML-CODE special register, whichcontains a numeric exception code that indicates the error type.To handle errors, use either or both of the following phrases of the XML GENERATEstatement:v ON EXCEPTIONv COUNT INIf you code the ON EXCEPTION phrase in the XML GENERATE statement, control istransferred to the imperative statement that you specify. You might code animperative statement, <strong>for</strong> example, to display the XML-CODE value. If you do notcode an ON EXCEPTION phrase, control is transferred to the end of the XML GENERATEstatement.When an error occurs, one problem might be that the data item that receives theXML output is not large enough. In that case, the XML output is not complete, andthe XML-CODE special register contains error code 400.You can examine the generated XML output by doing these steps:1. Code the COUNT IN phrase in the XML GENERATE statement.The count field that you specify holds a count of the XML character encodingunits that are filled during XML generation. If you define the XML output asnational, the count is in UTF-16 character encoding units; <strong>for</strong> all otherencodings (including <strong>for</strong> UTF-8), the count is in bytes.2. Use the count field as a reference modification length to refer to the substringof the receiving data item that contains the XML characters that were generateduntil the point when the error occurred.For example, if XML-OUTPUT is the data item that receives the XML output, andXML-CHAR-COUNT is the count field, then XML-OUTPUT(1:XML-CHAR-COUNT)references the XML output.Use the contents of XML-CODE to determine what corrective action to take. For a listof the exceptions that can occur during XML generation, see the related referencebelow.RELATED TASKS“Referring to substrings of data items” on page 107548 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Example: generating XMLRELATED REFERENCES“XML GENERATE exceptions” on page 718XML-CODE (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The following example simulates the building of a purchase order in a group dataitem, and generates an XML version of that purchase order.Program XGFX uses XML GENERATE to produce XML output in elementary data itemxmlPO from the source record, group data item purchaseOrder. Elementary dataitems in the source record are converted to character <strong>for</strong>mat as necessary, and thecharacters are inserted as the values of XML attributes whose names are derivedfrom the data-names in the source record.XGFX calls program Pretty, which uses the XML PARSE statement with processingprocedure p to <strong>for</strong>mat the XML output with new lines and indentation so that theXML content can more easily be verified.Program XGFXIdentification division.Program-id. XGFX.Data division.Working-storage section.01 numItems pic 99 global.01 purchaseOrder global.05 orderDate pic x(10).05 shipTo.10 country pic xx value 'US'.10 name pic x(30).10 street pic x(30).10 city pic x(30).10 state pic xx.10 zip pic x(10).05 billTo.10 country pic xx value 'US'.10 name pic x(30).10 street pic x(30).10 city pic x(30).10 state pic xx.10 zip pic x(10).05 orderComment pic x(80).05 items occurs 0 to 20 times depending on numItems.10 item.15 partNum pic x(6).15 productName pic x(50).15 quantity pic 99.15 USPrice pic 999v99.15 shipDate pic x(10).15 itemComment pic x(40).01 numChars comp pic 999.01 xmlPO pic x(999).Procedure division.m.Move 20 to numItemsMove spaces to purchaseOrderMove '1999-10-20' to orderDateMove 'US' to country of shipToMove 'Alice Smith' to name of shipToMove '123 Maple Street' to street of shipToChapter 29. Producing XML output 549


Move 'Mill Valley' to city of shipToMove 'CA' to state of shipToMove '90952' to zip of shipToMove 'US' to country of billToMove 'Robert Smith' to name of billToMove '8 Oak Avenue' to street of billToMove 'Old Town' to city of billToMove 'PA' to state of billToMove '95819' to zip of billToMove 'Hurry, my lawn is going wild!' to orderComment|||Move 0 to numItemsCall 'addFirstItem'Call 'addSecondItem'Move space to xmlPOXml generate xmlPO from purchaseOrder count in numCharswith xml-declaration with attributesnamespace 'http://www.example.com' namespace-prefix 'po'Call 'pretty' using xmlPO value numCharsGoback.Identification division.Program-id. 'addFirstItem'.Procedure division.Add 1 to numItemsMove '872-AA' to partNum(numItems)Move 'Lawnmower' to productName(numItems)Move 1 to quantity(numItems)Move 148.95 to USPrice(numItems)Move 'Confirm this is electric' to itemComment(numItems)Goback.End program 'addFirstItem'.Identification division.Program-id. 'addSecondItem'.Procedure division.Add 1 to numItemsMove '926-AA' to partNum(numItems)Move 'Baby Monitor' to productName(numItems)Move 1 to quantity(numItems)Move 39.98 to USPrice(numItems)Move '1999-05-21' to shipDate(numItems)Goback.End program 'addSecondItem'.End program XGFX.Program PrettyProcess xmlparse(xmlss), codepage(37)Identification division.Program-id. Pretty.Data division.Working-storage section.01 prettyPrint.05 pose pic 999.05 posd pic 999.05 depth pic 99.05 inx pic 999.05 elementName pic x(30).05 indent pic x(40).05 buffer pic x(998).05 lastitem pic 9.88 unknown value 0.88 xml-declaration value 1.550 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


88 element value 2.88 attribute value 3.88 charcontent value 4.Linkage section.1 doc.2 pic x occurs 16384 times depending on len.1 len comp-5 pic 9(9).Procedure division using doc value len.m.Move space to prettyPrintMove 0 to depthMove 1 to posd poseXml parse doc processing procedure pGoback.p.Evaluate xml-eventWhen 'VERSION-INFORMATION'String '' delimited by size into bufferwith pointer posdSet unknown to truePer<strong>for</strong>m printlineMove 1 to posdWhen elementString '>' delimited by size into bufferwith pointer posdWhen attributeString '">' delimited by size into bufferwith pointer posdEnd-evaluateIf elementName not = spacePer<strong>for</strong>m printlineEnd-ifMove xml-text to elementNameAdd 1 to depthMove 1 to poseSet element to trueIf xml-namespace-prefix = spaceString '


with pointer posdElseString xml-namespace-prefix ':' xml-text '="'delimited by size into buffer with pointer posdEnd-ifSet attribute to trueWhen 'NAMESPACE-DECLARATION'If elementString ' ' delimited by size into bufferwith pointer posdElseString '" ' delimited by size into bufferwith pointer posdEnd-ifIf xml-namespace-prefix = spaceString 'xmlns="' xml-namespace delimited by sizeinto buffer with pointer posdElseString 'xmlns:' xml-namespace-prefix '="' xml-namespacedelimited by size into buffer with pointer posdEnd-ifSet attribute to trueWhen 'ATTRIBUTE-CHARACTERS'String xml-text delimited by size into bufferwith pointer posdWhen 'ATTRIBUTE-CHARACTER'String xml-text delimited by size into bufferwith pointer posdWhen 'CONTENT-CHARACTERS'Evaluate trueWhen elementString '>' delimited by size into bufferwith pointer posdWhen attributeString '">' delimited by size into bufferwith pointer posdEnd-evaluateString xml-text delimited by size into bufferwith pointer posdSet charcontent to trueWhen 'CONTENT-CHARACTER'Evaluate trueWhen elementString '>' delimited by size into bufferwith pointer posdWhen attributeString '">' delimited by size into bufferwith pointer posdEnd-evaluateString xml-text delimited by size into bufferwith pointer posdSet charcontent to trueWhen 'END-OF-ELEMENT'Move space to elementNameEvaluate trueWhen elementString '/>' delimited by size into bufferwith pointer posdWhen attributeString '"/>' delimited by size into bufferwith pointer posdWhen otherIf xml-namespace-prefix = spaceString '' delimited by sizeinto buffer with pointer posdElseString ''552 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


delimited by size into buffer with pointer posdEnd-ifEnd-evaluateSet unknown to truePer<strong>for</strong>m printlineSubtract 1 from depthMove 1 to posdWhen otherContinueEnd-evaluate.printline.Compute inx = function max(0 2 * depth - 2) + posd - 1If inx > 120compute inx = 117 - function max(0 2 * depth - 2)If depth > 1Display indent(1:2 * depth - 2) buffer(1:inx) '...'ElseDisplay buffer(1:inx) '...'End-ifElseIf depth > 1Display indent(1:2 * depth - 2) buffer(1:posd - 1)ElseDisplay buffer(1:posd - 1)End-ifEnd-if.End program Pretty.Output from program XGFX


vvvvThe definition of the data is not of the required data type. Perhaps only theredefinitions (which are ignored by the XML GENERATE statement) have theappropriate <strong>for</strong>mat.The required data items are nested too deeply within irrelevant subordinategroups. The XML output should be “flattened” rather than hierarchical as itwould be by default.The required data items are broken up into too many components, and shouldbe output as the content of the containing group.The group item contains the required in<strong>for</strong>mation but in the wrong order.There are various ways that you can deal with such situations. One possibletechnique is to define a new data item that has the appropriate characteristics, andmove the required data to the appropriate fields of this new data item. However,this approach is somewhat laborious and requires careful maintenance to keep theoriginal and new data items synchronized.An alternative approach that has some advantages is to provide a redefinition ofthe original group data item, and to generate the XML output from thatredefinition. To do so, start from the original set of data descriptions, and makethese changes:vvvvvExclude elementary data items from the generated XML either by renamingthem to FILLER or by deleting their names.Provide more meaningful and appropriate names <strong>for</strong> the selected elementaryitems and <strong>for</strong> the group items that contain them.Remove unneeded intermediate group items to flatten the hierarchy.Specify different data types to obtain the desired trimming behavior.Choose a different order <strong>for</strong> the output by using a sequence of XML GENERATEstatements.The safest way to accomplish these changes is to use another copy of the originaldeclarations accompanied by one or more REPLACE compiler-directing statements.The example that is referenced below shows a way to do so.“Example: enhancing XML output”You might also find when you generate an XML document that some of theelement or attribute names and values contain hyphens. You might want to convertthe hyphens in the element and attribute names to underscores without changingthe hyphens that are in the element and attribute values. The example that isreferenced below shows a way to do so.“Example: converting hyphens in element or attribute names to underscores” onpage 557RELATED REFERENCESOperation of XML GENERATE (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: enhancing XML outputThe following example shows how you can modify XML output.Consider the following data structure. The XML that is generated from thestructure suffers from several problems that can be corrected.554 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


01 CDR-LIFE-BASE-VALUES-BOX.15 CDR-LIFE-BASE-VAL-DATE PIC X(08).15 CDR-LIFE-BASE-VALUE-LINE OCCURS 2 TIMES.20 CDR-LIFE-BASE-DESC.25 CDR-LIFE-BASE-DESC1 PIC X(15).25 FILLER PIC X(01).25 CDR-LIFE-BASE-LIT PIC X(08).25 CDR-LIFE-BASE-DTE PIC X(08).20 CDR-LIFE-BASE-PRICE.25 CDR-LIFE-BP-SPACE PIC X(02).25 CDR-LIFE-BP-DASH PIC X(02).25 CDR-LIFE-BP-SPACE1 PIC X(02).20 CDR-LIFE-BASE-PRICE-ED REDEFINESCDR-LIFE-BASE-PRICE PIC $$$.$$.20 CDR-LIFE-BASE-QTY.25 CDR-LIFE-QTY-SPACE PIC X(08).25 CDR-LIFE-QTY-DASH PIC X(02).25 CDR-LIFE-QTY-SPACE1 PIC X(02).25 FILLER PIC X(02).20 CDR-LIFE-BASE-QTY-ED REDEFINESCDR-LIFE-BASE-QTY PIC ZZ,ZZZ,ZZZ.ZZZ.20 CDR-LIFE-BASE-VALUE PIC X(15).20 CDR-LIFE-BASE-VALUE-ED REDEFINESCDR-LIFE-BASE-VALUEPIC $(4),$$$,$$9.99.15 CDR-LIFE-BASE-TOT-VALUE-LINE.20 CDR-LIFE-BASE-TOT-VALUE PIC X(15).When this data structure is populated with some sample values, and XML isgenerated directly from it and then <strong>for</strong>matted using program Pretty (shown in“Example: generating XML” on page 549), the result is as follows:01/02/03First 01/01/01$23.00 123.0 $765.00Second 02/02/02$34.00 234.0Chapter 29. Producing XML output 555


$654.00Very high!This generated XML suffers from several problems:v The element names are long and not very meaningful.v There is unwanted data, <strong>for</strong> example, CDR-LIFE-BASE-LIT andCDR-LIFE-BASE-DTE.v Required data has an unnecessary parent. For example, CDR-LIFE-BASE-DESC1 hasparent CDR-LIFE-BASE-DESC.v Other required fields are split into too many subcomponents. For example,CDR-LIFE-BASE-PRICE has three subcomponents <strong>for</strong> one amount.These and other characteristics of the XML output can be remedied by redefiningthe storage as follows:1 BaseValues redefines CDR-LIFE-BASE-VALUES-BOX.2 BaseValueDate pic x(8).2 BaseValueLine occurs 2 times.3 Description pic x(15).3 pic x(9).3 BaseDate pic x(8).3 BasePrice pic x(6) justified.3 BaseQuantity pic x(14) justified.3 BaseValue pic x(15) justified.2 TotalValue pic x(15).The result of generating and <strong>for</strong>matting XML from the set of definitions of the datavalues shown above is more usable:01/02/03First01/01/01$23.00123.000$765.00Second02/02/02$34.00234.000$654.00Very high!You can redefine the original data definition directly, as shown above. However, itis generally safer to use the original definition but to modify it suitably using thetext-manipulation capabilities of the compiler. An example is shown in the REPLACEcompiler-directing statement below. This REPLACE statement might appearcomplicated, but it has the advantage of being self-maintaining if the original datadefinitions are modified.replace ==CDR-LIFE-BASE-VALUES-BOX== by==BaseValues redefines CDR-LIFE-BASE-VALUES-BOX====CDR-LIFE-BASE-VAL-DATE== by ==BaseValueDate==556 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


==CDR-LIFE-BASE-VALUE-LINE== by ==BaseValueLine====20 CDR-LIFE-BASE-DESC.== by ======CDR-LIFE-BASE-DESC1== by ==Description====CDR-LIFE-BASE-LIT== by ======CDR-LIFE-BASE-DTE== by ==BaseDate====20 CDR-LIFE-BASE-PRICE.== by ======25 CDR-LIFE-BP-SPACE PIC X(02).== by ======25 CDR-LIFE-BP-DASH PIC X(02).== by ======25 CDR-LIFE-BP-SPACE1 PIC X(02).== by ======CDR-LIFE-BASE-PRICE-ED== by ==BasePrice====REDEFINES CDR-LIFE-BASE-PRICE PIC $$$.$$.== by==pic x(6) justified.====20 CDR-LIFE-BASE-QTY.25 CDR-LIFE-QTY-SPACE PIC X(08).25 CDR-LIFE-QTY-DASH PIC X(02).25 CDR-LIFE-QTY-SPACE1 PIC X(02).25 FILLER PIC X(02).== by ======CDR-LIFE-BASE-QTY-ED== by ==BaseQuantity====REDEFINES CDR-LIFE-BASE-QTY PIC ZZ,ZZZ,ZZZ.ZZZ.== by==pic x(14) justified.====CDR-LIFE-BASE-VALUE-ED== by ==BaseValue====20 CDR-LIFE-BASE-VALUE PIC X(15).== by ======REDEFINES CDR-LIFE-BASE-VALUE PIC $(4),$$$,$$9.99.==by ==pic x(15) justified.====CDR-LIFE-BASE-TOT-VALUE-LINE. 20== by ======CDR-LIFE-BASE-TOT-VALUE== by ==TotalValue==.The result of this REPLACE statement followed by a second instance of the originalset of definitions is similar to the suggested redefinition of group item BaseValuesshown above. This REPLACE statement illustrates a variety of techniques <strong>for</strong>eliminating unwanted definitions and <strong>for</strong> modifying the definitions that should beretained. Use whichever technique is appropriate <strong>for</strong> your situation.RELATED REFERENCESOperation of XML GENERATE (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)REPLACE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: converting hyphens in element or attribute names tounderscoresWhen you generate an XML document from a data structure whose items havedata-names that contain hyphens, the generated XML has element or attributenames that contain hyphens. This example shows a way to convert hyphens thatoccur in element or attribute names to underscores without changing hyphens thatoccur in element or attribute values.1 Customer-Record.2 Customer-Number pic 9(9).2 First-Name pic x(10).2 Last-Name pic x(20).When the data structure above is populated with some sample values, and XML isgenerated from it and then <strong>for</strong>matted using program Pretty (shown in “Example:generating XML” on page 549), the result might be as follows:12345JohnSmith-JonesChapter 29. Producing XML output 557


The element names contain hyphens, but the content of the element Last-Name alsocontains a hyphen.Assuming that this XML document is the content of data item xmldoc, and thatcharcnt has been set to the length of the XML document, you can change all thehyphens in the element names to underscores but leave the element valuesunchanged by using the following code:1 xmldoc pic x(16384).1 charcnt comp-5 pic 9(5).1 pos comp-5 pic 9(5).1 tagstate comp-5 pic 9 value zero.1 quotestate comp-5 pic 9 value zero....dash-to-underscore.per<strong>for</strong>m varying pos from 1 by 1until pos > charcntif xmldoc(pos:1) = '


Part 6. Developing object-oriented programsChapter 30. Writing object-oriented programs 561Example: accounts. . . . . . . . . . . . 562Subclasses . . . . . . . . . . . . . 563Defining a class . . . . . . . . . . . . 564CLASS-ID paragraph <strong>for</strong> defining a class . . . 566REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class 566Example: external class-names and Javapackages . . . . . . . . . . . . . 567WORKING-STORAGE SECTION <strong>for</strong> definingclass instance data. . . . . . . . . . . 568Example: defining a class . . . . . . . . 569Defining a class instance method . . . . . . . 569METHOD-ID paragraph <strong>for</strong> defining a classinstance method . . . . . . . . . . . 570INPUT-OUTPUT SECTION <strong>for</strong> defining a classinstance method . . . . . . . . . . . 571DATA DIVISION <strong>for</strong> defining a class instancemethod . . . . . . . . . . . . . . 571PROCEDURE DIVISION <strong>for</strong> defining a classinstance method . . . . . . . . . . . 572Overriding an instance method . . . . . . 573Overloading an instance method . . . . . . 574Coding attribute (get and set) methods . . . . 575Example: coding a get method . . . . . 575Example: defining a method . . . . . . . 576Account class . . . . . . . . . . . 576Check class . . . . . . . . . . . . 577Defining a client . . . . . . . . . . . . 578REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a client 579DATA DIVISION <strong>for</strong> defining a client . . . . 580Choosing LOCAL-STORAGE orWORKING-STORAGE . . . . . . . . 581Comparing and setting object references . . . 581Invoking methods (INVOKE) . . . . . . . 582USING phrase <strong>for</strong> passing arguments . . . 583Example: passing con<strong>for</strong>ming object-referencearguments from a <strong>COBOL</strong> client . . . . . 584RETURNING phrase <strong>for</strong> obtaining a returnedvalue . . . . . . . . . . . . . . 585Invoking overridden superclass methods . . 586Creating and initializing instances of classes . . 586Instantiating Java classes . . . . . . . 587Instantiating <strong>COBOL</strong> classes . . . . . . 588Freeing instances of classes . . . . . . . . 588Example: defining a client . . . . . . . . 589Defining a subclass . . . . . . . . . . . 589CLASS-ID paragraph <strong>for</strong> defining a subclass 590REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a subclass 591WORKING-STORAGE SECTION <strong>for</strong> definingsubclass instance data . . . . . . . . . 592Defining a subclass instance method . . . . 592Example: defining a subclass (with methods) 592CheckingAccount class (subclass of Account) 593Defining a factory section . . . . . . . . . 594WORKING-STORAGE SECTION <strong>for</strong> definingfactory data . . . . . . . . . . . . . 594Defining a factory method . . . . . . . . 595Hiding a factory or static method . . . . 596Invoking factory or static methods . . . . 597Example: defining a factory (with methods) . . 597Account class . . . . . . . . . . . 598CheckingAccount class (subclass of Account) 600Check class . . . . . . . . . . . . 601TestAccounts client program . . . . . . 602Output produced by the TestAccounts clientprogram . . . . . . . . . . . . . 602Wrapping procedure-oriented <strong>COBOL</strong> programs 603Structuring OO applications . . . . . . . . 603Examples: <strong>COBOL</strong> applications that run usingthe java command. . . . . . . . . . . 604Displaying a message . . . . . . . . 604Echoing the input strings . . . . . . . 604Chapter 31. Communicating with Java methods 607Accessing JNI services . . . . . . . . . . 607Handling Java exceptions . . . . . . . . 608Example: handling Java exceptions . . . . 609Managing local and global references . . . . 610Deleting, saving, and freeing local references 610Java access controls . . . . . . . . . . 611Sharing data with Java . . . . . . . . . . 612Coding interoperable data types in <strong>COBOL</strong> andJava . . . . . . . . . . . . . . . 612Declaring arrays and strings <strong>for</strong> Java . . . . 613Manipulating Java arrays . . . . . . . . 614Example: processing a Java int array . . . 616Manipulating Java strings . . . . . . . . 616Example: J2EE client written in <strong>COBOL</strong> . . . . 619<strong>COBOL</strong> client (ConverterClient.cbl) . . . . . 619Java client (ConverterClient.java) . . . . . . 621© Copyright IBM Corp. 1991, 2009 559


560 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 30. Writing object-oriented programsWhen you write an object-oriented (OO) program, you have to determine whatclasses you need and the methods and data that the classes need to do their work.OO programs are based on objects (entities that encapsulate state and behavior) andtheir classes, methods, and data. A class is a template that defines the state and thecapabilities of an object. Usually a program creates and works with multiple objectinstances (or simply, instances) of a class, that is, multiple objects that are membersof that class. The state of each instance is stored in data known as instance data,and the capabilities of each instance are called instance methods. A class can definedata that is shared by all instances of the class, known as factory or static data, andmethods that are supported independently of any object instance, known as factoryor static methods.Using <strong>Enterprise</strong> <strong>COBOL</strong>, you can:v Define classes, with methods and data implemented in <strong>COBOL</strong>.v Create instances of Java and <strong>COBOL</strong> classes.v Invoke methods on Java and <strong>COBOL</strong> objects.v Write classes that inherit from Java classes or other <strong>COBOL</strong> classes.v Define and invoke overloaded methods.In <strong>Enterprise</strong> <strong>COBOL</strong> programs, you can call the services provided by the JavaNative Interface (JNI) to obtain Java-oriented capabilities in addition to the basicOO capabilities available directly in the <strong>COBOL</strong> language.In <strong>Enterprise</strong> <strong>COBOL</strong> classes, you can code CALL statements to interface withprocedural <strong>COBOL</strong> programs. Thus <strong>COBOL</strong> class definition syntax can beespecially useful <strong>for</strong> writing wrapper classes <strong>for</strong> procedural <strong>COBOL</strong> logic, enablingexisting <strong>COBOL</strong> code to be accessed from Java.Java code can create instances of <strong>COBOL</strong> classes, invoke methods of these classes,and can extend <strong>COBOL</strong> classes.It is recommended that you develop and run OO <strong>COBOL</strong> programs and Javaprograms in the z/<strong>OS</strong> UNIX environment.Restrictions:v <strong>COBOL</strong> class definitions and methods cannot contain EXEC SQL statements andcannot be compiled using the SQL compiler option.v <strong>COBOL</strong> class definitions and methods cannot contain EXEC CICS statements, andcannot be run in a CICS environment. They cannot be compiled using the CICScompiler option.“Example: accounts” on page 562RELATED TASKS“Defining a class” on page 564“Defining a class instance method” on page 569“Defining a client” on page 578“Defining a subclass” on page 589© Copyright IBM Corp. 1991, 2009 561


“Defining a factory section” on page 594Chapter 16, “Compiling, linking, and running OO applications,” on page 291<strong>Enterprise</strong> <strong>COBOL</strong> Compiler and Runtime Migration <strong>Guide</strong> (Upgrading IBM<strong>COBOL</strong> source programs)Example: accountsRELATED REFERENCESThe Java Language SpecificationConsider the example of a bank in which customers can open accounts and makedeposits to and withdrawals from their accounts. You could represent an accountby a general-purpose class, called Account. Because there are many customers,multiple instances of the Account class could exist simultaneously.After you determine the classes that you need, the next step is to determine themethods that the classes need to do their work. An Account class must provide thefollowing services:v Open the account.v Get the current balance.v Deposit to the account.v Withdraw from the account.v Report account status.The following methods <strong>for</strong> an Account class meet those needs:init Open an account and assign it an account number.getBalanceReturn the current balance of the account.credit Deposit a given sum to the account.debit Withdraw a given sum from the account.print Display account number and account balance.As you design an Account class and its methods, you discover the need <strong>for</strong> theclass to keep some instance data. Typically, an Account object needs the followinginstance data:v Account numberv Account balancevCustomer in<strong>for</strong>mation: name, address, home phone, work phone, social securitynumber, and so <strong>for</strong>thTo keep the example simple, however, it is assumed that the account number andaccount balance are the only instance data that the Account class needs.Diagrams are helpful when you design classes and methods. The followingdiagram depicts a first attempt at a design of the Account class:562 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The words in parentheses in the diagrams are the names of the instance data, andthe words that follow a number and colon are the names of the instance methods.The structure below shows how the classes relate to each other, and is known asthe inheritance hierarchy. The Account class inherits directly from the classjava.lang.Object.SubclassesIn the account example, Account is a general-purpose class. However, a bank couldhave many different types of accounts: checking accounts, savings accounts,mortgage loans, and so <strong>for</strong>th, all of which have all the general characteristics ofaccounts but could have additional characteristics not shared by all types ofaccounts.For example, a CheckingAccount class could have, in addition to the accountnumber and account balance that all accounts have, a check fee that applies to eachcheck written on the account. A CheckingAccount class also needs a method toprocess checks (that is, to read the amount, debit the payer, credit the payee, andso <strong>for</strong>th). So it makes sense to define CheckingAccount as a subclass of Account,and to define in the subclass the additional instance data and instance methodsthat the subclass needs.As you design the CheckingAccount class, you discover the need <strong>for</strong> a class thatmodels checks. An instance of class Check needs, at a minimum, instance data <strong>for</strong>payer, payee, and the check amount.Many additional classes (and database and transaction-processing logic) wouldneed to be designed in a real-world OO account system, but have been omitted tokeep the example simple. The updated inheritance diagram is shown below.Chapter 30. Writing object-oriented programs 563


A number and colon with no method-name following them indicate that themethod with that number is inherited from the superclass.Multiple inheritance: You cannot use multiple inheritance in OO <strong>COBOL</strong>applications. All classes that you define must have exactly one parent, andjava.lang.Object must be at the root of every inheritance hierarchy. The classstructure of any object-oriented system defined in an OO <strong>COBOL</strong> application isthus a tree.“Example: defining a method” on page 576Defining a classRELATED TASKS“Defining a class”“Defining a class instance method” on page 569“Defining a subclass” on page 589A <strong>COBOL</strong> class definition consists of an IDENTIFICATION DIVISION and ENVIRONMENTDIVISION, followed by an optional factory definition and optional object definition,followed by an END CLASS marker.Table 78. Structure of class definitionsSection Purpose SyntaxIDENTIFICATIONDIVISION(required)Name the class. Provideinheritance in<strong>for</strong>mation<strong>for</strong> it.“CLASS-ID paragraph <strong>for</strong> defining a class”on page 566 (required)AUTHOR paragraph (optional)INSTALLATION paragraph (optional)DATE-WRITTEN paragraph (optional)DATE-COMPILED paragraph (optional)564 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 78. Structure of class definitions (continued)Section Purpose SyntaxENVIRONMENTDIVISION(required)Factory definition(optional)Object definition(optional)Describe the computingenvironment. Relateclass-names used withinthe class definition to thecorresponding externalclass-names knownoutside the compilationunit.Define data to be sharedby all instances of theclass, and methodssupported independentlyof any object instance.Define instance data andinstance methods.CONFIGURATION SECTION (required)“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining aclass” on page 566 (required)SOURCE-COMPUTER paragraph (optional)OBJECT-COMPUTER paragraph (optional)SPECIAL-NAMES paragraph (optional)IDENTIFICATION DIVISION.FACTORY.DATA DIVISION.WORKING-STORAGE SECTION.* (Factory data here)PROCEDURE DIVISION.* (Factory methods here)END FACTORY.IDENTIFICATION DIVISION.OBJECT.DATA DIVISION.WORKING-STORAGE SECTION.* (Instance data here)PROCEDURE DIVISION.* (Instance methods here)END OBJECT.If you specify the SOURCE-COMPUTER, OBJECT-COMPUTER, orSPECIAL-NAMES paragraphsin a class CONFIGURATION SECTION, they apply to the entire class definitionincluding all methods that the class introduces.A class CONFIGURATION SECTION can consist of the same entries as a programCONFIGURATION SECTION, except that a class CONFIGURATION SECTION cannot containan INPUT-OUTPUT SECTION. You define an INPUT-OUTPUT SECTION only in theindividual methods that require it rather than defining it at the class level.As shown above, you define instance data and methods in the DATA DIVISION andPROCEDURE DIVISION, respectively, within the OBJECT paragraph of the classdefinition. In classes that require data and methods that are to be associated withthe class itself rather than with individual object instances, define a separate DATADIVISION and PROCEDURE DIVISION within the FACTORY paragraph of the classdefinition.Each <strong>COBOL</strong> class definition must be in a separate source file.“Example: defining a class” on page 569RELATED TASKS“WORKING-STORAGE SECTION <strong>for</strong> defining class instance data” on page 568“Defining a class instance method” on page 569“Defining a subclass” on page 589“Defining a factory section” on page 594“Describing the computing environment” on page 7Chapter 16, “Compiling, linking, and running OO applications,” on page 291RELATED REFERENCES<strong>COBOL</strong> class definition structure (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 30. Writing object-oriented programs 565


CLASS-ID paragraph <strong>for</strong> defining a classUse the CLASS-ID paragraph in the IDENTIFICATION DIVISION to name a class andprovide inheritance in<strong>for</strong>mation <strong>for</strong> it.Identification Division. RequiredClass-id. Account inherits Base. RequiredUse the CLASS-ID paragraph to identify these classes:v The class that you are defining (Account in the example above).v The immediate superclass from which the class that you are defining inherits itscharacteristics. The superclass can be implemented in Java or <strong>COBOL</strong>.In the example above, inherits Base indicates that the Account class inheritsmethods and data from the class known within the class definition as Base. It isrecommended that you use the name Base in your OO <strong>COBOL</strong> programs to referto java.lang.Object.A class-name must use single-byte characters and must con<strong>for</strong>m to the normalrules of <strong>for</strong>mation <strong>for</strong> a <strong>COBOL</strong> user-defined word.Use the REP<strong>OS</strong>ITORY paragraph in the CONFIGURATION SECTION of the ENVIRONMENTDIVISION to associate the superclass name (Base in the example) with the name ofthe superclass as it is known externally (java.lang.Object <strong>for</strong> Base). You canoptionally also specify the name of the class that you are defining (Account in theexample) in the REP<strong>OS</strong>ITORY paragraph and associate it with its correspondingexternal class-name.You must derive all classes directly or indirectly from the java.lang.Object class.RELATED TASKS“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class”RELATED REFERENCESCLASS-ID paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)User-defined words (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a classUse the REP<strong>OS</strong>ITORY paragraph to declare to the compiler that the specified wordsare class-names when you use them within a class definition, and to optionallyrelate the class-names to the corresponding external class-names (the class-namesas they are known outside the compilation unit).External class-names are case sensitive and must con<strong>for</strong>m to Java rules of<strong>for</strong>mation. For example, in the Account class definition you might code this:Environment Division.RequiredConfiguration Section.RequiredRepository.RequiredClass Base is "java.lang.Object" RequiredClass Account is "Account". OptionalThe REP<strong>OS</strong>ITORY paragraph entries indicate that the external class-names of theclasses referred to as Base and Account within the class definition arejava.lang.Object and Account, respectively.566 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In the REP<strong>OS</strong>ITORY paragraph, you must code an entry <strong>for</strong> each class-name that youexplicitly reference in the class definition. For example:v Basev A superclass from which the class that you are defining inheritsv The classes that you reference in methods within the class definitionIn a REP<strong>OS</strong>ITORY paragraph entry, you must specify the external class-name if thename contains non-<strong>COBOL</strong> characters. You must also specify the externalclass-name <strong>for</strong> any referenced class that is part of a Java package. For such a class,specify the external class-name as the fully qualified name of the package,followed by period (.), followed by the simple name of the Java class. Forexample, the Object class is part of the java.lang package, so specify its externalname as java.lang.Object as shown above.An external class-name that you specify in the REP<strong>OS</strong>ITORY paragraph must be analphanumeric literal that con<strong>for</strong>ms to the rules of <strong>for</strong>mation <strong>for</strong> a fully qualifiedJava class-name.|If you do not include the external class-name in a REP<strong>OS</strong>ITORY paragraph entry, theexternal class-name is <strong>for</strong>med from the class-name in the following manner:v The class-name is converted to uppercase.v Each hyphen is changed to zero.v The first character, if a digit, is changed:– 1-9 are changed to A-I.– 0 is changed to J.v Underscores are not changed.In the example above, class Account is known externally as Account (in mixedcase) because the external name is spelled using mixed case.You can optionally include in the REP<strong>OS</strong>ITORY paragraph an entry <strong>for</strong> the class thatyou are defining (Account in this example). You must include an entry <strong>for</strong> the classthat you are defining if the external class-name contains non-<strong>COBOL</strong> characters, orto specify a fully package-qualified class-name if the class is to be part of a Javapackage.“Example: external class-names and Java packages”RELATED TASKS“Declaring arrays and strings <strong>for</strong> Java” on page 613RELATED REFERENCESREP<strong>OS</strong>ITORY paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The Java Language Specification (Identifiers)The Java Language Specification (Packages)Example: external class-names and Java packagesThe following example shows how external class-names are determined fromentries in a REP<strong>OS</strong>ITORY paragraph.Chapter 30. Writing object-oriented programs 567


Environment division.Configuration section.Repository.Class Employee is "com.acme.Employee"Class JavaException is "java.lang.Exception"Class Orders.The local class-names (the class-names as used within the class definition), the Javapackages that contain the classes, and the associated external class-names are asshown in the table below.Local class-name Java package External class-nameEmployee com.acme com.acme.EmployeeJavaException java.lang java.lang.ExceptionOrders (unnamed) ORDERSThe external class-name (the name after the class-name and optional IS in theREP<strong>OS</strong>ITORY paragraph entry) is composed of the fully qualified name of thepackage (if any) followed by a period, followed by the simple name of the class.RELATED TASKS“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class” on page 566RELATED REFERENCESREP<strong>OS</strong>ITORY paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)WORKING-STORAGE SECTION <strong>for</strong> defining class instancedataUse the WORKING-STORAGE SECTION in the DATA DIVISION of the OBJECT paragraph todescribe the instance data that a <strong>COBOL</strong> class needs, that is, the data to be allocated<strong>for</strong> each instance of the class.The OBJECT keyword, which you must immediately precede with anIDENTIFICATION DIVISION declaration, indicates the beginning of the definitions ofthe instance data and instance methods <strong>for</strong> the class. For example, the definition ofthe instance data <strong>for</strong> the Account class might look like this:Identification division.Object.Data division.Working-storage section.01 AccountNumber pic 9(6).01 AccountBalance pic S9(9) value zero....End Object.The instance data is allocated when an object instance is created, and exists untilgarbage collection of the instance by the Java run time.You can initialize simple instance data by using VALUE clauses as shown above. Youcan initialize more complex instance data by coding customized methods to createand initialize instances of classes.<strong>COBOL</strong> instance data is equivalent to Java private nonstatic member data. Noother class or subclass (nor factory method in the same class, if any) can reference<strong>COBOL</strong> instance data directly. Instance data is global to all instance methods that568 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


the OBJECT paragraph defines. If you want to make instance data accessible fromoutside the OBJECT paragraph, define attribute (get or set) instance methods <strong>for</strong>doing so.The syntax of the WORKING-STORAGE SECTION <strong>for</strong> instance data declaration isgenerally the same as in a program, with these exceptions:v You cannot use the EXTERNAL attribute.v You can use the GLOBAL attribute, but it has no effect.RELATED TASKS“Creating and initializing instances of classes” on page 586“Freeing instances of classes” on page 588“Defining a factory method” on page 595“Coding attribute (get and set) methods” on page 575Example: defining a classThe following example shows a first attempt at the definition of the Account class,excluding method definitions.cbl dll,thread,pgmname(longmixed)Identification Division.Class-id. Account inherits Base.Environment Division.Configuration section.Repository.Class Base is "java.lang.Object"Class Account is "Account".*Identification division.Object.Data division.Working-storage section.01 AccountNumber pic 9(6).01 AccountBalance pic S9(9) value zero.*Procedure Division.** (Instance method definitions here)*End Object.*End class Account.RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291“Defining a client” on page 578Defining a class instance methodDefine <strong>COBOL</strong> instance methods in the PROCEDURE DIVISION of the OBJECT paragraphof a class definition. An instance method defines an operation that is supported <strong>for</strong>each object instance of a class.A <strong>COBOL</strong> instance method definition consists of four divisions (like a <strong>COBOL</strong>program), followed by an END METHOD marker.Chapter 30. Writing object-oriented programs 569


Table 79. Structure of instance method definitionsDivision Purpose SyntaxIDENTIFICATION(required)ENVIRONMENT(optional)DATA (optional)PROCEDURE(optional)Name a method.Relate the file-names usedin a method to thecorresponding file-namesknown to the operatingsystem.Define external files.Allocate a copy of thedata.Code the executablestatements to completethe service provided bythe method.“METHOD-ID paragraph <strong>for</strong> defining aclass instance method” (required)AUTHOR paragraph (optional)INSTALLATION paragraph (optional)DATE-WRITTEN paragraph (optional)DATE-COMPILED paragraph (optional)“INPUT-OUTPUT SECTION <strong>for</strong> defining aclass instance method” on page 571(optional)“DATA DIVISION <strong>for</strong> defining a classinstance method” on page 571 (optional)“PROCEDURE DIVISION <strong>for</strong> defining aclass instance method” on page 572(optional)Definition: The signature of a method consists of the name of the method and thenumber and type of its <strong>for</strong>mal parameters. (You define the <strong>for</strong>mal parameters of a<strong>COBOL</strong> method in the USING phrase of the method’s PROCEDURE DIVISION header.)Within a class definition, you do not need to make each method-name unique, butyou do need to give each method a unique signature. (You overload methods bygiving them the same name but a different signature.)<strong>COBOL</strong> instance methods are equivalent to Java public nonstatic methods.“Example: defining a method” on page 576RELATED TASKS“PROCEDURE DIVISION <strong>for</strong> defining a class instance method” on page 572“Overloading an instance method” on page 574“Overriding an instance method” on page 573“Invoking methods (INVOKE)” on page 582“Defining a subclass instance method” on page 592“Defining a factory method” on page 595METHOD-ID paragraph <strong>for</strong> defining a class instance methodUse the METHOD-ID paragraph to name an instance method. Immediately precedethe METHOD-ID paragraph with an IDENTIFICATION DIVISION declaration to indicatethe beginning of the method definition.For example, the definition of the credit method in the Account class begins likethis:Identification Division.Method-id. "credit".570 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Code the method-name as an alphanumeric or national literal. The method-name isprocessed in a case-sensitive manner and must con<strong>for</strong>m to the rules of <strong>for</strong>mation<strong>for</strong> a Java method-name.Other Java or <strong>COBOL</strong> methods or programs (that is, clients) use the method-nameto invoke a method.RELATED TASKS“Invoking methods (INVOKE)” on page 582“Using national data (Unicode) in <strong>COBOL</strong>” on page 126RELATED REFERENCESThe Java Language Specification (Meaning of method names)The Java Language Specification (Identifiers)METHOD-ID paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)INPUT-OUTPUT SECTION <strong>for</strong> defining a class instance methodThe ENVIRONMENT DIVISION of an instance method can have only one section, theINPUT-OUTPUT SECTION. This section relates the file-names used in a methoddefinition to the corresponding file-names as they are known to the operatingsystem.For example, if the Account class defined a method that read in<strong>for</strong>mation from afile, the Account class might have an INPUT-OUTPUT SECTION that is coded like this:Environment Division.Input-Output Section.File-Control.Select account-file Assign AcctFile.The syntax <strong>for</strong> the INPUT-OUTPUT SECTION of a method is the same as the syntax <strong>for</strong>the INPUT-OUTPUT SECTION of a program.RELATED TASKS“Describing the computing environment” on page 7RELATED REFERENCESINPUT-OUTPUT section (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)DATA DIVISION <strong>for</strong> defining a class instance methodThe DATA DIVISION of an instance method consists of any of the following foursections: FILE SECTION, LOCAL-STORAGE SECTION, WORKING-STORAGE SECTION, andLINKAGE SECTION.FILE SECTIONThe same as a program FILE SECTION, except that a method FILE SECTIONcan define EXTERNAL files only.LOCAL-STORAGE SECTIONA separate copy of the LOCAL-STORAGE data is allocated <strong>for</strong> each invocationof the method, and is freed on return from the method. The methodLOCAL-STORAGE SECTION is similar to a program LOCAL-STORAGE SECTION.If you specify the VALUE clause on a data item, the item is initialized to thatvalue on each invocation of the method.Chapter 30. Writing object-oriented programs 571


WORKING-STORAGE SECTIONA single copy of the WORKING-STORAGE data is allocated. The data persists inits last-used state until the run unit ends. The same copy of the data isused whenever the method is invoked, regardless of the invoking object orthread. The method WORKING-STORAGE SECTION is similar to a programWORKING-STORAGE SECTION.If you specify the VALUE clause on a data item, the item is initialized to thatvalue on the first invocation of the method. You can specify the EXTERNALclause <strong>for</strong> the data items.LINKAGE SECTIONThe same as a program LINKAGE SECTION.If you define a data item with the same name in both the DATA DIVISION of aninstance method and the DATA DIVISION of the OBJECT paragraph, a reference in themethod to that data-name refers only to the method data item. The method DATADIVISION takes precedence.RELATED TASKS“Describing the data” on page 13“Sharing data by using the EXTERNAL clause” on page 475RELATED REFERENCESDATA DIVISION overview (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)PROCEDURE DIVISION <strong>for</strong> defining a class instance methodCode the executable statements to implement the service that an instance methodprovides in the PROCEDURE DIVISION of the instance method.You can code most <strong>COBOL</strong> statements in the PROCEDURE DIVISION of a method thatyou can code in the PROCEDURE DIVISION of a program. You cannot, however, codethe following statements in a method:v ENTRYv EXIT PROGRAMv The following obsolete elements of Standard <strong>COBOL</strong> 85:– ALTER– GOTO without a specified procedure-name– SEGMENT-LIMIT– USE FOR DEBUGGINGAdditionally, because you must compile all <strong>COBOL</strong> class definitions with theTHREAD compiler option, you cannot use SORT or MERGE statements in a <strong>COBOL</strong>method.You can code the EXIT METHOD or GOBACK statement in an instance method to returncontrol to the invoking client. Both statements have the same effect. If you specifythe RETURNING phrase upon invocation of the method, the EXIT METHOD or GOBACKstatement returns the value of the data item to the invoking client.An implicit EXIT METHOD is generated as the last statement in the PROCEDUREDIVISION of each method.572 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


You can specify STOP RUN in a method; doing so terminates the entire run unitincluding all threads executing within it.You must terminate a method definition with an END METHOD marker. For example,the following statement marks the end of the credit method:End method "credit".USING phrase <strong>for</strong> obtaining passed arguments: Specify the <strong>for</strong>mal parameters toa method, if any, in the USING phrase of the method’s PROCEDURE DIVISION header.You must specify that the arguments are passed BY VALUE. Define each parameteras a level-01 or level-77 item in the method’s LINKAGE SECTION. The data type ofeach parameter must be one of the types that are interoperable with Java.RETURNING phrase <strong>for</strong> returning a value: Specify the data item to be returnedas the method result, if any, in the RETURNING phrase of the method’s PROCEDUREDIVISION header. Define the data item as a level-01 or level-77 item in the method’sLINKAGE SECTION. The data type of the return value must be one of the types thatare interoperable with Java.RELATED TASKS“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Overriding an instance method”“Overloading an instance method” on page 574“Comparing and setting object references” on page 581“Invoking methods (INVOKE)” on page 582Chapter 16, “Compiling, linking, and running OO applications,” on page 291RELATED REFERENCES“THREAD” on page 352The procedure division header (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Overriding an instance methodAn instance method that is defined in a subclass is said to override an inheritedinstance method that would otherwise be accessible in the subclass if the twomethods have the same signature.To override a superclass instance method m1 in a <strong>COBOL</strong> subclass, define aninstance method m1 in the subclass that has the same name and whose PROCEDUREDIVISION USING phrase (if any) has the same number and type of <strong>for</strong>malparameters as the superclass method has. (If the superclass method is implementedin Java, you must code <strong>for</strong>mal parameters that are interoperable with the datatypes of the corresponding Java parameters.) When a client invokes m1 on aninstance of the subclass, the subclass method rather than the superclass method isinvoked.For example, the Account class defines a method debit whose LINKAGE SECTIONand PROCEDURE DIVISION header look like this:Linkage section.01 inDebit pic S9(9) binary.Procedure Division using by value inDebit.If you define a CheckingAccount subclass and want it to have a debit method thatoverrides the debit method defined in the Account superclass, define the subclassmethod with exactly one input parameter also specified as pic S9(9) binary. IfaChapter 30. Writing object-oriented programs 573


client invokes debit using an object reference to a CheckingAccount instance, theCheckingAccount debit method (rather than the debit method in the Accountsuperclass) is invoked.The presence or absence of a method return value and the data type of the returnvalue used in the PROCEDURE DIVISION RETURNING phrase (if any) must be identicalin the subclass instance method and the overridden superclass instance method.An instance method must not override a factory method in a <strong>COBOL</strong> superclassnor a static method in a Java superclass.“Example: defining a method” on page 576RELATED TASKS“PROCEDURE DIVISION <strong>for</strong> defining a class instance method” on page 572“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Invoking methods (INVOKE)” on page 582“Invoking overridden superclass methods” on page 586“Defining a subclass” on page 589“Hiding a factory or static method” on page 596RELATED REFERENCESThe Java Language Specification (Inheritance, overriding, and hiding)Overloading an instance methodTwo methods that are supported in a class (whether defined in the class orinherited from a superclass) are said to be overloaded if they have the same namebut different signatures.You overload methods when you want to enable clients to invoke differentversions of a method, <strong>for</strong> example, to initialize data using different sets ofparameters.To overload a method, define a method whose PROCEDURE DIVISION USING phrase(if any) has a different number or type of <strong>for</strong>mal parameters than an identicallynamed method that is supported in the same class. For example, the Account classdefines an instance method init that has exactly one <strong>for</strong>mal parameter. TheLINKAGE SECTION and PROCEDURE DIVISION header of the init method look like this:Linkage section.01 inAccountNumber pic S9(9) binary.Procedure Division using by value inAccountNumber.Clients invoke this method to initialize an Account instance with a given accountnumber (and a default account balance of zero) by passing exactly one argumentthat matches the data type of inAccountNumber.But the Account class could define, <strong>for</strong> example, a second instance method initthat has an additional <strong>for</strong>mal parameter that allows the opening account balance toalso be specified. The LINKAGE SECTION and PROCEDURE DIVISION header of this initmethod could look like this:Linkage section.01 inAccountNumber pic S9(9) binary.01 inBalance pic S9(9) binary.Procedure Division using by value inAccountNumberinBalance.574 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Clients could invoke either init method by passing arguments that match thesignature of the desired method.The presence or absence of a method return value does not have to be consistent inoverloaded methods, and the data type of the return value given in the PROCEDUREDIVISION RETURNING phrase (if any) does not have to be identical in overloadedmethods.You can overload factory methods in exactly the same way that you overloadinstance methods.The rules <strong>for</strong> overloaded method definition and resolution of overloaded methodinvocations are based on the corresponding rules <strong>for</strong> Java.RELATED TASKS“Invoking methods (INVOKE)” on page 582“Defining a factory method” on page 595RELATED REFERENCESThe Java Language Specification (Overloading)Coding attribute (get and set) methodsYou can provide access to an instance variable X from outside the class in which Xis defined by coding accessor (get) and mutator (set) methods <strong>for</strong> X.Instance variables in <strong>COBOL</strong> are private: the class that defines instance variablesfully encapsulates them, and only the instance methods defined in the same OBJECTparagraph can access them directly. Normally a well-designed object-orientedapplication does not need to access instance variables from outside the class.<strong>COBOL</strong> does not directly support the concept of a public instance variable asdefined in Java and other object-oriented languages, nor the concept of a classattribute as defined by CORBA. (A CORBA attribute is an instance variable that hasan automatically generated get method <strong>for</strong> accessing the value of the variable, andan automatically generated set method <strong>for</strong> modifying the value of the variable ifthe variable is not read-only.)“Example: coding a get method”RELATED TASKS“WORKING-STORAGE SECTION <strong>for</strong> defining class instance data” on page 568“Processing the data” on page 19Example: coding a get methodThe following example shows the definition in the Account class of an instancemethod, getBalance, to return the value of the instance variable AccountBalance toa client. getBalance and AccountBalance are defined in the OBJECT paragraph of theAccount class definition.Identification Division.Class-id. Account inherits Base.* (ENVIRONMENT DIVISION not shown)* (FACTORY paragraph not shown)*Identification division.Object.Chapter 30. Writing object-oriented programs 575


Data division.Working-storage section.01 AccountBalance pic S9(9) value zero.* (Other instance data not shown)*Procedure Division.*Identification Division.Method-id. "getBalance".Data division.Linkage section.01 outBalance pic S9(9) binary.*Procedure Division returning outBalance.Move AccountBalance to outBalance.End method "getBalance".** (Other instance methods not shown)End Object.*End class Account.Example: defining a methodThe following example adds to the previous example the instance methoddefinitions of the Account class, and shows the definition of the Java Check class.(The previous example was “Example: defining a class” on page 569.)Account classcbl dll,thread,pgmname(longmixed)Identification Division.Class-id. Account inherits Base.Environment Division.Configuration section.Repository.Class Base is "java.lang.Object"Class Account is "Account".** (FACTORY paragraph not shown)*Identification division.Object.Data division.Working-storage section.01 AccountNumber pic 9(6).01 AccountBalance pic S9(9) value zero.*Procedure Division.** init method to initialize the account:Identification Division.Method-id. "init".Data division.Linkage section.01 inAccountNumber pic S9(9) binary.Procedure Division using by value inAccountNumber.Move inAccountNumber to AccountNumber.End method "init".** getBalance method to return the account balance:Identification Division.Method-id. "getBalance".Data division.Linkage section.576 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


01 outBalance pic S9(9) binary.Procedure Division returning outBalance.Move AccountBalance to outBalance.End method "getBalance".** credit method to deposit to the account:Identification Division.Method-id. "credit".Data division.Linkage section.01 inCredit pic S9(9) binary.Procedure Division using by value inCredit.Add inCredit to AccountBalance.End method "credit".** debit method to withdraw from the account:Identification Division.Method-id. "debit".Data division.Linkage section.01 inDebit pic S9(9) binary.Procedure Division using by value inDebit.Subtract inDebit from AccountBalance.End method "debit".** print method to display <strong>for</strong>matted account number and balance:Identification Division.Method-id. "print".Data division.Local-storage section.01 PrintableAccountNumber pic ZZZZZZ999999.01 PrintableAccountBalance pic $$$$,$$$,$$9CR.Procedure Division.Move AccountNumber to PrintableAccountNumberMove AccountBalance to PrintableAccountBalanceDisplay " Account: " PrintableAccountNumberDisplay " Balance: " PrintableAccountBalance.End method "print".*End Object.*End class Account.Check class/*** A Java class <strong>for</strong> check in<strong>for</strong>mation*/public class Check {private CheckingAccount payer;private Account payee;private intamount;public Check(CheckingAccount inPayer, Account inPayee, int inAmount) {payer=inPayer;payee=inPayee;amount=inAmount;}public int getAmount() {return amount;}public Account getPayee() {return payee;}}Chapter 30. Writing object-oriented programs 577


Defining a clientRELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291A program or method that requests services from one or more methods in a classis called a client of that class.In a <strong>COBOL</strong> or Java client, you can:v Create object instances of Java and <strong>COBOL</strong> classes.v Invoke instance methods on Java and <strong>COBOL</strong> objects.v Invoke <strong>COBOL</strong> factory methods and Java static methods.In a <strong>COBOL</strong> client, you can also call services provided by the Java Native Interface(JNI).A <strong>COBOL</strong> client program consists of the usual four divisions:Table 80. Structure of <strong>COBOL</strong> clientsDivision Purpose SyntaxIDENTIFICATION(required)ENVIRONMENT(required)DATA (optional)PROCEDURE(optional)Name a client.Describe the computingenvironment. Relateclass-names used in theclient to thecorresponding externalclass-names knownoutside the compilationunit.Describe the data that theclient needs.Create instances of classes,manipulate objectreference data items, andinvoke methods.Code as usual, except that a client programmust be:vvRecursive (declared RECURSIVE in thePROGRAM-ID paragraph)Thread-enabled (compiled with theTHREAD option, and con<strong>for</strong>ming to thecoding guidelines <strong>for</strong> threadedapplications)CONFIGURATION SECTION (required)“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining aclient” on page 579 (required)“DATA DIVISION <strong>for</strong> defining a client” onpage 580 (optional)Code using INVOKE, IF, and SET statements.Because you must compile all <strong>COBOL</strong> programs that contain object-oriented syntaxor that interoperate with Java with the THREAD compiler option, you cannot use thefollowing language elements in a <strong>COBOL</strong> client:v SORT or MERGE statementsv Nested programsAny programs that you compile with the THREAD compiler option must berecursive. You must specify the RECURSIVE clause in the PROGRAM-ID paragraph ofeach OO <strong>COBOL</strong> client program.578 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Example: defining a client” on page 589RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291Chapter 27, “Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading,” on page 493Chapter 31, “Communicating with Java methods,” on page 607“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Creating and initializing instances of classes” on page 586“Comparing and setting object references” on page 581“Invoking methods (INVOKE)” on page 582“Invoking factory or static methods” on page 597RELATED REFERENCES“THREAD” on page 352REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a clientUse the REP<strong>OS</strong>ITORY paragraph to declare to the compiler that the specified wordsare class-names when you use them in a <strong>COBOL</strong> client, and to optionally relate theclass-names to the corresponding external class-names (the class-names as they areknown outside the compilation unit).External class-names are case sensitive, and must con<strong>for</strong>m to Java rules of<strong>for</strong>mation. For example, in a client program that uses the Account and Checkclasses you might code this:Environment division. RequiredConfiguration section. RequiredSource-Computer. IBM-390.Object-Computer. IBM-390.Repository.Class Account is "Account"Class Check is "Check".RequiredThe REP<strong>OS</strong>ITORY paragraph entries indicate that the external class-names of theclasses referred to as Account and Check within the client are Account and Check,respectively.In the REP<strong>OS</strong>ITORY paragraph, you must code an entry <strong>for</strong> each class-name that youexplicitly reference in the client. In a REP<strong>OS</strong>ITORY paragraph entry, you must specifythe external class-name if the name contains non-<strong>COBOL</strong> characters.You must specify the external class-name <strong>for</strong> any referenced class that is part of aJava package. For such a class, specify the external class-name as the fully qualifiedname of the package, followed by period (.), followed by the simple name of theJava class.An external class-name that you specify in the REP<strong>OS</strong>ITORY paragraph must be analphanumeric literal that con<strong>for</strong>ms to the rules of <strong>for</strong>mation <strong>for</strong> a fully qualifiedJava class-name.If you do not include the external class-name in a REP<strong>OS</strong>ITORY paragraph entry, theexternal class-name is <strong>for</strong>med from the class-name in the same manner as it iswhen an external class-name is not included in a REP<strong>OS</strong>ITORY paragraph entry in aclass definition. In the example above, class Account and class Check are knownexternally as Account and Check (in mixed case), respectively, because the externalnames are spelled using mixed case.Chapter 30. Writing object-oriented programs 579


The SOURCE-COMPUTER, OBJECT-COMPUTER, and SPECIAL-NAMES paragraphs of theCONFIGURATION SECTION are optional.RELATED TASKS“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class” on page 566RELATED REFERENCESREP<strong>OS</strong>ITORY paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The Java Language Specification (Identifiers)The Java Language Specification (Packages)DATA DIVISION <strong>for</strong> defining a clientYou can use any of the sections of the DATA DIVISION to describe the data that theclient needs.Data Division.Local-storage section.01 anAccount usage object reference Account.01 aCheckingAccount usage object reference CheckingAccount.01 aCheck usage object reference Check.01 payee usage object reference Account....Because a client references classes, it needs one or more special data items calledobject references, that is, references to instances of those classes. All requests toinstance methods require an object reference to an instance of a class in which themethod is supported (that is, either defined or available by inheritance). You codeobject references to refer to instances of Java classes using the same syntax as youuse to refer to instances of <strong>COBOL</strong> classes. In the example above, the phrase usageobject reference indicates an object reference data item.All four object references in the code above are called typed object referencesbecause a class-name appears after the OBJECT REFERENCE phrase. A typed objectreference can refer only to an instance of the class named in the OBJECT REFERENCEphrase or to one of its subclasses. Thus anAccount can refer to instances of theAccount class or one of its subclasses, but cannot refer to instances of any otherclass. Similarly, aCheck can refer only to instances of the Check class or anysubclasses that it might have.Another type of object reference, not shown above, does not have a class-nameafter the OBJECT REFERENCE phrase. Such a reference is called a universal objectreference, which means that it can refer to instances of any class. Avoid codinguniversal object references, because they are interoperable with Java in only verylimited circumstances (when used in the RETURNING phrase of the INVOKEclass-name NEW . . . statement).You must define, in the REP<strong>OS</strong>ITORY paragraph of the CONFIGURATION SECTION,class-names that you use in the OBJECT REFERENCE phrase.RELATED TASKS“Choosing LOCAL-STORAGE or WORKING-STORAGE” on page 581“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Invoking methods (INVOKE)” on page 582“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a client” on page 579580 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED REFERENCESRETURNING phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Choosing LOCAL-STORAGE or WORKING-STORAGEYou can in general use the WORKING-STORAGE SECTION to define working data that aclient program needs. However, if the program could simultaneously run onmultiple threads, you might instead want to define the data in the LOCAL-STORAGESECTION.Each thread has access to a separate copy of LOCAL-STORAGE data but shares accessto a single copy of WORKING-STORAGE data. If you define the data in theWORKING-STORAGE SECTION, you need to synchronize access to the data or ensurethat no two threads can access it simultaneously.RELATED TASKSChapter 27, “Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading,” on page 493Comparing and setting object referencesYou can compare object references by coding conditional statements or a call to theJNI service IsSameObject, and you can set object references by using the SETstatement.For example, code either IF statement below to check whether the object referenceanAccount refers to no object instance:If anAccount = Null ...If anAccount = Nulls ...You can code a call to IsSameObject to check whether two object references, object1and object2, refer to the same object instance or whether each refers to no objectinstance. To ensure that the arguments and return value are interoperable withJava and to establish addressability to the callable service, code the following datadefinitions and statements be<strong>for</strong>e the call to IsSameObject:Local-storage Section....01 is-same Pic X.88 is-same-false Value X'00'.88 is-same-true Value X'01' Through X'FF'.Linkage Section.Copy JNI.Procedure Division.Set Address Of JNIEnv To JNIEnvPtrSet Address Of JNINativeInterface To JNIEnvCall IsSameObject Using By Value JNIEnvPtr object1 object2Returning is-sameIf is-same-true ...Within a method you can check whether an object reference refers to the objectinstance on which the method was invoked by coding a call to IsSameObject thatcompares the object reference and SELF.You can instead invoke the Java equals method (inherited from java.lang.Object) todetermine whether two object references refer to the same object instance.You can make an object reference refer to no object instance by using the SETstatement. For example:Set anAccount To Null.Chapter 30. Writing object-oriented programs 581


You can also make one object reference refer to the same instance as another objectreference does by using the SET statement. For example:Set anotherAccount To anAccount.This SET statement causes anotherAccount to refer to the same object instance asanAccount does. If the receiver (anotherAccount) is a universal object reference, thesender (anAccount) can be either a universal or a typed object reference. If thereceiver is a typed object reference, the sender must be a typed object referencebound to the same class as the receiver or to one of its subclasses.Within a method you can make an object reference refer to the object instance onwhich the method was invoked by setting it to SELF. For example:Set anAccount To Self.RELATED TASKS“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Accessing JNI services” on page 607RELATED REFERENCESThe Java Native Interface (IsSameObject)Invoking methods (INVOKE)In a Java client, you can create object instances of classes that were implemented in<strong>COBOL</strong> and invoke methods on those objects using standard Java syntax. In a<strong>COBOL</strong> client, you can invoke methods that are defined in Java or <strong>COBOL</strong> classesby coding the INVOKE statement.Invoke Account "createAccount"using by value 123456returning anAccountInvoke anAccount "credit" using by value 500.The first example INVOKE statement above uses the class-name Account to invoke amethod called createAccount. This method must be either defined or inherited inthe Account class, and must be one of the following types:v A Java static methodv A <strong>COBOL</strong> factory methodThe phrase using by value 123456 indicates that 123456 is an input argument tothe method, and is passed by value. The input argument 123456 and the returneddata item anAccount must con<strong>for</strong>m to the definition of the <strong>for</strong>mal parameters andreturn type, respectively, of the (possibly overloaded) createAccount method.The second INVOKE statement uses the returned object reference anAccount toinvoke the instance method credit, which is defined in the Account class. Theinput argument 500 must con<strong>for</strong>m to the definition of the <strong>for</strong>mal parameters of the(possibly overloaded) credit method.Code the name of the method to be invoked either as a literal or as an identifierwhose value at run time matches the method-name in the signature of the targetmethod. The method-name must be an alphanumeric or national literal or acategory alphabetic, alphanumeric, or national data item, and is interpreted in acase-sensitive manner.582 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


When you code an INVOKE statement using an object reference (as in the secondexample statement above), the statement begins with one of the following two<strong>for</strong>ms:Invoke objRef "literal-name" ...Invoke objRef identifier-name ...When the method-name is an identifier, you must define the object reference(objRef) as USAGE OBJECT REFERENCE with no specified type, that is, as a universalobject reference.If an invoked method is not supported in the class to which the object referencerefers, a severity-3 Language Environment condition is raised at run time unlessyou code the ON EXCEPTION phrase in the INVOKE statement.You can use the optional scope terminator END-INVOKE with the INVOKE statement.The INVOKE statement does not set the RETURN-CODE special register.RELATED TASKS“USING phrase <strong>for</strong> passing arguments”“RETURNING phrase <strong>for</strong> obtaining a returned value” on page 585“PROCEDURE DIVISION <strong>for</strong> defining a class instance method” on page 572“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Invoking overridden superclass methods” on page 586“Invoking factory or static methods” on page 597RELATED REFERENCESINVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)USING phrase <strong>for</strong> passing argumentsIf you pass arguments to a method, specify the arguments in the USING phrase ofthe INVOKE statement. Code the data type of each argument so that it con<strong>for</strong>ms tothe type of the corresponding <strong>for</strong>mal parameter in the intended target method.Table 81. Con<strong>for</strong>mance of arguments in a <strong>COBOL</strong> client<strong>Programming</strong>language of thetarget methodIs the argumentan objectreference?Then code the DATADIVISION definition ofthe argument as:<strong>COBOL</strong> No The same as thedefinition of thecorresponding <strong>for</strong>malparameterJava No Interoperable with thecorresponding Javaparameter<strong>COBOL</strong> or Java Yes An object reference that istyped to the same class asthe correspondingparameter in the targetmethodRestrictionIn a <strong>COBOL</strong> client (unlikein a Java client), the classof an argument cannot bea subclass of the class ofthe correspondingparameter.Chapter 30. Writing object-oriented programs 583


See the example referenced below <strong>for</strong> a way to make an object-reference argumentcon<strong>for</strong>m to the type of a corresponding <strong>for</strong>mal parameter by using the SETstatement or the REDEFINES clause.“Example: passing con<strong>for</strong>ming object-reference arguments from a <strong>COBOL</strong> client”If the target method is overloaded, the data types of the arguments are used toselect from among the methods that have the same name.You must specify that the arguments are passed BY VALUE. In other words, thearguments are not affected by any change to the corresponding <strong>for</strong>mal parametersin the invoked method.The data type of each argument must be one of the types that are interoperablewith Java.RELATED TASKS“PROCEDURE DIVISION <strong>for</strong> defining a class instance method” on page 572“Overloading an instance method” on page 574“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Passing data” on page 465RELATED REFERENCESINVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SET statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)REDEFINES clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: passing con<strong>for</strong>ming object-reference arguments from a<strong>COBOL</strong> clientThe following example shows a way to make an object-reference argument in a<strong>COBOL</strong> client con<strong>for</strong>m to the expected class of the corresponding <strong>for</strong>mal parameterin an invoked method.Class C defines a method M that has one parameter, a reference to an object ofclass java.lang.Object:...Class-id. C inherits Base....Repository.Class Base is "java.lang.Object"Class JavaObject is "java.lang.Object".Identification division.Factory....Procedure Division.Identification Division.Method-id. "M".Data division.Linkage section.01 obj object reference JavaObject.Procedure Division using by value obj....To invoke method M, a <strong>COBOL</strong> client must pass an argument that is a reference toan object of class java.lang.Object. The client below defines a data item aString,which cannot be passed as an argument to M because aString is a reference to anobject of class java.lang.String. The client first uses a SET statement to assign584 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


aString to a data item, anObj, that is a reference to an object of classjava.lang.Object. (This SET statement is legal because java.lang.String is a subclassof java.lang.Object.) The client then passes anObj as the argument to M....Repository.Class jstring is "java.lang.String"Class JavaObject is "java.lang.Object".Data division.Local-storage section.01 aString object reference jstring.01 anObj object reference JavaObject.*Procedure division.. . . (statements here assign a value to aString)Set anObj to aStringInvoke C "M"using by value anObjInstead of using a SET statement to obtain anObj as a reference to an object of classjava.lang.Object, the client could define aString and anObj with the REDEFINESclause as follows:...01 aString object reference jstring.01 anObj redefines aString object reference JavaObject.After the client assigns a value to data item aString (that is, a valid reference to anobject of class java.lang.String), anObj can be passed as the argument to M. For anexample of the use of the REDEFINES clause to obtain argument con<strong>for</strong>mance, seethe example referenced below.“Example: J2EE client written in <strong>COBOL</strong>” on page 619RELATED TASKS“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“PROCEDURE DIVISION <strong>for</strong> defining a class instance method” on page 572RELATED REFERENCESINVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)SET statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)REDEFINES clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)RETURNING phrase <strong>for</strong> obtaining a returned valueIf a data item is to be returned as the method result, specify the item in theRETURNING phrase of the INVOKE statement. Define the returned item in the DATADIVISION of the client.The item that you specify in the RETURNING phrase of the INVOKE statement mustcon<strong>for</strong>m to the type returned by the target method, as shown in the table below.Table 82. Con<strong>for</strong>mance of the returned data item in a <strong>COBOL</strong> client<strong>Programming</strong>language of thetarget methodIs the returned iteman object reference?Then code the DATA DIVISION definition ofthe returned item as:<strong>COBOL</strong> No The same as the definition of the RETURNINGitem in the target methodJava No Interoperable with the returned Java dataitemChapter 30. Writing object-oriented programs 585


Table 82. Con<strong>for</strong>mance of the returned data item in a <strong>COBOL</strong> client (continued)<strong>Programming</strong>language of thetarget methodIs the returned iteman object reference?Then code the DATA DIVISION definition ofthe returned item as:<strong>COBOL</strong> or Java Yes An object reference that is typed to thesame class as the object reference that isreturned by the target methodIn all cases, the data type of the returned value must be one of the types that areinteroperable with Java.RELATED TASKS“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612RELATED REFERENCESINVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Invoking overridden superclass methodsSometimes within a class you need to invoke an overridden superclass methodinstead of invoking a method that has the same signature and is defined in thecurrent class.For example, suppose that the CheckingAccount class overrides the debit instancemethod defined in its immediate superclass, Account. You could invoke theAccount debit method within a method in the CheckingAccount class by codingthis statement:Invoke Super "debit" Using By Value amount.You would define amount as PIC S9(9) BINARY to match the signature of the debitmethods.The CheckingAccount class overrides the print method that is defined in theAccount class. Because the print method has no <strong>for</strong>mal parameters, a method inthe CheckingAccount class could invoke the superclass print method with thisstatement:Invoke Super "print".The keyword SUPER indicates that you want to invoke a superclass method ratherthan a method in the current class. (SUPER is an implicit reference to the object usedin the invocation of the currently executing method.)“Example: accounts” on page 562RELATED TASKS“Overriding an instance method” on page 573RELATED REFERENCESINVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Creating and initializing instances of classesBe<strong>for</strong>e you can use the instance methods that are defined in a Java or <strong>COBOL</strong>class, you must first create an instance of the class.586 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


To create a new instance of class class-name and to obtain a reference object-referenceto the created object, code a statement of the following <strong>for</strong>m, where object-referenceis defined in the DATA DIVISION of the client:INVOKE class-name NEW...RETURNING object-referenceWhen you code the INVOKE ...NEWstatement within a method, and the use ofthe returned object reference is not limited to the duration of the methodinvocation, you must convert the returned object reference to a global reference bycalling the JNI service NewGlobalRef:Call NewGlobalRef using by value JNIEnvPtr object-referencereturning object-referenceIf you do not call NewGlobalRef, the returned object reference is only a localreference, which means that it is automatically freed after the method returns.RELATED TASKS“Instantiating Java classes”“Instantiating <strong>COBOL</strong> classes” on page 588“Accessing JNI services” on page 607“Managing local and global references” on page 610“DATA DIVISION <strong>for</strong> defining a client” on page 580“Invoking methods (INVOKE)” on page 582“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612RELATED REFERENCESINVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Instantiating Java classesTo instantiate a Java class, invoke any parameterized constructor that the classsupports by coding the USING phrase in the INVOKE ...NEWstatementimmediately be<strong>for</strong>e the RETURNING phrase, passing BY VALUE the number and typesof arguments that match the signature of the constructor.The data type of each argument must be one of the types that are interoperablewith Java. To invoke the default (parameterless) constructor, omit the USING phrase.For example, to create an instance of the Check class, initialize its instance data,and obtain reference aCheck to the Check instance created, you could code thisstatement in a <strong>COBOL</strong> client:Invoke Check Newusing by value aCheckingAccount, payee, 125returning aCheckRELATED TASKS“Invoking methods (INVOKE)” on page 582“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612RELATED REFERENCESVALUE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)INVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 30. Writing object-oriented programs 587


Instantiating <strong>COBOL</strong> classesTo instantiate a <strong>COBOL</strong> class, you can specify either a typed or universal objectreference in the RETURNING phrase of the INVOKE ...NEWstatement. However,you cannot code the USING phrase: the instance data is initialized as specified in theVALUE clauses in the class definition.Thus the INVOKE ...NEWstatement is useful <strong>for</strong> instantiating <strong>COBOL</strong> classes thathave only simple instance data. For example, the following statement creates aninstance of the Account class, initializes the instance data as specified in VALUEclauses in the WORKING-STORAGE SECTION of the OBJECT paragraph of the Accountclass definition, and provides reference outAccount to the new instance:Invoke Account New returning outAccountTo make it possible to initialize <strong>COBOL</strong> instance data that cannot be initializedusing VALUE clauses alone, when designing a <strong>COBOL</strong> class you must define aparameterized creation method in the FACTORY paragraph and a parameterizedinitialization method in the OBJECT paragraph:1. In the parameterized factory creation method, do these steps:a. Code INVOKE class-name NEW RETURNING objectRef to create an instance ofclass-name and to give initial values to the instance data items that haveVALUE clauses.b. Invoke the parameterized initialization method on the instance (objectRef),passing BY VALUE the arguments that were supplied to the factory method.2. In the initialization method, code logic to complete the instance datainitialization using the values supplied through the <strong>for</strong>mal parameters.To create an instance of the <strong>COBOL</strong> class and properly initialize it, the clientinvokes the parameterized factory method, passing BY VALUE the desiredarguments. The object reference returned to the client is a local reference. If theclient code is within a method, and the use of the returned object reference is notlimited to the duration of that method, the client code must convert the returnedobject reference to a global reference by calling the JNI service NewGlobalRef.“Example: defining a factory (with methods)” on page 597RELATED TASKS“Accessing JNI services” on page 607“Managing local and global references” on page 610“Invoking methods (INVOKE)” on page 582“Defining a factory section” on page 594RELATED REFERENCESVALUE clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)INVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Freeing instances of classesYou do not need to take any action to free individual object instances of any class.No syntax is available <strong>for</strong> doing so. The Java runtime system automaticallyper<strong>for</strong>ms garbage collection, that is, it reclaims the memory <strong>for</strong> objects that are nolonger in use.588 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


There could be times, however, when you need to explicitly free local or globalreferences to objects within a native <strong>COBOL</strong> client in order to permit garbagecollection of the referenced objects to occur.RELATED TASKS“Managing local and global references” on page 610Example: defining a clientThe following example shows a small client program of the Account class.The program does this:v Invokes a factory method createAccount to create an Account instance with adefault balance of zerov Invokes the instance method credit to deposit $500 to the new accountv Invokes the instance method print to display the account status(The Account class was shown in “Example: defining a method” on page 576.)cbl dll,thread,pgmname(longmixed)Identification division.Program-id. "TestAccounts" recursive.Environment division.Configuration section.Repository.Class Account is "Account".Data Division.* Working data is declared in LOCAL-STORAGE instead of* WORKING-STORAGE so that each thread has its own copy:Local-storage section.01 anAccount usage object reference Account.*Procedure division.Test-Account-section.Display "Test Account class"* Create account 123456 with 0 balance:Invoke Account "createAccount"using by value 123456returning anAccount* Deposit 500 to the account:Invoke anAccount "credit" using by value 500Invoke anAccount "print"Display space*Stop Run.End program "TestAccounts".“Example: defining a factory (with methods)” on page 597Defining a subclassRELATED TASKS“Defining a factory method” on page 595“Invoking factory or static methods” on page 597Chapter 16, “Compiling, linking, and running OO applications,” on page 291You can make a class (called a subclass, derived class, or child class) aspecialization of another class (called a superclass, base class, or parent class).Chapter 30. Writing object-oriented programs 589


A subclass inherits the methods and instance data of its superclasses, and is relatedto its superclasses by an is-a relationship. For example, if subclass P inherits fromsuperclass Q, and subclass Q inherits from superclass S, then an instance of P is aninstance of Q and also (by transitivity) an instance of S. An instance of P inheritsthe methods and data of Q and S.Using subclasses has several advantages:v Reuse of code: Through inheritance, a subclass can reuse methods that alreadyexist in a superclass.v Specialization: In a subclass you can add new methods to handle cases that thesuperclass does not handle. You can also add new data items that the superclassdoes not need.v Change in action: A subclass can override a method that it inherits from asuperclass by defining a method of the same signature as that in the superclass.When you override a method, you might make only a few minor changes orcompletely change what the method does.Restriction: You cannot use multiple inheritance in your <strong>COBOL</strong> programs. Each<strong>COBOL</strong> class that you define must have exactly one immediate superclass that isimplemented in Java or <strong>COBOL</strong>, and each class must be derived directly orindirectly from java.lang.Object. The semantics of inheritance are as defined byJava.The structure and syntax of a subclass definition are identical to those of a classdefinition: Define instance data and methods in the DATA DIVISION and PROCEDUREDIVISION, respectively, within the OBJECT paragraph of the subclass definition. Insubclasses that require data and methods that are to be associated with thesubclass itself rather than with individual object instances, define a separate DATADIVISION and PROCEDURE DIVISION within the FACTORY paragraph of the subclassdefinition.<strong>COBOL</strong> instance data is private. A subclass can access the instance data of a<strong>COBOL</strong> superclass only if the superclass defines attribute (get or set) instancemethods <strong>for</strong> doing so.“Example: accounts” on page 562“Example: defining a subclass (with methods)” on page 592RELATED TASKS“Defining a class” on page 564“Overriding an instance method” on page 573“Coding attribute (get and set) methods” on page 575“Defining a subclass instance method” on page 592“Defining a factory section” on page 594RELATED REFERENCESThe Java Language Specification (Inheritance, overriding, and hiding)<strong>COBOL</strong> class definition structure (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)CLASS-ID paragraph <strong>for</strong> defining a subclassUse the CLASS-ID paragraph to name the subclass and indicate from whichimmediate Java or <strong>COBOL</strong> superclass it inherits its characteristics.Identification Division.RequiredClass-id. CheckingAccount inherits Account. Required590 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In the example above, CheckingAccount is the subclass being defined.CheckingAccount inherits all the methods of the class known within the subclassdefinition as Account. CheckingAccount methods can access Account instance dataonly if the Account class provides attribute (get or set) methods <strong>for</strong> doing so.You must specify the name of the immediate superclass in the REP<strong>OS</strong>ITORYparagraph in the CONFIGURATION SECTION of the ENVIRONMENT DIVISION. You canoptionally associate the superclass name with the name of the class as it is knownexternally. You can also specify the name of the subclass that you are defining(here, CheckingAccount) in the REP<strong>OS</strong>ITORY paragraph and associate it with itscorresponding external class-name.RELATED TASKS“CLASS-ID paragraph <strong>for</strong> defining a class” on page 566“Coding attribute (get and set) methods” on page 575“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a subclass”REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a subclassUse the REP<strong>OS</strong>ITORY paragraph to declare to the compiler that the specified wordsare class-names when you use them within a subclass definition, and to optionallyrelate the class-names to the corresponding external class-names (the class-namesas they are known outside the compilation unit).For example, in the CheckingAccount subclass definition, these REP<strong>OS</strong>ITORYparagraph entries indicate that the external class-names of the classes referred to asCheckingAccount, Check, and Account within the subclass definition areCheckingAccount, Check, and Account, respectively.Environment Division.RequiredConfiguration Section.RequiredRepository.RequiredClass CheckingAccount is "CheckingAccount" OptionalClass Check is "Check" RequiredClass Account is "Account". RequiredIn the REP<strong>OS</strong>ITORY paragraph, you must code an entry <strong>for</strong> each class-name that youexplicitly reference in the subclass definition. For example:v A user-defined superclass from which the subclass that you are defining inheritsv The classes that you reference in methods within the subclass definitionThe rules <strong>for</strong> coding REP<strong>OS</strong>ITORY paragraph entries in a subclass are identical tothose <strong>for</strong> coding REP<strong>OS</strong>ITORY paragraph entries in a class.RELATED TASKS“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class” on page 566RELATED REFERENCESREP<strong>OS</strong>ITORY paragraph (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 30. Writing object-oriented programs 591


WORKING-STORAGE SECTION <strong>for</strong> defining subclass instancedataUse the WORKING-STORAGE SECTION in the DATA DIVISION of the subclass OBJECTparagraph to describe any instance data that the subclass needs in addition to theinstance data defined in its superclasses. Use the same syntax that you use todefine instance data in a class.For example, the definition of the instance data <strong>for</strong> the CheckingAccount subclassof the Account class might look like this:Identification division.Object.Data division.Working-storage section.01 CheckFee pic S9(9) value 1....End Object.RELATED TASKS“WORKING-STORAGE SECTION <strong>for</strong> defining class instance data” on page 568Defining a subclass instance methodA subclass inherits the methods of its superclasses. In a subclass definition, youcan override any instance method that the subclass inherits by defining an instancemethod with the same signature as the inherited method. You can also define newmethods that the subclass needs.The structure and syntax of a subclass instance method are identical to those of aclass instance method. Define subclass instance methods in the PROCEDURE DIVISIONof the OBJECT paragraph of the subclass definition.“Example: defining a subclass (with methods)”RELATED TASKS“Defining a class instance method” on page 569“Overriding an instance method” on page 573“Overloading an instance method” on page 574Example: defining a subclass (with methods)The following example shows the instance method definitions <strong>for</strong> theCheckingAccount subclass of the Account class.The processCheck method invokes the Java instance methods getAmount andgetPayee of the Check class to get the check data. It invokes the credit and debitinstance methods inherited from the Account class to credit the payee and debitthe payer of the check.The print method overrides the print instance method defined in the Accountclass. It invokes the overridden print method to display account status, and alsodisplays the check fee. CheckFee is an instance data item defined in the subclass.(The Account class was shown in “Example: defining a method” on page 576.)592 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


CheckingAccount class (subclass of Account)cbl dll,thread,pgmname(longmixed)Identification Division.Class-id. CheckingAccount inherits Account.Environment Division.Configuration section.Repository.Class CheckingAccount is "CheckingAccount"Class Checkis "Check"Class Account is "Account".** (FACTORY paragraph not shown)*Identification division.Object.Data division.Working-storage section.01 CheckFee pic S9(9) value 1.Procedure Division.** processCheck method to get the check amount and payee,* add the check fee, and invoke inherited methods debit* to debit the payer and credit to credit the payee:Identification Division.Method-id. "processCheck".Data division.Local-storage section.01 amount pic S9(9) binary.01 payee usage object reference Account.Linkage section.01 aCheck usage object reference Check.*Procedure Division using by value aCheck.Invoke aCheck "getAmount" returning amountInvoke aCheck "getPayee" returning payeeInvoke payee "credit" using by value amountAdd checkFee to amountInvoke self "debit" using by value amount.End method "processCheck".** print method override to display account status:Identification Division.Method-id. "print".Data division.Local-storage section.01 printableFee pic $$,$$$,$$9.Procedure Division.Invoke super "print"Move CheckFee to printableFeeDisplay " Check fee: " printableFee.End method "print".*End Object.*End class CheckingAccount.RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291“Invoking methods (INVOKE)” on page 582“Overriding an instance method” on page 573“Invoking overridden superclass methods” on page 586Chapter 30. Writing object-oriented programs 593


Defining a factory sectionUse the FACTORY paragraph in a class definition to define data and methods thatare to be associated with the class itself rather than with individual objectinstances.<strong>COBOL</strong> factory data is equivalent to Java private static data. A single copy of thedata is instantiated <strong>for</strong> the class and is shared by all object instances of the class.You most commonly use factory data when you want to gather data from all theinstances of a class. For example, you could define a factory data item to keep arunning total of the number of instances of the class that are created.<strong>COBOL</strong> factory methods are equivalent to Java public static methods. The methodsare supported by the class independently of any object instance. You mostcommonly use factory methods to customize object creation when you cannot useVALUE clauses alone to initialize instance data.By contrast, you use the OBJECT paragraph in a class definition to define data thatis created <strong>for</strong> each object instance of the class, and methods that are supported <strong>for</strong>each object instance of the class.A factory definition consists of three divisions, followed by an END FACTORYstatement:Table 83. Structure of factory definitionsDivision Purpose SyntaxIDENTIFICATION(required)DATA (optional)PROCEDURE(optional)Identify the start of thefactory definition.Describe data that isallocated once <strong>for</strong> theclass (as opposed to dataallocated <strong>for</strong> each instanceof a class).Define factory methods.IDENTIFICATION DIVISION.FACTORY.“WORKING-STORAGE SECTION <strong>for</strong>defining factory data” (optional)Factory method definitions: “Defining afactory method” on page 595“Example: defining a factory (with methods)” on page 597RELATED TASKS“Defining a class” on page 564“Instantiating <strong>COBOL</strong> classes” on page 588“Wrapping procedure-oriented <strong>COBOL</strong> programs” on page 603“Structuring OO applications” on page 603WORKING-STORAGE SECTION <strong>for</strong> defining factory dataUse the WORKING-STORAGE SECTION in the DATA DIVISION of the FACTORY paragraphto describe the factory data that a <strong>COBOL</strong> class needs, that is, statically allocateddata to be shared by all object instances of the class.The FACTORY keyword, which you must immediately precede with anIDENTIFICATION DIVISION declaration, indicates the beginning of the definitions ofthe factory data and factory methods <strong>for</strong> the class. For example, the definition ofthe factory data <strong>for</strong> the Account class might look like this:594 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Identification division.Factory.Data division.Working-storage section.01 NumberOfAccounts pic 9(6) value zero....End Factory.You can initialize simple factory data by using VALUE clauses as shown above.<strong>COBOL</strong> factory data is equivalent to Java private static data. No other class orsubclass (nor instance method in the same class, if any) can reference <strong>COBOL</strong>factory data directly. Factory data is global to all factory methods that the FACTORYparagraph defines. If you want to make factory data accessible from outside theFACTORY paragraph, define factory attribute (get or set) methods <strong>for</strong> doing so.RELATED TASKS“Coding attribute (get and set) methods” on page 575“Instantiating <strong>COBOL</strong> classes” on page 588Defining a factory methodDefine <strong>COBOL</strong> factory methods in the PROCEDURE DIVISION of the FACTORY paragraphof a class definition. A factory method defines an operation that is supported by aclass independently of any object instance of the class. <strong>COBOL</strong> factory methods areequivalent to Java public static methods.You typically define factory methods <strong>for</strong> classes whose instances require complexinitialization, that is, to values that you cannot assign by using VALUE clauses alone.Within a factory method you can invoke instance methods to initialize the instancedata. A factory method cannot directly access instance data.You can code factory attribute (get and set) methods to make factory dataaccessible from outside the FACTORY paragraph, <strong>for</strong> example, to make the dataaccessible from instance methods in the same class or from a client program. Forexample, the Account class could define a factory method getNumberOfAccountsto return the current tally of the number of accounts.You can use factory methods to wrap procedure-oriented <strong>COBOL</strong> programs so thatthey are accessible from Java programs. You can code a factory method called mainto enable you to run an OO application by using the java command, and tostructure your applications in keeping with standard Java practice. See the relatedtasks <strong>for</strong> details.In defining factory methods, you use the same syntax that you use to defineinstance methods. A <strong>COBOL</strong> factory method definition consists of four divisions(like a <strong>COBOL</strong> program), followed by an END METHOD marker:Table 84. Structure of factory method definitionsDivision Purpose SyntaxIDENTIFICATION(required)ENVIRONMENT(optional)DATA (optional)Same as <strong>for</strong> a classinstance methodSame as <strong>for</strong> a classinstance methodSame as <strong>for</strong> a classinstance methodSame as <strong>for</strong> a class instance method(required)Same as <strong>for</strong> a class instance methodSame as <strong>for</strong> a class instance methodChapter 30. Writing object-oriented programs 595


Table 84. Structure of factory method definitions (continued)Division Purpose SyntaxPROCEDURE(optional)Same as <strong>for</strong> a classinstance methodSame as <strong>for</strong> a class instance methodWithin a class definition, you do not need to make each factory method-nameunique, but you do need to give each factory method a unique signature. You canoverload factory methods in exactly the same way that you overload instancemethods. For example, the CheckingAccount subclass provides two versions of thefactory method createCheckingAccount: one that initializes the account to have adefault balance of zero, and one that allows the opening balance to be passed in.Clients can invoke either createCheckingAccount method by passing argumentsthat match the signature of the intended method.If you define a data item with the same name in both the DATA DIVISION of afactory method and the DATA DIVISION of the FACTORY paragraph, a reference in themethod to that data-name refers only to the method data item. The method DATADIVISION takes precedence.“Example: defining a factory (with methods)” on page 597RELATED TASKS“Structuring OO applications” on page 603“Wrapping procedure-oriented <strong>COBOL</strong> programs” on page 603“Instantiating <strong>COBOL</strong> classes” on page 588“Defining a class instance method” on page 569“Coding attribute (get and set) methods” on page 575“Overloading an instance method” on page 574“Hiding a factory or static method”“Invoking factory or static methods” on page 597“Using object-oriented <strong>COBOL</strong> and Java under IMS” on page 432Hiding a factory or static methodA factory method defined in a subclass is said to hide an inherited <strong>COBOL</strong> or Javamethod that would otherwise be accessible in the subclass if the two methods havethe same signature.To hide a superclass factory method f1 in a <strong>COBOL</strong> subclass, define a factorymethod f1 in the subclass that has the same name and whose PROCEDURE DIVISIONUSING phrase (if any) has the same number and type of <strong>for</strong>mal parameters as thesuperclass method has. (If the superclass method is implemented in Java, you mustcode <strong>for</strong>mal parameters that are interoperable with the data types of thecorresponding Java parameters.) When a client invokes f1 using the subclass name,the subclass method rather than the superclass method is invoked.The presence or absence of a method return value and the data type of the returnvalue used in the PROCEDURE DIVISION RETURNING phrase (if any) must be identicalin the subclass factory method and the hidden superclass method.A factory method must not hide an instance method in a Java or <strong>COBOL</strong>superclass.“Example: defining a factory (with methods)” on page 597596 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Overriding an instance method” on page 573“Invoking methods (INVOKE)” on page 582RELATED REFERENCESThe Java Language Specification (Inheritance, overriding, and hiding)The procedure division header (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Invoking factory or static methodsTo invoke a <strong>COBOL</strong> factory method or Java static method in a <strong>COBOL</strong> method orclient program, code the class-name as the first operand of the INVOKE statement.For example, a client program could invoke one of the overloadedCheckingAccount factory methods called createCheckingAccount to create achecking account with account number 777777 and an opening balance of $300 bycoding this statement:Invoke CheckingAccount "createCheckingAccount"using by value 777777 300returning aCheckingAccountTo invoke a factory method from within the same class in which you define thefactory method, you also use the class-name as the first operand in the INVOKEstatement.Code the name of the method to be invoked either as a literal or as an identifierwhose value at run time is the method-name. The method-name must be analphanumeric or national literal or a category alphabetic, alphanumeric, or nationaldata item, and is interpreted in a case-sensitive manner.If an invoked method is not supported in the class that you name in the INVOKEstatement, a severity-3 Language Environment condition is raised at run timeunless you code the ON EXCEPTION phrase in the INVOKE statement.The con<strong>for</strong>mance requirements <strong>for</strong> passing arguments to a <strong>COBOL</strong> factory methodor Java static method in the USING phrase, and receiving a return value in theRETURNING phrase, are the same as those <strong>for</strong> invoking instance methods.“Example: defining a factory (with methods)”RELATED TASKS“Invoking methods (INVOKE)” on page 582“Using national data (Unicode) in <strong>COBOL</strong>” on page 126“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612RELATED REFERENCESINVOKE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: defining a factory (with methods)The following example updates the previous examples to show the definition offactory data and methods.These updates are shown:Chapter 30. Writing object-oriented programs 597


vvvvThe Account class adds factory data and a parameterized factory method,createAccount, which allows an Account instance to be created using an accountnumber that is passed in.The CheckingAccount subclass adds factory data and an overloadedparameterized factory method, createCheckingAccount. One implementation ofcreateCheckingAccount initializes the account with a default balance of zero, andthe other allows the opening balance to be passed in. Clients can invoke eithermethod by passing arguments that match the signature of the desired method.The TestAccounts client invokes the services provided by the factory methods ofthe Account and CheckingAccount classes, and instantiates the Java Check class.The output from the TestAccounts client program is shown.(The previous examples were “Example: defining a method” on page 576,“Example: defining a client” on page 589, and “Example: defining a subclass (withmethods)” on page 592.)You can also find the complete source code <strong>for</strong> this example in thecobol/demo/oosample subdirectory in the HFS. Typically the complete path <strong>for</strong>the source is /usr/lpp/cobol/demo/oosample. You can use the makefile there tocompile and link the code.Account classcbl dll,thread,pgmname(longmixed),libIdentification Division.Class-id. Account inherits Base.Environment Division.Configuration section.Repository.Class Base is "java.lang.Object"Class Account is "Account".*Identification division.Factory.Data division.Working-storage section.01 NumberOfAccounts pic 9(6) value zero.*Procedure Division.** createAccount method to create a new Account* instance, then invoke the OBJECT paragraph's init* method on the instance to initialize its instance data:Identification Division.Method-id. "createAccount".Data division.Linkage section.01 inAccountNumber pic S9(6) binary.01 outAccount object reference Account.* Facilitate access to JNI services:Copy JNI.Procedure Division using by value inAccountNumberreturning outAccount.* Establish addressability to JNI environment structure:Set address of JNIEnv to JNIEnvPtrSet address of JNINativeInterface to JNIEnvInvoke Account New returning outAccountInvoke outAccount "init" using by value inAccountNumberAdd 1 to NumberOfAccounts.End method "createAccount".*End Factory.*598 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Identification division.Object.Data division.Working-storage section.01 AccountNumber pic 9(6).01 AccountBalance pic S9(9) value zero.*Procedure Division.** init method to initialize the account:Identification Division.Method-id. "init".Data division.Linkage section.01 inAccountNumber pic S9(9) binary.Procedure Division using by value inAccountNumber.Move inAccountNumber to AccountNumber.End method "init".** getBalance method to return the account balance:Identification Division.Method-id. "getBalance".Data division.Linkage section.01 outBalance pic S9(9) binary.Procedure Division returning outBalance.Move AccountBalance to outBalance.End method "getBalance".** credit method to deposit to the account:Identification Division.Method-id. "credit".Data division.Linkage section.01 inCredit pic S9(9) binary.Procedure Division using by value inCredit.Add inCredit to AccountBalance.End method "credit".** debit method to withdraw from the account:Identification Division.Method-id. "debit".Data division.Linkage section.01 inDebit pic S9(9) binary.Procedure Division using by value inDebit.Subtract inDebit from AccountBalance.End method "debit".** print method to display <strong>for</strong>matted account number and balance:Identification Division.Method-id. "print".Data division.Local-storage section.01 PrintableAccountNumber pic ZZZZZZ999999.01 PrintableAccountBalance pic $$$$,$$$,$$9CR.Procedure Division.Move AccountNumber to PrintableAccountNumberMove AccountBalance to PrintableAccountBalanceDisplay " Account: " PrintableAccountNumberDisplay " Balance: " PrintableAccountBalance.End method "print".*End Object.*End class Account.Chapter 30. Writing object-oriented programs 599


CheckingAccount class (subclass of Account)cbl dll,thread,pgmname(longmixed),libIdentification Division.Class-id. CheckingAccount inherits Account.Environment Division.Configuration section.Repository.Class CheckingAccount is "CheckingAccount"Class Checkis "Check"Class Account is "Account".*Identification division.Factory.Data division.Working-storage section.01 NumberOfCheckingAccounts pic 9(6) value zero.*Procedure Division.** createCheckingAccount overloaded method to create a new* CheckingAccount instance with a default balance, invoke* inherited instance method init to initialize the account* number, and increment factory data tally of checking accounts:Identification Division.Method-id. "createCheckingAccount".Data division.Linkage section.01 inAccountNumber pic S9(6) binary.01 outCheckingAccount object reference CheckingAccount.* Facilitate access to JNI services:Copy JNI.Procedure Division using by value inAccountNumberreturning outCheckingAccount.* Establish addressability to JNI environment structure:Set address of JNIEnv to JNIEnvPtrSet address of JNINativeInterface to JNIEnvInvoke CheckingAccount New returning outCheckingAccountInvoke outCheckingAccount "init"using by value inAccountNumberAdd 1 to NumberOfCheckingAccounts.End method "createCheckingAccount".** createCheckingAccount overloaded method to create a new* CheckingAccount instance, invoke inherited instance methods* init to initialize the account number and credit to set the* balance, and increment factory data tally of checking accounts:Identification Division.Method-id. "createCheckingAccount".Data division.Linkage section.01 inAccountNumber pic S9(6) binary.01 inInitialBalance pic S9(9) binary.01 outCheckingAccount object reference CheckingAccount.Copy JNI.Procedure Division using by value inAccountNumberinInitialBalancereturning outCheckingAccount.Set address of JNIEnv to JNIEnvPtrSet address of JNINativeInterface to JNIEnvInvoke CheckingAccount New returning outCheckingAccountInvoke outCheckingAccount "init"using by value inAccountNumberInvoke outCheckingAccount "credit"using by value inInitialBalanceAdd 1 to NumberOfCheckingAccounts.End method "createCheckingAccount".*600 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


End Factory.*Identification division.Object.Data division.Working-storage section.01 CheckFee pic S9(9) value 1.Procedure Division.** processCheck method to get the check amount and payee,* add the check fee, and invoke inherited methods debit* to debit the payer and credit to credit the payee:Identification Division.Method-id. "processCheck".Data division.Local-storage section.01 amount pic S9(9) binary.01 payee usage object reference Account.Linkage section.01 aCheck usage object reference Check.Procedure Division using by value aCheck.Invoke aCheck "getAmount" returning amountInvoke aCheck "getPayee" returning payeeInvoke payee "credit" using by value amountAdd checkFee to amountInvoke self "debit" using by value amount.End method "processCheck".** print method override to display account status:Identification Division.Method-id. "print".Data division.Local-storage section.01 printableFee pic $$,$$$,$$9.Procedure Division.Invoke super "print"Move CheckFee to printableFeeDisplay " Check fee: " printableFee.End method "print".*End Object.*End class CheckingAccount.Check class/*** A Java class <strong>for</strong> check in<strong>for</strong>mation*/public class Check {private CheckingAccount payer;private Account payee;private intamount;public Check(CheckingAccount inPayer, Account inPayee, int inAmount) {payer=inPayer;payee=inPayee;amount=inAmount;}public int getAmount() {return amount;}public Account getPayee() {return payee;}}Chapter 30. Writing object-oriented programs 601


TestAccounts client programcbl dll,thread,pgmname(longmixed)Identification division.Program-id. "TestAccounts" recursive.Environment division.Configuration section.Repository.Class Account is "Account"Class CheckingAccount is "CheckingAccount"Class Checkis "Check".Data Division.* Working data is declared in Local-storage* so that each thread has its own copy:Local-storage section.01 anAccount usage object reference Account.01 aCheckingAccount usage object reference CheckingAccount.01 aCheck usage object reference Check.01 payee usage object reference Account.*Procedure division.Test-Account-section.Display "Test Account class"* Create account 123456 with 0 balance:Invoke Account "createAccount"using by value 123456returning anAccount* Deposit 500 to the account:Invoke anAccount "credit" using by value 500Invoke anAccount "print"Display space*Display "Test CheckingAccount class"* Create checking account 777777 with balance of 300:Invoke CheckingAccount "createCheckingAccount"using by value 777777 300returning aCheckingAccount* Set account 123456 as the payee:Set payee to anAccount* Initialize check <strong>for</strong> 125 to be paid by account 777777 to payee:Invoke Check Newusing by value aCheckingAccount, payee, 125returning aCheck* Debit the payer, and credit the payee:Invoke aCheckingAccount "processCheck"using by value aCheckInvoke aCheckingAccount "print"Invoke anAccount "print"*Stop Run.End program "TestAccounts".Output produced by the TestAccounts client programTest Account classAccount: 123456Balance: $500Test CheckingAccount classAccount: 777777Balance: $174Check fee: $1Account: 123456Balance: $625RELATED TASKS“Creating and initializing instances of classes” on page 586602 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Defining a factory method” on page 595“Invoking factory or static methods” on page 597Chapter 16, “Compiling, linking, and running OO applications,” on page 291Wrapping procedure-oriented <strong>COBOL</strong> programsA wrapper is a class that provides an interface between object-oriented code andprocedure-oriented code. Factory methods provide a convenient means <strong>for</strong> writingwrappers <strong>for</strong> existing procedural <strong>COBOL</strong> code to make it accessible from Javaprograms.To wrap <strong>COBOL</strong> code, do these steps:1. Create a simple <strong>COBOL</strong> class that contains a FACTORY paragraph.2. In the FACTORY paragraph, code a factory method that uses a CALL statement tocall the procedural program.A Java program can invoke the factory method by using a static method invocationexpression, thus invoking the <strong>COBOL</strong> procedural program.Structuring OO applicationsRELATED TASKS“Defining a class” on page 564“Defining a factory section” on page 594“Defining a factory method” on page 595You can structure applications that use object-oriented <strong>COBOL</strong> syntax in one ofthree ways.An OO application can begin with:v A <strong>COBOL</strong> program, which can have any name.Under z/<strong>OS</strong> UNIX, you can run the application by specifying the name of thelinked module (which should match the program name) at the commandprompt. You can also bind the program as a module in a PDSE and run it in JCLusing the EXEC PGM statement.v A Java class definition that contains a method called main. Declare main aspublic, static, and void, with a single parameter of type String[].You can run the application with the java command, specifying the name of theclass that contains main, and zero or more strings as command-line arguments.v A <strong>COBOL</strong> class definition that contains a factory method called main. Declaremain with no RETURNING phrase and a single USING parameter, an object referenceto a class that is an array with elements of type java.lang.String. (Thus main is ineffect public, static, and void, with a single parameter of type String[].)You can run the application with the java command, specifying the name of theclass that contains main, and zero or more strings as command-line arguments.Structure an OO application this way if you want to:– Run the application by using the java command.– Run the application in an environment where applications must start with themain method of a Java class (such as a Java dependent region).– Follow standard Java programming practice.“Examples: <strong>COBOL</strong> applications that run using the java command” on page 604Chapter 30. Writing object-oriented programs 603


RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291“Defining a factory method” on page 595“Declaring arrays and strings <strong>for</strong> Java” on page 613Chapter 22, “Developing <strong>COBOL</strong> programs <strong>for</strong> IMS,” on page 431Examples: <strong>COBOL</strong> applications that run using the javacommandThe following examples show <strong>COBOL</strong> class definitions that contain a factorymethod called main.In each case, main has no RETURNING phrase and has a single USING parameter, anobject reference to a class that is an array with elements of type java.lang.String.You can run these applications by using the java command.Displaying a messagecbl dll,threadIdentification Division.Class-id. CBLmain inherits Base.Environment Division.Configuration section.Repository.Class Base is "java.lang.Object"Class stringArray is "jobjectArray:java.lang.String"Class CBLmain is "CBLmain".*Identification Division.Factory.Procedure division.*Identification Division.Method-id. "main".Data division.Linkage section.01 SA usage object reference stringArray.Procedure division using by value SA.Display " >> <strong>COBOL</strong> main method entered".End method "main".End factory.End class CBLmain.Echoing the input stringscbl dll,thread,lib,pgmname(longmixed),ssrangeIdentification Division.Class-id. Echo inherits Base.Environment Division.Configuration section.Repository.Class Base is "java.lang.Object"Class stringArray is "jobjectArray:java.lang.String"Class jstring is "java.lang.String"Class Echo is "Echo".*Identification Division.Factory.Procedure division.*Identification Division.Method-id. "main".Data division.604 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Local-storage section.01 SAlen pic s9(9) binary.01 I pic s9(9) binary.01 SAelement object reference jstring.01 SAelementlen pic s9(9) binary.01 Sbuffer pic X(65535).01 P pointer.Linkage section.01 SA object reference stringArray.Copy "JNI.cpy" suppress.Procedure division using by value SA.Set address of JNIEnv to JNIEnvPtrSet address of JNINativeInterface to JNIEnvCall GetArrayLength using by value JNIEnvPtr SAreturning SAlenDisplay "Input string array length: " SAlenDisplay "Input strings:"Per<strong>for</strong>m varying I from 0 by 1 until I = SAlenCall GetObjectArrayElementusing by value JNIEnvPtr SA Ireturning SAelementCall "GetStringPlat<strong>for</strong>mLength"using by value JNIEnvPtrSAelementaddress of SAelementlen0Call "GetStringPlat<strong>for</strong>m"using by value JNIEnvPtrSAelementaddress of Sbufferlength of Sbuffer0Display Sbuffer(1:SAelementlen)End-per<strong>for</strong>m.End method "main".End factory.End class Echo.RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291“Defining a factory method” on page 595Chapter 31, “Communicating with Java methods,” on page 607Chapter 30. Writing object-oriented programs 605


606 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 31. Communicating with Java methodsTo achieve interlanguage interoperability with Java, you need to follow certainrules and guidelines <strong>for</strong> using services in the Java Native Interface (JNI), codingdata types, and compiling <strong>COBOL</strong> programs.You can invoke methods that are written in Java from <strong>COBOL</strong> programs, and youcan invoke methods that are written in <strong>COBOL</strong> from Java programs. You need tocode <strong>COBOL</strong> object-oriented language <strong>for</strong> basic Java object capabilities. Foradditional Java capabilities, you can call JNI services.Because Java programs might be multithreaded and use asynchronous signals,compile <strong>COBOL</strong> programs with the THREAD option.“Example: J2EE client written in <strong>COBOL</strong>” on page 619RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291“Accessing JNI services”“Sharing data with Java” on page 612Chapter 30, “Writing object-oriented programs,” on page 561Chapter 27, “Preparing <strong>COBOL</strong> programs <strong>for</strong> multithreading,” on page 493Accessing JNI servicesRELATED REFERENCESJava 2 SDK, Standard Edition DocumentationThe Java Native Interface (JNI) provides many callable services that you can usewhen you develop applications that mix <strong>COBOL</strong> and Java. To facilitate access tothese services, copy JNI.cpy into the LINKAGE SECTION of your <strong>COBOL</strong> program.The JNI.cpy copybook contains these definitions:v <strong>COBOL</strong> data definitions that correspond to the Java JNI typesv JNINativeInterface, the JNI environment structure that contains function pointers<strong>for</strong> accessing the callable service functionsYou obtain the JNI environment structure by two levels of indirection from the JNIenvironment pointer, as the following illustration shows:JNIEnvPtrpointerPrivate perthreaddatapointerpointerpointerJNI functionJNI function...JNI functionUse the special register JNIEnvPtr to reference the JNI environment pointer toobtain the address <strong>for</strong> the JNI environment structure. JNIEnvPtr is implicitly© Copyright IBM Corp. 1991, 2009 607


defined as USAGE POINTER; do not use it as a receiving data item. Be<strong>for</strong>e youreference the contents of the JNI environment structure, you must code thefollowing statements to establish its addressability:Linkage section.COPY JNI...Procedure division.Set address of JNIEnv to JNIEnvPtrSet address of JNINativeInterface to JNIEnv...The code above sets the addresses of the following items:v JNIEnv, a pointer data item that JNI.cpy provides. JNIEnvPtr is the <strong>COBOL</strong>special register that contains the environment pointer.v JNINativeInterface, the <strong>COBOL</strong> group structure that JNI.cpy contains. Thisstructure maps the JNI environment structure, which contains an array offunction pointers <strong>for</strong> the JNI callable services.After you code the statements above, you can access the JNI callable services withCALL statements that reference the function pointers. You can pass the JNIEnvPtrspecial register as the first argument to the services that require the environmentpointer, as shown in the following example:01 InputArrayObj usage object reference jlongArray.01 ArrayLen pic S9(9) comp-5....Call GetArrayLength using by value JNIEnvPtr InputArrayObjreturning ArrayLenImportant: Pass all arguments to the JNI callable services by value.Some JNI callable services require a Java class-object reference as an argument. Toobtain a reference to the class object that is associated with a class, use one of thefollowing JNI callable services:v GetObjectClassv FindClassRestriction: The JNI environment pointer is thread specific. Do not pass it fromone thread to another.RELATED TASKS“Managing local and global references” on page 610“Handling Java exceptions”“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Defining a client” on page 578RELATED REFERENCESAppendix F, “JNI.cpy,” on page 741The Java Native InterfaceHandling Java exceptionsUse JNI services to throw and catch Java exceptions.Throwing an exception: Use one of the following services to throw a Javaexception from a <strong>COBOL</strong> method:v Throw608 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vThrowNewYou must make the thrown object an instance of a subclass of java.lang.Throwable.The Java virtual machine (JVM) does not recognize and process the thrownexception until the method that contains the call has completed and returned tothe JVM.Catching an exception: After you invoke a method that might have thrown a Javaexception, you can do these steps:1. Test whether an exception occurred.2. If an exception occurred, process the exception.3. Clear the exception, if clearing is appropriate.Use the following JNI services:v ExceptionOccurredv ExceptionCheckv ExceptionDescribev ExceptionClearTo do error analysis, use the methods supported by the exception object that isreturned. This object is an instance of the java.lang.Throwable class.“Example: handling Java exceptions”Example: handling Java exceptionsThe following example shows the use of JNI services <strong>for</strong> catching an exceptionfrom Java and the use of the printStackTrace method of java.lang.Throwable <strong>for</strong>error analysis.Repository.Class JavaException is "java.lang.Exception"....Local-storage section.01 ex usage object reference JavaException.Linkage section.COPY "JNI.cpy"....Procedure division.Set address of JNIEnv to JNIEnvPtrSet address of JNINativeInterface to JNIEnv...Invoke anObj "someMethod"Per<strong>for</strong>m ErrorCheck...ErrorCheck.Call ExceptionOccurredusing by value JNIEnvPtrreturning exIf ex not = null thenCall ExceptionClear using by value JNIEnvPtrDisplay "Caught an unexpected exception"Invoke ex "printStackTrace"Stop runEnd-ifChapter 31. Communicating with Java methods 609


Managing local and global referencesThe Java virtual machine tracks the object references that you use in nativemethods, such as <strong>COBOL</strong> methods. This tracking ensures that the objects are notprematurely released during garbage collection.There are two classes of such references:Local referencesLocal references are valid only while the method that you invoke runs.Automatic freeing of the local references occurs after the native methodreturns.Global referencesGlobal references remain valid until you explicitly delete them. You cancreate global references from local references by using the JNI serviceNewGlobalRef.The following object references are always local:v Object references that are received as method parametersv Object references that are returned as the method RETURNING value from amethod invocationv Object references that are returned by a call to a JNI functionv Object references that you create by using the INVOKE ...NEWstatementYou can pass either a local reference or a global reference as an object referenceargument to a JNI service.You can code methods to return either local or global references as RETURNINGvalues. However, in either case, the reference that is received by the invokingprogram is a local reference.You can pass either local or global references as USING arguments in a methodinvocation. However, in either case, the reference that is received by the invokedmethod is a local reference.Local references are valid only in the thread in which you create them. Do not passthem from one thread to another.RELATED TASKS“Accessing JNI services” on page 607“Deleting, saving, and freeing local references”Deleting, saving, and freeing local referencesYou can manually delete local references at any point within a method. Save localreferences only in object references that you define in the LOCAL-STORAGE SECTIONof a method.Use a SET statement to convert a local reference to a global reference if you want tosave a reference in any of these data items:v An object instance variablev A factory variablev A data item in the WORKING-STORAGE SECTION of a method610 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Otherwise, an error occurs. These storage areas persist when a method returns;there<strong>for</strong>e a local reference is no longer valid.In most cases you can rely on the automatic freeing of local references that occurswhen a method returns. However, in some cases you should explicitly free a localreference within a method by using the JNI service DeleteLocalRef. Here are twosituations where explicit freeing is appropriate:vvIn a method you access a large object, thereby creating a local reference to theobject. After extensive computations, the method returns. Free the large object ifyou do not need it <strong>for</strong> the additional computations, because the local referenceprevents the object from being released during garbage collection.You create a large number of local references in a method, but do not use all ofthem at the same time. Because the Java virtual machine requires space to keeptrack of each local reference, you should free those that you no longer need.Freeing the local references helps prevent the system from running out ofmemory.For example, in a <strong>COBOL</strong> method you loop through a large array of objects,retrieve the elements as local references, and operate on one element at eachiteration. You can free the local reference to the array element after eachiteration.Use the following callable services to manage local references and globalreferences.Table 85. JNI services <strong>for</strong> local and global referencesService Input arguments Return value PurposeNewGlobalRef v The JNI environmentpointerv A local or global objectreferenceDeleteGlobalRef v The JNI environmentpointerv A global object referenceDeleteLocalRef v The JNI environmentpointerv A local object referenceThe global reference, orNULL if the system is out ofmemoryNoneNoneTo create a new globalreference to the object thatthe input object referencerefers toTo delete a global referenceto the object that the inputobject reference refers toTo delete a local referenceto the object that the inputobject reference refers toRELATED TASKS“Accessing JNI services” on page 607Java access controlsThe Java access modifiers protected and private are not en<strong>for</strong>ced when you usethe Java Native Interface. There<strong>for</strong>e a <strong>COBOL</strong> program could invoke a protected orprivate Java method that is not invocable from a Java client. This usage is notrecommended.Chapter 31. Communicating with Java methods 611


Sharing data with JavaYou can share the <strong>COBOL</strong> data types that have Java equivalents. (Some <strong>COBOL</strong>data types have Java equivalents, but others do not.)Share data items with Java in these ways:v Pass them as arguments in the USING phrase of an INVOKE statement.v Receive them as parameters in the USING phrase from a Java method.v Receive them as the RETURNING value in an INVOKE statement.v Return them as the value in the RETURNING phrase of the PROCEDURE DIVISIONheader in a <strong>COBOL</strong> method.To pass or receive arrays and strings, declare them as object references:v Declare an array as an object reference that contains an instance of one of thespecial array classes.v Declare a string as an object reference that contains an instance of the jstringclass.RELATED TASKS“Coding interoperable data types in <strong>COBOL</strong> and Java”“Declaring arrays and strings <strong>for</strong> Java” on page 613“Manipulating Java arrays” on page 614“Manipulating Java strings” on page 616“Invoking methods (INVOKE)” on page 582Chapter 25, “Sharing data,” on page 465Coding interoperable data types in <strong>COBOL</strong> and JavaYour <strong>COBOL</strong> program can use only certain data types when communicating withJava.Table 86. Interoperable data types in <strong>COBOL</strong> and JavaPrimitive Java datatypeboolean 1byte 1shortintlongfloat 2double 2charclass types (objectreferences)Corresponding <strong>COBOL</strong> data typePIC X followed by exactly two condition-names of this <strong>for</strong>m:level-number data-name PIC X.88 data-name-false value X'00'.88 data-name-true value X'01' through X'FF'.Single-byte alphanumeric: PIC X or PIC AUSAGE BINARY, COMP, COMP-4, orCOMP-5, with PICTURE clause of the<strong>for</strong>m S9(n), where 1


Table 86. Interoperable data types in <strong>COBOL</strong> and Java (continued)Primitive Java datatypeCorresponding <strong>COBOL</strong> data type1. You must distinguish boolean from byte, because they each correspond to PIC X. PIC Xis interpreted as boolean only when you define an argument or a parameter with thetwo condition-names as shown. Otherwise, a PIC X data item is interpreted as the Javabyte type.2. Java floating-point data is represented in IEEE floating point. <strong>Enterprise</strong> <strong>COBOL</strong>,however, uses hexadecimal floating-point representation. When you pass floating-pointarguments by using an INVOKE statement or you receive floating-point data from a Javamethod, the arguments and data are automatically converted as needed.RELATED TASKS“Using national data (Unicode) in <strong>COBOL</strong>” on page 126Declaring arrays and strings <strong>for</strong> JavaWhen you communicate with Java, declare arrays by using the special arrayclasses, and declare strings by using jstring. Code the <strong>COBOL</strong> data types shown inthe table below.Table 87. Interoperable arrays and strings in <strong>COBOL</strong> and JavaJava data type Corresponding <strong>COBOL</strong> data typeboolean[ ]object reference jbooleanArraybyte[ ]object reference jbyteArrayshort[ ]object reference jshortArrayint[ ]object reference jintArraylong[ ]object reference jlongArraychar[ ]object reference jcharArrayObject[ ]object reference jobjectArrayStringobject reference jstringTo use one of these classes <strong>for</strong> interoperability with Java, you must code an entryin the REP<strong>OS</strong>ITORY paragraph. For example:Configuration section.Repository.Class jbooleanArray is "jbooleanArray".The REP<strong>OS</strong>ITORY paragraph entry <strong>for</strong> an object array type must specify an externalclass-name in one of these <strong>for</strong>ms:"jobjectArray""jobjectArray:external-classname-2"In the first case, the REP<strong>OS</strong>ITORY entry specifies an array class in which the elementsof the array are objects of type java.lang.Object. In the second case, the REP<strong>OS</strong>ITORYentry specifies an array class in which the elements of the array are objects of typeexternal-classname-2. Code a colon as the separator between the specification of thejobjectArray type and the external class-name of the array elements.Chapter 31. Communicating with Java methods 613


The following example shows both cases. In the example, oa defines an array ofelements that are objects of type java.lang.Object. aDepartment defines an array ofelements that are objects of type com.acme.Employee.Environment Division.Configuration Section.Repository.Class jobjectArray is "jobjectArray"Class Employee is "com.acme.Employee"Class Department is "jobjectArray:com.acme.Employee"....Linkage section.01 oa usage object reference jobjectArray.01 aDepartment usage object reference Department....Procedure division using by value aDepartment....“Examples: <strong>COBOL</strong> applications that run using the java command” on page 604The following Java array types are currently not supported <strong>for</strong> interoperation with<strong>COBOL</strong> programs.Table 88. Noninteroperable array types in <strong>COBOL</strong> and JavaJava data type Corresponding <strong>COBOL</strong> data typefloat[ ]object reference jfloatArraydouble[ ]object reference jdoubleArrayRELATED TASKS“REP<strong>OS</strong>ITORY paragraph <strong>for</strong> defining a class” on page 566Manipulating Java arraysTo represent an array in a <strong>COBOL</strong> program, code a group item that contains asingle elementary item that is of the data type that corresponds to the Java type ofthe array. Specify an OCCURS or OCCURS DEPENDING ON clause that is appropriate <strong>for</strong>the array.For example, the following code specifies a structure to receive 500 or fewerinteger values from a jlongArray object:01 longArray.02 X pic S9(10) comp-5 occurs 1 to 500 times depending on N.To operate on objects of the special Java-array classes, call the services that the JNIprovides. You can use services to access and set individual elements of an arrayand <strong>for</strong> the following purposes, using the services cited:Table 89. JNI array servicesService Input arguments Return value PurposeGetArrayLength v The JNI environment pointer The array length as To get the number ofa binary fullword elements in a Javav The array object referenceintegerarray objectNewBooleanArray,NewByteArray, NewCharArray,NewShortArray, NewIntArray,NewLongArrayvvThe JNI environment pointerThe number of elements in thearray, as a binary fullwordintegerThe array objectreference, or NULL ifthe array cannot beconstructedTo create a new Javaarray object614 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 89. JNI array services (continued)Service Input arguments Return value PurposeGetBooleanArrayElements,GetByteArrayElements,GetCharArrayElements,GetShortArrayElements,GetIntArrayElements,GetLongArrayElementsReleaseBooleanArrayElements,ReleaseByteArrayElements,ReleaseCharArrayElements,ReleaseShortArrayElements,ReleaseIntArrayElements,ReleaseLongArrayElementsvvvvvvvThe JNI environment pointerThe array object referenceA pointer to a boolean item. Ifthe pointer is not null, theboolean item is set to true if acopy of the array elements wasmade. If a copy was made, thecorrespondingReleasexxxArrayElements servicemust be called if changes are tobe written back to the arrayobject.The JNI environment pointerThe array object referenceA pointer to the storage bufferThe release mode, as a binaryfullword integer. See Java JNIdocumentation <strong>for</strong> details.(Recommendation: Specify 0 tocopy back the array content andfree the storage buffer.)NewObjectArray v The JNI environment pointerv The number of elements in thearray, as a binary fullwordintegerv An object reference <strong>for</strong> the arrayelement classv An object reference <strong>for</strong> the initialelement value. All array elementsare set to this value.GetObjectArrayElement v The JNI environment pointerv The array object referencev An array element index, as abinary fullword integer usingorigin zeroSetObjectArrayElement v The JNI environment pointerv The array object referencev The array element index, as abinary fullword integer usingorigin zerov The object reference <strong>for</strong> the newvalueA pointer to thestorage bufferNone; the storage<strong>for</strong> the array isreleased.The array objectreference, or NULL ifthe array cannot beconstructed 1An object reference 2None 3To extract the arrayelements from a Javaarray into a storagebuffer. The servicesreturn a pointer to thestorage buffer, whichyou can use as theaddress of a <strong>COBOL</strong>group data itemdefined in the LINKAGESECTION.To release the storagebuffer that containselements that havebeen extracted from aJava array, andconditionally map theupdated array valuesback into the arrayobjectTo create a new Javaobject arrayTo return the elementat a given index withinan object arrayTo set an elementwithin an object array1. NewObjectArray throws an exception if the system runs out of memory.2. GetObjectArrayElement throws an exception if the index is not valid.3. SetObjectArrayElement throws an exception if the index is not valid or if the new value is not a subclass of theelement class of the array.“Examples: <strong>COBOL</strong> applications that run using the java command” on page 604“Example: processing a Java int array” on page 616Chapter 31. Communicating with Java methods 615


RELATED TASKS“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Declaring arrays and strings <strong>for</strong> Java” on page 613“Accessing JNI services” on page 607Example: processing a Java int arrayThe following example shows the use of the Java-array classes and JNI services toprocess a Java array in <strong>COBOL</strong>.cbl lib,thread,dllIdentification division.Class-id. OOARRAY inherits Base.Environment division.Configuration section.Repository.Class Base is "java.lang.Object"Class jintArray is "jintArray".Identification division.Object.Procedure division.Identification division.Method-id. "ProcessArray".Data Division.Local-storage section.01 intArrayPtr pointer.01 intArrayLen pic S9(9) comp-5.Linkage section.COPY JNI.01 inIntArrayObj usage object reference jintArray.01 intArrayGroup.02 X pic S9(9) comp-5occurs 1 to 1000 times depending on intArrayLen.Procedure division using by value inIntArrayObj.Set address of JNIEnv to JNIEnvPtrSet address of JNINativeInterface to JNIEnvCall GetArrayLengthusing by value JNIEnvPtr inIntArrayObjreturning intArrayLenCall GetIntArrayElementsusing by value JNIEnvPtr inIntArrayObj 0returning IntArrayPtrSet address of intArrayGroup to intArrayPtr* . . . process the array elements X(I) ...Call ReleaseIntArrayElementsusing by value JNIEnvPtr inIntArrayObj intArrayPtr 0.End method "ProcessArray".End Object.End class OOARRAY.Manipulating Java strings<strong>COBOL</strong> represents Java String data in Unicode. To represent a Java String in a<strong>COBOL</strong> program, declare the string as an object reference of the jstring class. Thenuse JNI services to set or extract <strong>COBOL</strong> alphanumeric or national (Unicode) datafrom the object.||Services <strong>for</strong> Unicode: Use the following standard services to convert betweenjstring object references and <strong>COBOL</strong> USAGE NATIONAL data items. Use these services<strong>for</strong> applications that you intend to be portable between the workstation and the616 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|mainframe. Access these services by using function pointers in theJNINativeInterface environment structure.Table 90. Services that convert between jstring references and national dataService Input arguments Return valueNewString 1 v The JNI environment pointer jstring object referencev A pointer to a Unicode string, suchas a <strong>COBOL</strong> national data itemv The number of characters in thestring; binary fullwordGetStringLength v The JNI environment pointerv A jstring object referenceThe number of Unicode characters in the jstringobject reference; binary fullwordGetStringChars 1 v The JNI environment pointerv A jstring object referencev A pointer to a boolean data item, orNULLReleaseStringChars v The JNI environment pointerv A jstring object referencev A pointer to the array of Unicodecharacters that was returned fromGetStringCharsvvA pointer to the array of Unicode charactersextracted from the jstring object, or NULL if theoperation fails. The pointer is valid until it isreleased with ReleaseStringChars.When the pointer to the boolean data item isnot null, the boolean value is set to true if acopy is made of the string and to false if nocopy is made.None; the storage <strong>for</strong> the array is released.1. This service throws an exception if the system runs out of memory.Services <strong>for</strong> EBCDIC: Use the following z/<strong>OS</strong> services, an extension of the JNI, toconvert between jstring object references and <strong>COBOL</strong> alphanumeric data (PICX(n)).Table 91. Services that convert between jstring references and alphanumeric dataService Input arguments Return valueNewStringPlat<strong>for</strong>m v The JNI environment pointerv Pointer to the null-terminated EBCDICcharacter string that you want to convertto a jstring object0 Success.vvPointer to the jstring object reference inwhich you want the resultPointer to the Java encoding name <strong>for</strong> thestring, represented as a null-terminatedEBCDIC character string 1Return code as a binary fullwordinteger:-1 Mal<strong>for</strong>med input or illegalinput character.-2 Unsupported encoding; thejstring object reference pointeris set to NULL.Chapter 31. Communicating with Java methods 617


Table 91. Services that convert between jstring references and alphanumeric data (continued)Service Input arguments Return valueGetStringPlat<strong>for</strong>mLength v The JNI environment pointerv jstring object reference <strong>for</strong> which you wantthe length0 Success.v Pointer to a binary fullword integer <strong>for</strong> theresultvPointer to the Java encoding name <strong>for</strong> thestring, represented as a null-terminatedEBCDIC character string 1Return code as a binary fullwordinteger:-1 Mal<strong>for</strong>med input or illegalinput character.-2 Unsupported encoding; thejstring object reference pointeris set to NULL.GetStringPlat<strong>for</strong>m v The JNI environment pointerv jstring object reference that you want toconvert to a null-terminated stringv Pointer to the output buffer in which youwant the converted stringv Length of the output buffer as a binaryfullword integerv Pointer to the Java encoding name <strong>for</strong> thestring, represented as a null-terminatedEBCDIC character string 1Returns, in the third argument, theneeded length in bytes of the outputbuffer to hold the converted Javastring, including the terminating nullbyte referenced by the secondargument.Return code as a binary fullwordinteger:0 Success.-1 Mal<strong>for</strong>med input or illegalinput character.-2 Unsupported encoding; theoutput string is set to a nullstring.-3 Conversion buffer is full.1. If the pointer is NULL, the encoding from the Java file.encoding property is used.These EBCDIC services are packaged as a DLL that is part of your IBM JavaSoftware Development Kit. For details about the services, see jni_convert.h in theIBM Java Software Development Kit.Use CALL literal statements to call the services. The calls are resolved through thelibjvm.x DLL side file, which you must include in the link step of any <strong>COBOL</strong>program that uses object-oriented language.For example, the following code creates a Java String object from the EBCDICstring ’MyConverter’. (This code fragment is from the J2EE client program, whichis shown in full in “Example: J2EE client written in <strong>COBOL</strong>” on page 619.)Move z"MyConverter" to stringBufCall "NewStringPlat<strong>for</strong>m"using by value JNIEnvPtraddress of stringBufaddress of jstring10returning rcIf the EBCDIC services are the only JNI services that you call from a <strong>COBOL</strong>program, you do not need to copy the JNI.cpy copybook. You also do not need toestablish addressability with the JNI environment pointer.618 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Services <strong>for</strong> UTF-8: The Java Native Interface also provides services <strong>for</strong> conversionbetween jstring object references and UTF-8 strings. These services are notrecommended <strong>for</strong> use in <strong>COBOL</strong> programs due to the difficulty in handling UTF-8character strings on the z/<strong>OS</strong> plat<strong>for</strong>m.RELATED TASKS“Accessing JNI services” on page 607“Coding interoperable data types in <strong>COBOL</strong> and Java” on page 612“Declaring arrays and strings <strong>for</strong> Java” on page 613“Using national data (Unicode) in <strong>COBOL</strong>” on page 126Chapter 16, “Compiling, linking, and running OO applications,” on page 291Example: J2EE client written in <strong>COBOL</strong>The following example shows a <strong>COBOL</strong> client program that can access enterprisebeans that run on a J2EE-compliant EJB server.The <strong>COBOL</strong> client is equivalent to the J2EE client program in the Getting Startedsection of the Java 2 <strong>Enterprise</strong> Edition Developer’s <strong>Guide</strong>. For your convenience incomparing implementations, the second example shows the equivalent Java clientfrom the guide. (The enterprise bean is the Java implementation of the simplecurrency-converter enterprise bean, and is in the same guide.)||You can find an alternate version of the Java enterprise bean and client code in TheJava EE 5 Tutorial, referenced below.<strong>COBOL</strong> client (ConverterClient.cbl)Process pgmname(longmixed),lib,dll,thread****************************************************************** Demo J2EE client written in <strong>COBOL</strong>. ** ** Based on the sample J2EE client written in Java, which is ** given in the "Getting Started" chapter of "The Java(TM) 2 ** <strong>Enterprise</strong> Edition Developer's <strong>Guide</strong>." ** ** The client: ** - Locates the home interface of a session enterprise bean ** (a simple currency converter bean) ** - Creates an enterprise bean instance ** - Invokes a business method (currency conversion) ******************************************************************Identification division.Program-id. "ConverterClient" is recursive.Environment Division.Configuration section.Repository.Class InitialContext is "javax.naming.InitialContext"Class PortableRemoteObjectis "javax.rmi.PortableRemoteObject"Class JavaObject is "java.lang.Object"Class JavaClass is "java.lang.Class"Class JavaException is "java.lang.Exception"Class jstring is "jstring"Class Converter is "Converter"Class ConverterHome is "ConverterHome".Data division.Working-storage section.01 initialCtx object reference InitialContext.01 obj object reference JavaObject.01 classObj object reference JavaClass.Chapter 31. Communicating with Java methods 619


01 ex object reference JavaException.01 currencyConverter object reference Converter.01 home object reference ConverterHome.01 homeObject redefines home object reference JavaObject.01 jstring1 object reference jstring.01 stringBuf pic X(500) usage display.01 len pic s9(9) comp-5.01 rc pic s9(9) comp-5.01 amount comp-2.Linkage section.Copy JNI.Procedure division.Set address of JNIenv to JNIEnvPtrSet address of JNINativeInterface to JNIenv****************************************************************** Create JNDI naming context. ******************************************************************Invoke InitialContext New returning initialCtxPer<strong>for</strong>m JavaExceptionCheck****************************************************************** Create a jstring object <strong>for</strong> the string "MyConverter" <strong>for</strong> use ** as argument to the lookup method. ******************************************************************Move z"MyConverter" to stringBufCall "NewStringPlat<strong>for</strong>m"using by value JNIEnvPtraddress of stringBufaddress of jstring10returning rcIf rc not = zero thenDisplay "Error occurred creating jstring object"Stop runEnd-if****************************************************************** Use the lookup method to obtain a reference to the home ** object bound to the name "MyConverter". (This is the JNDI ** name specified when deploying the J2EE application.) ******************************************************************Invoke initialCtx "lookup" using by value jstring1returning objPer<strong>for</strong>m JavaExceptionCheck****************************************************************** Narrow the home object to be of type ConverterHome. ** First obtain class object <strong>for</strong> the ConverterHome class, by ** passing the null-terminated ASCII string "ConverterHome" to ** the FindClass API. Then use this class object as the ** argument to the static method "narrow". ******************************************************************Move z"ConverterHome" to stringBufCall "__etoa"using by value address of stringBufreturning lenIf len = -1 thenDisplay "Error occurred on ASCII conversion"Stop runEnd-ifCall FindClassusing by value JNIEnvPtraddress of stringBufreturning classObjIf classObj = nullDisplay "Error occurred locating ConverterHome class"620 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Stop runEnd-ifInvoke PortableRemoteObject "narrow"using by value objclassObjreturning homeObjectPer<strong>for</strong>m JavaExceptionCheck****************************************************************** Create the ConverterEJB instance and obtain local object ** reference <strong>for</strong> its remote interface ******************************************************************Invoke home "create" returning currencyConverterPer<strong>for</strong>m JavaExceptionCheck****************************************************************** Invoke business methods ******************************************************************Invoke currencyConverter "dollarToYen"using by value +100.00E+0returning amountPer<strong>for</strong>m JavaExceptionCheckDisplay amountInvoke currencyConverter "yenToEuro"using by value +100.00E+0returning amountPer<strong>for</strong>m JavaExceptionCheckDisplay amount****************************************************************** Remove the object and return. ******************************************************************Invoke currencyConverter "remove"Per<strong>for</strong>m JavaExceptionCheckGoback.****************************************************************** Check <strong>for</strong> thrown Java exceptions ******************************************************************JavaExceptionCheck.Call ExceptionOccurred using by value JNIEnvPtrreturning exIf ex not = null thenCall ExceptionClear using by value JNIEnvPtrDisplay "Caught an unexpected exception"Invoke ex "printStackTrace"Stop runEnd-if.End program "ConverterClient".Java client (ConverterClient.java)/*** Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.** This software is the proprietary in<strong>for</strong>mation of Sun Microsystems, Inc.* Use is subject to license terms.**/Chapter 31. Communicating with Java methods 621


import javax.naming.Context;import javax.naming.InitialContext;import javax.rmi.PortableRemoteObject;import Converter;import ConverterHome;public class ConverterClient {public static void main(String[] args) {try {Context initial = new InitialContext();Object objref = initial.lookup("MyConverter");ConverterHome home =(ConverterHome)PortableRemoteObject.narrow(objref,ConverterHome.class);Converter currencyConverter = home.create();double amount = currencyConverter.dollarToYen(100.00);System.out.println(String.valueOf(amount));amount = currencyConverter.yenToEuro(100.00);System.out.println(String.valueOf(amount));currencyConverter.remove();}}} catch (Exception ex) {System.err.println("Caught an unexpected exception!");ex.printStackTrace();}RELATED TASKSChapter 16, “Compiling, linking, and running OO applications,” on page 291WebSphere <strong>for</strong> z/<strong>OS</strong>: ApplicationsJava 2 <strong>Enterprise</strong> Edition Developer’s <strong>Guide</strong> (Getting Started)The Java EE 5 Tutorial (Getting Started with <strong>Enterprise</strong> Beans)622 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 7. Specialized processingChapter 32. Interrupts and checkpoint/restart 625Setting checkpoints . . . . . . . . . . . 625Designing checkpoints . . . . . . . . . 626Testing <strong>for</strong> a successful checkpoint . . . . . 627DD statements <strong>for</strong> defining checkpoint data sets 627Examples: defining checkpoint data sets . . 627Messages generated during checkpoint . . . . 628Restarting programs . . . . . . . . . . . 628Requesting automatic restart . . . . . . . 629Requesting deferred restart . . . . . . . . 629Formats <strong>for</strong> requesting deferred restart . . . . 630Example: requesting a deferred restart . . . 631Resubmitting jobs <strong>for</strong> restart . . . . . . . 631Example: restarting a job at a specificcheckpoint step. . . . . . . . . . . . 631Example: requesting a step restart . . . . . 631Example: resubmitting a job <strong>for</strong> a step restart 632Example: resubmitting a job <strong>for</strong> a checkpointrestart . . . . . . . . . . . . . . . 632Avoiding problems with packed-decimal fields 657Moving from expanded to windowed date fields 658Chapter 33. Processing two-digit-year dates 635Millennium language extensions (MLE) . . . . 636Principles and objectives of these extensions . . 636Resolving date-related logic problems . . . . . 637Using a century window . . . . . . . . 638Example: century window . . . . . . . 639Using internal bridging . . . . . . . . . 639Example: internal bridging . . . . . . . 640Moving to full field expansion. . . . . . . 641Example: converting files to expanded date<strong>for</strong>m . . . . . . . . . . . . . . 641Using year-first, year-only, and year-last date fields 643Compatible dates . . . . . . . . . . . 643Example: comparing year-first date fields . . . 644Using other date <strong>for</strong>mats . . . . . . . . 644Example: isolating the year . . . . . . . . 645Manipulating literals as dates . . . . . . . . 645Assumed century window . . . . . . . . 646Treatment of nondates . . . . . . . . . 647Setting triggers and limits . . . . . . . . . 648Example: using limits . . . . . . . . . 649Using sign conditions . . . . . . . . . 650Sorting and merging by date . . . . . . . . 650Example: sorting by date and time . . . . . 651Per<strong>for</strong>ming arithmetic on date fields. . . . . . 651Allowing <strong>for</strong> overflow from windowed datefields . . . . . . . . . . . . . . . 652Specifying the order of evaluation . . . . . 653Controlling date processing explicitly . . . . . 653Using DATEVAL . . . . . . . . . . . 654Using UNDATE . . . . . . . . . . . 654Example: DATEVAL . . . . . . . . . . 655Example: UNDATE . . . . . . . . . . 655Analyzing and avoiding date-related diagnosticmessages . . . . . . . . . . . . . . . 656Avoiding problems in processing dates . . . . . 657© Copyright IBM Corp. 1991, 2009 623


624 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 32. Interrupts and checkpoint/restartWhen programs run <strong>for</strong> an extended period of time, interruptions might haltprocessing be<strong>for</strong>e the end of a job. The checkpoint/restart functions of z/<strong>OS</strong> allowan interrupted program to be restarted at the beginning of a job step or at acheckpoint that you have set.Because the checkpoint/restart functions cause a lot of extra processing, use themonly when you anticipate interruptions caused by machine malfunctions, input oroutput errors, or intentional operator intervention.The checkpoint routine starts from the <strong>COBOL</strong> load module that contains yourprogram. While your program is running, the checkpoint routine creates records atpoints that you have designated using the <strong>COBOL</strong> RERUN clause. A checkpointrecord contains a snapshot of the in<strong>for</strong>mation in the registers and main storagewhen the program reached the checkpoint.The restart routine restarts an interrupted program. You can per<strong>for</strong>m a restart atany time after the program was interrupted: either immediately (automatic restart),or later (deferred restart).RELATED TASKS“Setting checkpoints”“Restarting programs” on page 628“Resubmitting jobs <strong>for</strong> restart” on page 631z/<strong>OS</strong> DFSMS: Checkpoint/RestartSetting checkpointsRELATED REFERENCES“DD statements <strong>for</strong> defining checkpoint data sets” on page 627“Messages generated during checkpoint” on page 628“Formats <strong>for</strong> requesting deferred restart” on page 630To set checkpoints, use job control statements and use the RERUN clause in theENVIRONMENT DIVISION. Associate each RERUN clause with a particular <strong>COBOL</strong> file.The RERUN clause indicates that a checkpoint record is to be written onto acheckpoint data set whenever a specified number of records in the <strong>COBOL</strong> file hasbeen processed or when END OF VOLUME is reached. You cannot use the RERUN clausewith files that have been defined with the EXTERNAL attribute.You can write checkpoint records from several <strong>COBOL</strong> files onto one checkpointdata set, but you must use a separate data set exclusively <strong>for</strong> checkpoint records.You cannot embed checkpoint records in one of your program data sets.Restrictions: A checkpoint data set must have sequential organization. You cannotwrite checkpoints on VSAM data sets or on data sets that are allocated toextended-<strong>for</strong>mat QSAM data sets. Also, a checkpoint cannot be taken if anyprogram in the run unit has an extended-<strong>for</strong>mat QSAM data set that is open.© Copyright IBM Corp. 1991, 2009 625


Checkpoint records are written on the checkpoint data set defined by a DDstatement. In the DD statement, you also choose the checkpoint method:Single (store single checkpoints)Only one checkpoint record exists at any given time. After the firstcheckpoint record is written, any succeeding checkpoint record overlaysthe previous one.This method is acceptable <strong>for</strong> most programs. You save space on thecheckpoint data set, and you can restart your program at the latestcheckpoint.Multiple (store multiple contiguous checkpoints)Checkpoints are recorded and numbered sequentially. Each checkpoint issaved.Use this method when you want to restart a program at a checkpoint otherthan the latest one taken.You must use the multiple checkpoint method <strong>for</strong> complete compliance toStandard <strong>COBOL</strong> 85.Checkpoints during sort operations have the following requirements:v If checkpoints are to be taken during a sort operation, add a DD statement <strong>for</strong>SORTCKPT in the job control procedure <strong>for</strong> execution.v You can take checkpoint records on ASCII-collated sorts, but the system-name thatindicates the checkpoint data set must not specify an ASCII file.RELATED TASKS“Using checkpoint/restart with DFSORT” on page 231“Designing checkpoints”“Testing <strong>for</strong> a successful checkpoint” on page 627RELATED REFERENCES“DD statements <strong>for</strong> defining checkpoint data sets” on page 627Designing checkpointsDesign your checkpoints at critical points in your program so that data can beeasily reconstructed. Do not change the contents of files between the time of acheckpoint and the time of the restart.In a program that uses disk files, design the program so that you can identifypreviously processed records. For example, consider a disk file that contains loanrecords that are periodically updated <strong>for</strong> interest due. If a checkpoint is taken,records are updated, and then the program is interrupted, you would want to testthat the records that are updated after the last checkpoint are not updated againwhen the program is restarted. To do this, set up a date field in each record, andupdate the field each time the record is processed. Then, after the restart, test thefield to determine whether the record was already processed.For efficient repositioning of a print file, take checkpoints on the file only afterprinting the last line of a page.626 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Testing <strong>for</strong> a successful checkpointAfter each input or output statement that issues a checkpoint, the RETURN-CODEspecial register is updated with the return code from the checkpoint routine.There<strong>for</strong>e, you can test whether the checkpoint was successful and decide whetherconditions are right to allow a restart.If the return code is greater than 4, an error has occurred in the checkpoint. Checkthe return code to prevent a restart that could cause incorrect output.RELATED REFERENCESz/<strong>OS</strong> DFSMS: Checkpoint/Restart (Return codes)DD statements <strong>for</strong> defining checkpoint data setsTo define checkpoint data sets, use DD statements.For tape://ddname DD DSNAME=data-set-name,// [VOLUME=SER=volser,]UNIT=device-type,// DISP=({NEW|MOD},PASS)For direct-access devices://ddname DD DSNAME=data-set-name,// [VOLUME=(PRIVATE,RETAIN,SER=volser),]// UNIT=device-type,SPACE=(subparms),// DISP=({NEW|MOD},PASS,KEEP)ddnameProvides a link to the DD statement. The same as the ddname portion of theassignment-name used in the <strong>COBOL</strong> RERUN clause.data-set-nameIdentifies the checkpoint data set to the restart procedure. The name givento the data set used to record checkpoint records.volser Identifies the volume by serial number.device-typeIdentifies the device.subparmsSpecifies the amount of track space needed <strong>for</strong> the data set.MOD Specifies the multiple contiguous checkpoint method.NEW Specifies the single checkpoint method.PASSKEEPPrevents deletion of the data set at successful completion of the job step,unless the job step is the last in the job. If it is the last step, the data set isdeleted.Keeps the data set if the job step abnormally ends.“Examples: defining checkpoint data sets”Examples: defining checkpoint data setsThe following examples show the JCL and <strong>COBOL</strong> coding you can use to definecheckpoint data sets.Chapter 32. Interrupts and checkpoint/restart 627


Writing single checkpoint records, using tape://CHECKPT DD DSNAME=CHECK1,VOLUME=SER=ND0003,// UNIT=TAPE,DISP=(NEW,KEEP),LABEL=(,NL)...ENVIRONMENT DIVISION....RERUN ON CHECKPT EVERY5000 RECORDS OF ACCT-FILE.Writing single checkpoint records, using disk://CHEK DD DSNAME=CHECK2,// VOLUME=(PRIVATE,RETAIN,SER=DB0030),// UNIT=3380,DISP=(NEW,KEEP),SPACE=(CYL,5)...ENVIRONMENT DIVISION....RERUN ON CHEK EVERY20000 RECORDS OF PAYCODE.RERUN ON CHEK EVERY30000 RECORDS OF IN-FILE.Writing multiple contiguous checkpoint records, using tape://CHEKPT DD DSNAME=CHECK3,VOLUME=SER=111111,// UNIT=TAPE,DISP=(MOD,PASS),LABEL=(,NL)...ENVIRONMENT DIVISION....RERUN ON CHEKPT EVERY10000 RECORDS OF PAY-FILE.Messages generated during checkpointRestarting programsThe system checkpoint routine advises the operator of the status of the checkpointstaken by displaying in<strong>for</strong>mative messages on the console.Each time a checkpoint is successfully completed, a message is displayed thatassociates the jobname (ddname, unit, volser) with the checkpoint taken (checkid).The control program assigns checkid as an eight-character string. The first characteris the letter C, followed by a decimal number that indicates the checkpoint. Forexample, the following message indicates the fourth checkpoint taken in the jobstep:checkid C0000004The system restart routine retrieves the in<strong>for</strong>mation recorded in a checkpointrecord, restores the contents of main storage and all registers, and restarts theprogram.You can begin the restart routine in one of two ways:v Automatically at the time an interruption stopped the programv At a later time as a deferred restartThe RD parameter of the job control language determines the type of restart. Youcan use the RD parameter on either the JOB or the EXEC statement. If coded on theJOB statement, the parameter overrides any RD parameters on the EXEC statement.628 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


To suppress both restart and writing checkpoints, code RD=NC.Restriction: If you try to restart at a checkpoint taken by a <strong>COBOL</strong> programduring a SORT or MERGE operation, an error message is issued and the restart iscanceled. Only checkpoints taken by DFSORT are valid.Data sets that have the SYSOUT parameter coded in their DD statements are handledin various ways depending on the type of restart.If the checkpoint data set is multivolume, include in the VOLUME parameter thesequence number of the volume on which the checkpoint entry was written. If thecheckpoint data set is on a 7-track tape with nonstandard labels or no labels, theSYSCHK DD statement must contain DCB=(TRTCH=C,. . .).RELATED TASKS“Using checkpoint/restart with DFSORT” on page 231“Requesting automatic restart”“Requesting deferred restart”Requesting automatic restartAutomatic restart occurs only at the latest checkpoint taken. If no checkpoint wastaken be<strong>for</strong>e interruption, automatic restart occurs at the beginning of the job step.Whenever automatic restart is to occur, the system repositions all devices exceptunit-record devices.If you want automatic restart, code RD=R or RD=RNC:v RD=R indicates that restart is to occur at the latest checkpoint. Code the RERUNclause <strong>for</strong> at least one data set in the program in order to record checkpoints. Ifno checkpoint is taken be<strong>for</strong>e interruption, restart occurs at the beginning of thejob step.v RD=RNC indicates that no checkpoint is to be written, and that any restart is tooccur at the beginning of the job step. In this case, RERUN clauses areunnecessary; if any are present, they are ignored.If you omit the RD parameter, the CHKPT macro instruction remains active, andcheckpoints can be taken during processing. If an interrupt occurs after the firstcheckpoint, automatic restart will occur.To restart automatically, a program must satisfy the following conditions:v In the program you must request restart by using the RD parameter or by takinga checkpoint.v An abend that terminated the job must return a code that allows restart.v The operator must authorize the restart.“Example: requesting a step restart” on page 631Requesting deferred restartDeferred restart can occur at any checkpoint, not necessarily the latest one taken.You can restart your program at a checkpoint other than at the beginning of the jobstep.Chapter 32. Interrupts and checkpoint/restart 629


When a deferred restart has been successfully completed, the system displays amessage on the console stating that the job has been restarted. Control is thengiven to your program.If you want deferred restart, code the RD parameter as RD=NR. This <strong>for</strong>m of theparameter suppresses automatic restart but allows a checkpoint record to bewritten provided that a RERUN clause was coded.Request a deferred restart by using the RESTART parameter on the JOB card and aSYSCHK DD statement to identify the checkpoint data set. If a SYSCHK DD statement ispresent in a job and the JOB statement does not contain the RESTART parameter, theSYSCHK DD statement is ignored. If a RESTART parameter without the CHECKIDsubparameter is included in a job, a SYSCHK DD statement must not appear be<strong>for</strong>ethe first EXEC statement <strong>for</strong> the job.“Example: restarting a job at a specific checkpoint step” on page 631RELATED REFERENCES“Formats <strong>for</strong> requesting deferred restart”Formats <strong>for</strong> requesting deferred restartThe <strong>for</strong>mats <strong>for</strong> the RESTART parameter of the JOB statement and the SYSCHK DDstatements are as shown below.//jobname JOB MSGLEVEL=1,RESTART=(request[,checkid])//SYSCHK DD DSNAME=data-set-name,// DISP=OLD[,UNIT=device-type,// VOLUME=SER=volser]MSGLEVEL=1 (or MSGLEVEL=(1,y))MSGLEVEL is required.RESTART=(request,[checkid])Identifies the particular checkpoint at which restart is to occur.requestTakes one of the following <strong>for</strong>ms:* Indicates restart at the beginning of the job.stepnameIndicates restart at the beginning of a job step.stepname.procstepIndicates restart at a procedure step within the job step.checkidIdentifies the checkpoint where restart is to occur.SYSCHK The ddname used to identify a checkpoint data set to the control program.The SYSCHK DD statement must immediately precede the first EXECstatement of the resubmitted job, and must follow any JOBLIB statement.data-set-nameIdentifies the checkpoint data set. It must be the same name thatwas used when the checkpoint was taken.device-type and volserIdentify the device type and the serial number of the volume thatcontains the checkpoint data set.630 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Example: requesting a deferred restart”Example: requesting a deferred restartThis example shows JCL to restart the GO step of an IGYWCLG procedure atcheckpoint identifier (CHECKID) C0000003.//jobname JOB MSGLEVEL=1,RESTART=(stepname.GO,C0000003)//SYSCHK DD DSNAME=CHEKPT,// DISP=OLD[,UNIT=3380,VOLUME=SER=111111]...Resubmitting jobs <strong>for</strong> restartWhen you resubmit a job <strong>for</strong> restart, be careful with any DD statements that mightaffect the execution of the restarted job step. The restart routine uses in<strong>for</strong>mationfrom DD statements in the resubmitted job to reset files <strong>for</strong> use after restart.If you want a data set to be deleted at the end of a job step, give it a conditionaldisposition of PASS or KEEP (rather than DELETE). This disposition allows the dataset to be available if an interruption <strong>for</strong>ces a restart. If you want to restart a job atthe beginning of a step, you must first discard any data set created (defined as NEWin a DD statement) in the previous run, or change the DD statement to mark the dataset as OLD.The system automatically repositions input data sets that are on tape or disk.“Example: resubmitting a job <strong>for</strong> a step restart” on page 632“Example: resubmitting a job <strong>for</strong> a checkpoint restart” on page 632Example: restarting a job at a specific checkpoint stepThis example shows a sequence of job control statements <strong>for</strong> restarting a job at aspecific step.//PAYROLL JOB MSGLEVEL=1,REGION=80K,// RESTART=(STEP1,CHECKPT4)//JOBLIB DD DSNAME=PRIV.LIB3,DISP=OLD//SYSCHK DD DSNAME=CHKPTLIB,// [UNIT=TAPE,VOL=SER=456789,]// DISP=(OLD,KEEP)//STEP1 EXEC PGM=PROG4,TIME=5Example: requesting a step restartThis example shows the use of the RD parameter, which requests step restart <strong>for</strong>any abnormally terminated job step.//J1234 JOB 386,SMITH,MSGLEVEL=1,RD=R//S1 EXEC PGM=MYPROG//INDATA DD DSNAME=INVENT[,UNIT=TAPE],DISP=OLD,// [VOLUME=SER=91468,]// LABEL=RETPD=14//REPORT DD SYSOUT=A//WORK DD DSNAME=T91468,DISP=(,,KEEP),// UNIT=SYSDA,SPACE=(3000,(5000,500)),// VOLUME=(PRIVATE,RETAIN,,6)//DDCKPNT DD UNIT=TAPE,DISP=(MOD,PASS,CATLG),// DSNAME=C91468,LABEL=(,NL)Chapter 32. Interrupts and checkpoint/restart 631


The DDCKPNT DD statement defines a checkpoint data set. For this step, after a RERUNclause is per<strong>for</strong>med, only automatic checkpoint restart can occur unless a CHKPTcancel is issued.Example: resubmitting a job <strong>for</strong> a step restartThis example shows the changes that you might make to the JCL be<strong>for</strong>e youresubmit a job <strong>for</strong> step restart.//J3412 JOB 386,SMITH,MSGLEVEL=1,RD=R,RESTART=*//S1 EXEC PGM=MYPROG//INDATA DD DSNAME=INVENT[,UNIT=TAPE],DISP=OLD,// [VOLUME=SER=91468,]LABEL=RETPD=14//REPORT DD SYSOUT=A//WORK DD DSNAME=S91468,// DISP=(,,KEEP),UNIT=SYSDA,// SPACE=(3000,(5000,500)),// VOLUME=(PRIVATE,RETAIN,,6)//DDCHKPNT DD UNIT=TAPE,DISP=(MOD,PASS,CATLG),// DSNAME=R91468,LABEL=(,NL)The following changes were made in the example above:v The job name has been changed (from J1234 to J3412) to distinguish the originaljob from the restarted job.v The RESTART parameter has been added to the JOB statement, and indicates thatrestart is to begin with the first job step.v The WORK DD statement was originally assigned a conditional disposition of KEEP<strong>for</strong> this data set:– If the step terminated normally in the previous run of the job, the data setwas deleted, and no changes need to be made to this statement.– If the step abnormally terminated, the data set was kept. In that case, define anew data set (S91468 instead of T91468, as shown), or change the status of thedata set to OLD be<strong>for</strong>e resubmitting the job.v A new data set (R91468 instead of C91468) has also been defined as thecheckpoint data set.“Example: requesting a step restart” on page 631Example: resubmitting a job <strong>for</strong> a checkpoint restartThis example shows the changes that you might make to JCL be<strong>for</strong>e you resubmita job <strong>for</strong> checkpoint restart.//J3412 JOB 386,SMITH,MSGLEVEL=1,RD=R,// RESTART=(*,C0000002)//SYSCHK DD DSNAME=C91468,DISP=OLD//S1 EXEC PGM=MYPROG//INDATA DD DSNAME=INVENT,UNIT=TAPE,DISP=OLD,// VOLUME=SER=91468,LABEL=RETPD=14//REPORT DD SYSOUT=A//WORK DD DSNAME=T91468,DISP=(,,KEEP),// UNIT=SYSDA,SPACE=(3000,(5000,500)),// VOLUME=(PRIVATE,RETAIN,,6)//DDCKPNT DD UNIT=TAPE,DISP=(MOD,KEEP,CATLG),// DSNAME=C91468,LABEL=(,NL)The following changes were made in the example above:v The job name has been changed (from J1234 to J3412) to distinguish the originaljob from the restarted job.632 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvThe RESTART parameter has been added to the JOB statement, and indicates thatrestart is to begin with the first step at the checkpoint entry named C0000002.The DD statement DDCKPNT was originally assigned a conditional disposition ofCATLG <strong>for</strong> the checkpoint data set:– If the step terminated normally in the previous run of the job, the data setwas kept. In that case, the SYSCHK DD statement must contain all of thein<strong>for</strong>mation necessary <strong>for</strong> retrieving the checkpoint data set.– If the job abnormally terminated, the data set was cataloged. In that case, theonly parameters required on the SYSCHK DD statement are DSNAME and DISP asshown.If a checkpoint is taken in a job that is running when V=R is specified, the jobcannot be restarted until adequate nonpageable dynamic storage becomesavailable.Chapter 32. Interrupts and checkpoint/restart 633


634 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 33. Processing two-digit-year datesWith the millennium language extensions (MLE), you can make simple changes inyour <strong>COBOL</strong> programs to define date fields. The compiler recognizes and acts onthese dates by using a century window to ensure consistency.Use the following steps to implement automatic date recognition in a <strong>COBOL</strong>program:1. Add the DATE FORMAT clause to the data description entries of the data items inthe program that contain dates. You must identify all dates with DATE FORMATclauses, even those that are not used in comparisons.2. To expand dates, use MOVE or COMPUTE statements to copy the contents ofwindowed date fields to expanded date fields.3. If necessary, use the DATEVAL and UNDATE intrinsic functions to convert betweendate fields and nondates.4. Use the YEARWINDOW compiler option to set the century window as either a fixedwindow or a sliding window.5. Compile the program with the DATEPROC(FLAG) compiler option, and review thediagnostic messages to see if date processing has produced any unexpectedside effects.6. When the compilation has only in<strong>for</strong>mation-level diagnostic messages, you canrecompile the program with the DATEPROC(NOFLAG) compiler option to producea clean listing.You can use certain programming techniques to take advantage of date processingand control the effects of using date fields such as when comparing dates, sortingand merging by date, and per<strong>for</strong>ming arithmetic operations involving dates. Themillennium language extensions support year-first, year-only, and year-last datefields <strong>for</strong> the most common operations on date fields: comparisons, moving andstoring, and incrementing and decrementing.RELATED CONCEPTS“Millennium language extensions (MLE)” on page 636RELATED TASKS“Resolving date-related logic problems” on page 637“Using year-first, year-only, and year-last date fields” on page 643“Manipulating literals as dates” on page 645“Setting triggers and limits” on page 648“Sorting and merging by date” on page 650“Per<strong>for</strong>ming arithmetic on date fields” on page 651“Controlling date processing explicitly” on page 653“Analyzing and avoiding date-related diagnostic messages” on page 656“Avoiding problems in processing dates” on page 657RELATED REFERENCES“DATEPROC” on page 315“YEARWINDOW” on page 360DATE FORMAT clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)© Copyright IBM Corp. 1991, 2009 635


Millennium language extensions (MLE)The term millennium language extensions (MLE) refers to the features of <strong>Enterprise</strong><strong>COBOL</strong> that the DATEPROC compiler option activates to help with logic problemsthat involve dates in the year 2000 and beyond.When enabled, the extensions include:v The DATE FORMAT clause. Add this clause to items in the DATA DIVISION toidentify date fields and to specify the location of the year component within thedate.There are several restrictions on use of the DATE FORMAT clause; <strong>for</strong> example, youcannot specify it <strong>for</strong> items that have USAGE NATIONAL. See the related referencesbelow <strong>for</strong> details.v The reinterpretation as a date field of the function return value <strong>for</strong> the followingintrinsic functions:– DATE-OF-INTEGER– DATE-TO-YYYYMMDD– DAY-OF-INTEGER– DAY-TO-YYYYDDD– YEAR-TO-YYYYv The reinterpretation as a date field of the conceptual data items DATE, DATEYYYYMMDD, DAY, and DAY YYYYDDD in the following <strong>for</strong>ms of the ACCEPT statement:– ACCEPT identifier FROM DATE– ACCEPT identifier FROM DATE YYYYMMDD– ACCEPT identifier FROM DAY– ACCEPT identifier FROM DAY YYYYDDDv The intrinsic functions UNDATE and DATEVAL, used <strong>for</strong> selective reinterpretation ofdate fields and nondates.v The intrinsic function YEARWINDOW, which retrieves the starting year of thecentury window set by the YEARWINDOW compiler option.The DATEPROC compiler option enables special date-oriented processing of identifieddate fields. The YEARWINDOW compiler option specifies the 100-year window (thecentury window) to use <strong>for</strong> interpreting two-digit windowed years.RELATED CONCEPTS“Principles and objectives of these extensions”RELATED REFERENCES“DATEPROC” on page 315“YEARWINDOW” on page 360Restrictions on using date fields (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Principles and objectives of these extensionsTo gain the most benefit from the millennium language extensions, you need tounderstand the reasons <strong>for</strong> their introduction into the <strong>COBOL</strong> language.The millennium language extensions focus on a few key principles:v Programs to be recompiled with date semantics are fully tested and valuableassets of the enterprise. Their only relevant limitation is that two-digit years inthe programs are restricted to the range 1900-1999.636 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvNo special processing is done <strong>for</strong> the nonyear part of dates. That is why thenonyear part of the supported date <strong>for</strong>mats is denoted by Xs. To do otherwisemight change the meaning of existing programs. The only date-sensitivesemantics that are provided involve automatically expanding (and contracting)the two-digit year part of dates with respect to the century window <strong>for</strong> theprogram.Dates with four-digit year parts are generally of interest only when used incombination with windowed dates. Otherwise there is little difference betweenfour-digit year dates and nondates.Based on these principles, the millennium language extensions are designed tomeet several objectives. You should evaluate the objectives that you need to meetin order to resolve your date-processing problems, and compare them with theobjectives of the millennium language extensions, to determine how yourapplication can benefit from them. You should not consider using the extensions innew applications or in enhancements to existing applications, unless theapplications are using old data that cannot be expanded until later.The objectives of the millennium language extensions are as follows:v Extend the useful life of your application programs as they are currentlyspecified.v Keep source changes to a minimum, preferably limited to augmenting thedeclarations of date fields in the DATA DIVISION. To implement the centurywindow solution, you should not need to change the program logic in thePROCEDURE DIVISION.v Preserve the existing semantics of the programs when adding date fields. Forexample, when a date is expressed as a literal, as in the following statement, theliteral is considered to be compatible (windowed or expanded) with the datefield to which it is compared:If Expiry-Date Greater Than 980101 ...vvBecause the existing program assumes that two-digit-year dates expressed asliterals are in the range 1900-1999, the extensions do not change this assumption.The windowing feature is not intended <strong>for</strong> long-term use. It can extend theuseful life of applications as a start toward a long-term solution that can beimplemented later.The expanded date field feature is intended <strong>for</strong> long-term use, as an aid <strong>for</strong>expanding date fields in files and databases.The extensions do not provide fully specified or complete date-oriented data types,with semantics that recognize, <strong>for</strong> example, the month and day parts of Gregoriandates. They do, however, provide special semantics <strong>for</strong> the year part of dates.Resolving date-related logic problemsYou can adopt any of three approaches to assist with date-processing problems:use a century window, internal bridging, or full field expansion.Century windowYou define a century window and specify the fields that contain windoweddates. The compiler then interprets the two-digit years in these data fieldsaccording to the century window.Internal bridgingIf your files and databases have not yet been converted to four-digit-yearChapter 33. Processing two-digit-year dates 637


dates, but you prefer to use four-digit expanded-year logic in yourprograms, you can use an internal bridging technique to process the datesas four-digit-year dates.Full field expansionThis solution involves explicitly expanding two-digit-year date fields tocontain full four-digit years in your files and databases and then usingthese fields in expanded <strong>for</strong>m in your programs. This is the only methodthat assures reliable date processing <strong>for</strong> all applications.You can use the millennium language extensions with each approach to achieve asolution, but each has advantages and disadvantages, as shown below.Table 92. Advantages and disadvantages of Year 2000 solutionsAspect Century window Internal bridging Full field expansionImplementationFast and easy butmight not suit allapplicationsSome risk ofcorrupting dataMust ensure that changesto databases, copybooks,and programs aresynchronizedTestingLess testing isrequired because nochanges to programlogicPrograms canfunction beyond2000, but not along-term solutionTesting is easybecause changes toprogram logic arestraight<strong>for</strong>wardDuration of fixPrograms canfunction beyond2000, but not apermanent solutionPermanent solutionPer<strong>for</strong>manceMight degradeper<strong>for</strong>manceGood per<strong>for</strong>manceBest per<strong>for</strong>manceMaintenanceMaintenance is easier.“Example: century window” on page 639“Example: internal bridging” on page 640“Example: converting files to expanded date <strong>for</strong>m” on page 641RELATED TASKS“Using a century window”“Using internal bridging” on page 639“Moving to full field expansion” on page 641Using a century windowA century window is a 100-year interval, such as 1950-2049, within which anytwo-digit year is unique. For windowed date fields, you specify the centurywindow start date by using the YEARWINDOW compiler option.When the DATEPROC option is in effect, the compiler applies this window totwo-digit date fields in the program. For example, with a century window of1930-2029, <strong>COBOL</strong> interprets two-digit years as follows:v Year values from 00 through 29 are interpreted as years 2000-2029.v Year values from 30 through 99 are interpreted as years 1930-1999.638 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


To implement this century window, you use the DATE FORMAT clause to identify thedate fields in your program and use the YEARWINDOW compiler option to define thecentury window as either a fixed window or a sliding window:vvFor a fixed window, specify a four-digit year between 1900 and 1999 as theYEARWINDOW option value.For example, YEARWINDOW(1950) defines a fixed window of 1950-2049.For a sliding window, specify a negative integer from -1 through -99 as theYEARWINDOW option value.For example, YEARWINDOW(-50) defines a sliding window that starts 50 yearsbe<strong>for</strong>e the year in which the program is running. So if the program is running in2009, then the century window is 1959-2058; in 2010 it automatically becomes1960-2059, and so on.The compiler automatically applies the century window to operations on the datefields that you have identified. You do not need any extra program logic toimplement the windowing.“Example: century window”RELATED REFERENCES“DATEPROC” on page 315“YEARWINDOW” on page 360DATE FORMAT clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Restrictions on using date fields (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: century windowThe following example shows (in bold) how to modify a program with the DATEFORMAT clause to use the automatic date windowing capability.CBL LIB,QUOTE,NOOPT,DATEPROC(FLAG),YEARWINDOW(-60)...01 Loan-Record.05 Member-Number Pic X(8).05 DVD-ID Pic X(8).05 Date-Due-Back Pic X(6) Date Format yyxxxx.05 Date-Returned Pic X(6) Date Format yyxxxx....If Date-Returned > Date-Due-Back ThenPer<strong>for</strong>m Fine-Member.There are no changes to the PROCEDURE DIVISION. The addition of the DATE FORMATclause on the two date fields means that the compiler recognizes them aswindowed date fields, and there<strong>for</strong>e applies the century window when processingthe IF statement. For example, if Date-Due-Back contains 090102 (January 2, 2009)and Date-Returned contains 081231 (December 31, 2008), Date-Returned is less than(earlier than) Date-Due-Back, so the program does not per<strong>for</strong>m the Fine-Memberparagraph. (The program checks whether a DVD was returned on time.)Using internal bridgingFor internal bridging, you need to structure your program appropriately.Do the following steps:1. Read the input files with two-digit-year dates.Chapter 33. Processing two-digit-year dates 639


2. Declare these two-digit dates as windowed date fields and move them toexpanded date fields, so that the compiler automatically expands them tofour-digit-year dates.3. In the main body of the program, use the four-digit-year dates <strong>for</strong> all dateprocessing.4. Window the dates back to two-digit years.5. Write the two-digit-year dates to the output files.This process provides a convenient migration path to a full expanded-datesolution, and can have per<strong>for</strong>mance advantages over using windowed dates.When you use this technique, your changes to the program logic are minimal. Yousimply add statements to expand and contract the dates, and change thestatements that refer to dates to use the four-digit-year date fields inWORKING-STORAGE instead of the two-digit-year fields in the records.Because you are converting the dates back to two-digit years <strong>for</strong> output, youshould allow <strong>for</strong> the possibility that the year is outside the century window. Forexample, if a date field contains the year 2020, but the century window is1920-2019, then the date is outside the window. Simply moving the year to atwo-digit-year field will be incorrect. To protect against this problem, you can use aCOMPUTE statement to store the date, with the ON SIZE ERROR phrase to detectwhether the date is outside the century window.“Example: internal bridging”RELATED TASKS“Using a century window” on page 638“Per<strong>for</strong>ming arithmetic on date fields” on page 651“Moving to full field expansion” on page 641Example: internal bridgingThe following example shows (in bold) how a program can be changed toimplement internal bridging.CBL DATEPROC(FLAG),YEARWINDOW(-60)...File Section.FD Customer-File.01 Cust-Record.05 Cust-Number Pic 9(9) Binary....05 Cust-Date Pic 9(6) Date Format yyxxxx.Working-Storage Section.77 Exp-Cust-Date Pic 9(8) Date Format yyyyxxxx....Procedure Division.Open I-O Customer-File.Read Customer-File.Move Cust-Date to Exp-Cust-Date....*=====================================================** Use expanded date in the rest of the program logic **=====================================================*...Compute Cust-Date = Exp-Cust-Date640 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


On Size ErrorDisplay "Exp-Cust-Date outside century window"End-ComputeRewrite Cust-Record.Moving to full field expansionUsing the millennium language extensions, you can move gradually toward asolution that fully expands the date field.Do the following steps:1. Apply the century window solution, and use this solution until you have theresources to implement a more permanent solution.2. Apply the internal bridging solution. This way you can use expanded dates inyour programs while your files continue to hold dates in two-digit-year <strong>for</strong>m.You can progress more easily to a full-field-expansion solution because therewill be no further changes to the logic in the main body of the programs.3. Change the file layouts and database definitions to use four-digit-year dates.4. Change your <strong>COBOL</strong> copybooks to reflect these four-digit-year date fields.5. Run a utility program (or special-purpose <strong>COBOL</strong> program) to copy files fromthe old <strong>for</strong>mat to the new <strong>for</strong>mat.6. Recompile your programs and do regression testing and date testing.After you have completed the first two steps, you can repeat the remaining stepsany number of times. You do not need to change every date field in every file atthe same time. Using this method, you can select files <strong>for</strong> progressive conversionbased on criteria such as business needs or interfaces with other applications.When you use this method, you need to write special-purpose programs to convertyour files to expanded-date <strong>for</strong>m.“Example: converting files to expanded date <strong>for</strong>m”Example: converting files to expanded date <strong>for</strong>mThe following example shows a simple program that copies from one file toanother while expanding the date fields. The record length of the output file islarger than that of the input file because the dates are expanded.CBL LIB,QUOTE,NOOPT,DATEPROC(FLAG),YEARWINDOW(-80)************************************************** CONVERT - Read a file, convert the date **** fields to expanded <strong>for</strong>m, write **** the expanded records to a new **** file. **************************************************IDENTIFICATION DIVISION.PROGRAM-ID. CONVERT.ENVIRONMENT DIVISION.INPUT-OUTPUT SECTION.FILE-CONTROL.SELECT INPUT-FILEASSIGN TO INFILEFILE STATUS IS INPUT-FILE-STATUS.SELECT OUTPUT-FILEASSIGN TO OUTFILEChapter 33. Processing two-digit-year dates 641


DATA DIVISION.FILE SECTION.FDFILE STATUS IS OUTPUT-FILE-STATUS.INPUT-FILERECORDING MODE IS F.01 INPUT-RECORD.03 CUST-NAME.05 FIRST-NAME PIC X(10).05 LAST-NAME PIC X(15).03 ACCOUNT-NUM PIC 9(8).03 DUE-DATE PIC X(6) DATE FORMAT YYXXXX. (1)03 REMINDER-DATE PIC X(6) DATE FORMAT YYXXXX.03 DUE-AMOUNT PIC S9(5)V99 COMP-3.FD OUTPUT-FILERECORDING MODE IS F.01 OUTPUT-RECORD.03 CUST-NAME.05 FIRST-NAME PIC X(10).05 LAST-NAME PIC X(15).03 ACCOUNT-NUM PIC 9(8).03 DUE-DATE PIC X(8) DATE FORMAT YYYYXXXX. (2)03 REMINDER-DATE PIC X(8) DATE FORMAT YYYYXXXX.03 DUE-AMOUNT PIC S9(5)V99 COMP-3.WORKING-STORAGE SECTION.01 INPUT-FILE-STATUS PIC 99.01 OUTPUT-FILE-STATUS PIC 99.PROCEDURE DIVISION.OPEN INPUT INPUT-FILE.OPEN OUTPUT OUTPUT-FILE.READ-RECORD.READ INPUT-FILEAT END GO TO CL<strong>OS</strong>E-FILES.MOVE CORRESPONDING INPUT-RECORD TO OUTPUT-RECORD. (3)WRITE OUTPUT-RECORD.GO TO READ-RECORD.CL<strong>OS</strong>E-FILES.CL<strong>OS</strong>E INPUT-FILE.CL<strong>OS</strong>E OUTPUT-FILE.EXIT PROGRAM.END PROGRAM CONVERT.Notes:(1) The fields DUE-DATE and REMINDER-DATE in the input record are Gregoriandates with two-digit year components. They are defined with a DATEFORMAT clause so that the compiler recognizes them as windowed datefields.(2) The output record contains the same two fields in expanded date <strong>for</strong>mat.They are defined with a DATE FORMAT clause so that the compiler treatsthem as four-digit-year date fields.(3) The MOVE CORRESPONDING statement moves each item in INPUT-RECORD to itsmatching item in OUTPUT-RECORD. When the two windowed date fields are642 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


moved to the corresponding expanded date fields, the compiler expandsthe year values using the current century window.Using year-first, year-only, and year-last date fieldsWhen you compare two date fields of either year-first or year-only types, the twodates must be compatible; that is, they must have the same number of nonyearcharacters. The number of digits <strong>for</strong> the year component need not be the same.A year-first date field is a date field whose DATE FORMAT specification consists of YYor YYYY, followed by one or more Xs. The date <strong>for</strong>mat of a year-only date field hasjust the YY or YYYY. Ayear-last date field is a date field whose DATE FORMAT clausespecifies one or more Xs preceding YY or YYYY.Year-last date <strong>for</strong>mats are commonly used to display dates, but are less usefulcomputationally because the year, which is the most significant part of the date, isin the least significant position of the date representation.If your version of DFSORT (or equivalent) has the appropriate capabilities,year-last dates are supported as windowed keys in SORT or MERGE statements. Apartfrom sort and merge operations, functional support <strong>for</strong> year-last date fields islimited to equal or unequal comparisons and certain kinds of assignment. Theoperands must be either dates with identical (year-last) date <strong>for</strong>mats, or a date anda nondate. The compiler does not provide automatic windowing <strong>for</strong> operations onyear-last dates. When an unsupported usage (such as arithmetic on year-last dates)occurs, the compiler provides an error-level message.If you need more general date-processing capability <strong>for</strong> year-last dates, you shouldisolate and operate on the year part of the date.“Example: comparing year-first date fields” on page 644RELATED CONCEPTS“Compatible dates”RELATED TASKS“Sorting and merging by date” on page 650“Using other date <strong>for</strong>mats” on page 644Compatible datesThe meaning of the term compatible dates depends on whether the usage occurs inthe DATA DIVISION or the PROCEDURE DIVISION.The DATA DIVISION usage deals with the declaration of date fields, and the rulesthat govern <strong>COBOL</strong> language elements such as subordinate data items and theREDEFINES clause. In the following example, Review-Date and Review-Year arecompatible because Review-Year can be declared as a subordinate data item toReview-Date:01 Review-Record.03 Review-Date Date Format yyxxxx.05 Review-Year Pic XX Date Format yy.05 Review-M-D Pic XXXX.The PROCEDURE DIVISION usage deals with how date fields can be used together inoperations such as comparisons, moves, and arithmetic expressions. For year-firstChapter 33. Processing two-digit-year dates 643


and year-only date fields to be considered compatible, date fields must have thesame number of nonyear characters. For example, a field with DATE FORMAT YYXXXXis compatible with another field that has the same date <strong>for</strong>mat and with a YYYYXXXXfield, but not with a YYXXX field.Year-last date fields must have identical DATE FORMAT clauses. In particular,operations between windowed date fields and expanded year-last date fields arenot allowed. For example, you can move a date field that has a date <strong>for</strong>mat ofXXXXYY to another XXXXYY date field, but not to a date field that has a <strong>for</strong>mat ofXXXXYYYY.You can per<strong>for</strong>m operations on date fields, or on a combination of date fields andnondates, provided that the date fields in the operation are compatible. Forexample, assume the following definitions:01 Date-Gregorian-Win Pic 9(6) Packed-Decimal Date Format yyxxxx.01 Date-Julian-Win Pic 9(5) Packed-Decimal Date Format yyxxx.01 Date-Gregorian-Exp Pic 9(8) Packed-Decimal Date Format yyyyxxxx.The following statement is inconsistent because the number of nonyear digits isdifferent between the two fields:If Date-Gregorian-Win Less than Date-Julian-Win ...The following statement is accepted because the number of nonyear digits is thesame <strong>for</strong> both fields:If Date-Gregorian-Win Less than Date-Gregorian-Exp ...In this case the century window is applied to the windowed date field(Date-Gregorian-Win) to ensure that the comparison is meaningful.When a nondate is used in conjunction with a date field, the nondate is eitherassumed to be compatible with the date field or is treated as a simple numericvalue.Example: comparing year-first date fieldsThe following example shows a windowed date field that is compared with anexpanded date field.77 Todays-Date Pic X(8) Date Format yyyyxxxx.01 Loan-Record.05 Date-Due-Back Pic X(6) Date Format yyxxxx....If Date-Due-Back > Todays-Date Then ...The century window is applied to Date-Due-Back. Todays-Date must have a DATEFORMAT clause to define it as an expanded date field. If it did not, it would betreated as a nondate field and would there<strong>for</strong>e be considered to have the samenumber of year digits as Date-Due-Back. The compiler would apply the assumedcentury window of 1900-1999, which would create an inconsistent comparison.Using other date <strong>for</strong>matsTo be eligible <strong>for</strong> automatic windowing, a date field should contain a two-digityear as the first or only part of the field. The remainder of the field, if present,must contain between one and four characters, but its content is not important.644 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If there are date fields in your application that do not fit these criteria, you mighthave to make some code changes to define just the year part of the date as a datefield with the DATE FORMAT clause. Some examples of these types of date <strong>for</strong>matsare:vvA seven-character field that consists of a two-digit year, three characters thatcontain an abbreviation of the month, and two digits <strong>for</strong> the day of the month.This <strong>for</strong>mat is not supported because date fields can have only one through fournonyear characters.A Gregorian date of the <strong>for</strong>m DDMMYY. Automatic windowing is not providedbecause the year component is not the first part of the date. Year-last dates suchas these are fully supported as windowed keys in SORT or MERGE statements, andare also supported in a limited number of other <strong>COBOL</strong> operations.If you need to use date windowing in cases like these, you will need to add somecode to isolate the year portion of the date.Example: isolating the yearThe following example shows how you can isolate the year portion of a data fieldthat is in the <strong>for</strong>m DDMMYY.03 Last-Review-Date Pic 9(6).03 Next-Review-Date Pic 9(6)....Add 1 to Last-Review-Date Giving Next-Review-Date.In the code above, if Last-Review-Date contains 230109 (January 23, 2009), thenNext-Review-Date will contain 230110 (January 23, 2010) after the ADD statement isexecuted. This is a simple method <strong>for</strong> setting the next date <strong>for</strong> an annual review.However, if Last-Review-Date contains 230199, then adding 1 yields 230200, whichis not the desired result.Because the year is not the first part of these date fields, the DATE FORMAT clausecannot be applied without some code to isolate the year component. In the nextexample, the year component of both date fields has been isolated so that <strong>COBOL</strong>can apply the century window and maintain consistent results:03 Last-Review-Date Date Format xxxxyy.05 Last-R-DDMM Pic 9(4).05 Last-R-YY Pic 99 Date Format yy.03 Next-Review-Date Date Format xxxxyy.05 Next-R-DDMM Pic 9(4).05 Next-R-YY Pic 99 Date Format yy....Move Last-R-DDMM to Next-R-DDMM.Add 1 to Last-R-YY Giving Next-R-YY.Manipulating literals as datesIf a windowed date field has a level-88 condition-name associated with it, then theliteral in the VALUE clause is windowed against the century window of the compileunit rather than against the assumed century window of 1900-1999.For example, suppose you have these data definitions:05 Date-Due Pic 9(6) Date Format yyxxxx.88 Date-Target Value 091220.Chapter 33. Processing two-digit-year dates 645


If the century window is 1950-2049, and the contents of Date-Due are 091220(representing December 20, 2009), then the first condition below evaluates to true,but the second condition evaluates to false:If Date-Target. . .If Date-Due = 091220The literal 091220 is treated as a nondate; there<strong>for</strong>e it is windowed against theassumed century window of 1900-1999, and represents December 20, 1909. Butwhere the literal is specified in the VALUE clause of a level-88 condition-name, theliteral becomes part of the data item to which it is attached. Because this data itemis a windowed date field, the century window is applied whenever it is referenced.You can also use the DATEVAL intrinsic function in a comparison expression toconvert a literal to a date field. The resulting date field is treated as either awindowed date field or an expanded date field to ensure a consistent comparison.For example, using the above definitions, both of the following conditions evaluateto true:If Date-Due = Function DATEVAL (091220 "YYXXXX")If Date-Due = Function DATEVAL (20091220 "YYYYXXXX")With a level-88 condition-name, you can specify the THRU option on the VALUEclause, but you must specify a fixed century window on the YEARWINDOW compileroption rather than a sliding window. For example:05 Year-Field Pic 99 Date Format yy.88 In-Range Value 98 Thru 06.With this <strong>for</strong>m, the windowed value of the second item in the range must begreater than the windowed value of the first item. However, the compiler canverify this difference only if the YEARWINDOW compiler option specifies a fixedcentury window (<strong>for</strong> example, YEARWINDOW(1940) rather than YEARWINDOW(-69)).The windowed order requirement does not apply to year-last date fields. If youspecify a condition-name VALUE clause with the THROUGH phrase <strong>for</strong> a year-last datefield, the two literals must follow normal <strong>COBOL</strong> rules. That is, the first literalmust be less than the second literal.RELATED CONCEPTS“Assumed century window”“Treatment of nondates” on page 647RELATED TASKS“Controlling date processing explicitly” on page 653Assumed century windowWhen a program uses windowed date fields, the compiler applies the centurywindow that is defined by the YEARWINDOW compiler option to the compilation unit.When a windowed date field is used in conjunction with a nondate, and thecontext demands that the nondate be treated as a windowed date, the compileruses an assumed century window to resolve the nondate field.The assumed century window is 1900-1999, which typically is not the same as thecentury window <strong>for</strong> the compilation unit.646 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In many cases, particularly <strong>for</strong> literal nondates, this assumed century window isthe correct choice. In the following construct, the literal should retain its originalmeaning of January 1, 1972, and not change to 2072 if the century window is, <strong>for</strong>example, 1975-2074:01 Manufacturing-Record.03 Makers-Date Pic X(6) Date Format yyxxxx....If Makers-Date Greater than "720101" ...Even if the assumption is correct, it is better to make the year explicit andeliminate the warning-level diagnostic message (which results from applying theassumed century window) by using the DATEVAL intrinsic function:If Makers-Date Greater thanFunction Dateval("19720101" "YYYYXXXX") ...In some cases, the assumption might not be correct. For the following example,assume that Project-Controls is in a copy member that is used by otherapplications that have not yet been upgraded <strong>for</strong> year 2000 processing, andthere<strong>for</strong>e Date-Target cannot have a DATE FORMAT clause:01 Project-Controls.03 Date-Target Pic 9(6)....01 Progress-Record.03 Date-Complete Pic 9(6) Date Format yyxxxx....If Date-Complete Less than Date-Target ...In the example above, the following three conditions need to be true to makeDate-Complete earlier than (less than) Date-Target:v The century window is 1910-2009.v Date-Complete is 991202 (Gregorian date: December 2, 1999).v Date-Target is 000115 (Gregorian date: January 15, 2000).However, because Date-Target does not have a DATE FORMAT clause, it is a nondate.There<strong>for</strong>e, the century window applied to it is the assumed century window of1900-1999, and it is processed as January 15, 1900. So Date-Complete will be greaterthan Date-Target, which is not the desired result.In this case, you should use the DATEVAL intrinsic function to convert Date-Targetto a date field <strong>for</strong> this comparison. For example:If Date-Complete Less thanFunction Dateval (Date-Target "YYXXXX") ...RELATED TASKS“Controlling date processing explicitly” on page 653Treatment of nondatesHow the compiler treats a nondate depends upon its context.The following items are nondates:v A literal value.v A data item whose data description does not include a DATE FORMAT clause.v The results (intermediate or final) of some arithmetic expressions. For example,the difference of two date fields is a nondate, whereas the sum of a date fieldand a nondate is a date field.Chapter 33. Processing two-digit-year dates 647


vThe output from the UNDATE intrinsic function.Setting triggers and limitsWhen you use a nondate in conjunction with a date field, the compiler interpretsthe nondate either as a date whose <strong>for</strong>mat is compatible with the date field or as asimple numeric value. This interpretation depends on the context in which the datefield and nondate are used, as follows:v ComparisonWhen a date field is compared with a nondate, the nondate is considered to becompatible with the date field in the number of year and nonyear characters. Inthe following example, the nondate literal 971231 is compared with a windoweddate field:01 Date-1 Pic 9(6) Date Format yyxxxx....If Date-1 Greater than 971231 ...vvThe nondate literal 971231 is treated as if it had the same DATE FORMAT as Date-1,but with a base year of 1900.Arithmetic operationsIn all supported arithmetic operations, nondate fields are treated as simplenumeric values. In the following example, the numeric value 10000 is added tothe Gregorian date in Date-2, effectively adding one year to the date:01 Date-2 Pic 9(6) Date Format yyxxxx....Add 10000 to Date-2.MOVE statementMoving a date field to a nondate is not supported. However, you can use theUNDATE intrinsic function to do this.When you move a nondate to a date field, the sending field is assumed to becompatible with the receiving field in the number of year and nonyearcharacters. For example, when you move a nondate to a windowed date field,the nondate field is assumed to contain a compatible date with a two-digit year.Triggers and limits are special values that never match valid dates because eithertheir value is nonnumeric or the nonyear part of the value cannot occur in anactual date. Triggers and limits are recognized in date fields and also in nondatesused in combination with date fields.Type of date fieldAlphanumeric windowed date or year fieldsAlphanumeric and numeric windowed datefields with at least one X in the DATE FORMATclause (that is, date fields other than just ayear)Special valueHIGH-VALUE, LOW-VALUE, and SPACEAll nines or all zerosThe difference between a trigger and a limit is not in the particular value, but inthe way you use it. You can use any of the special values as either a trigger or alimit.When used as triggers, special values can indicate a specific condition such as″date not initialized″ or ″account past due.″ When used as limits, special values areintended to act as dates earlier or later than any valid date. LOW-VALUE, SPACE andzeros are lower limits; HIGH-VALUE and nines are upper limits.648 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


You activate trigger and limit support by specifying the TRIG suboption of theDATEPROC compiler option. If the DATEPROC(TRIG) compiler option is in effect,automatic expansion of windowed date fields (be<strong>for</strong>e their use as operands incomparisons, arithmetic, and so on) is sensitive to these special values.The DATEPROC(TRIG) option results in slower-per<strong>for</strong>ming code when windoweddates are compared. The DATEPROC(NOTRIG) option is a per<strong>for</strong>mance option thatassumes valid date values in all windowed date fields.When an actual or assumed windowed date field contains a trigger, the compilerexpands the trigger as if the value were propagated to the century part of theexpanded date result, rather than inferring 19 or 20 as the century value as innormal windowing. In this way, your application can test <strong>for</strong> special values or usethem as upper or lower date limits. Specifying DATEPROC(TRIG) also enables SORTand MERGE statement support of the DFSORT special indicators, which correspondto triggers and limits.“Example: using limits”RELATED TASKS“Using sign conditions” on page 650RELATED REFERENCES“DATEPROC” on page 315Example: using limitsThis example shows how you can use an expiration date field to hold either anormal expiration date or else a high limit that allows an “everlasting”subscription.Suppose that your application checks subscriptions <strong>for</strong> expiration, but you wantsome subscriptions to last indefinitely. Consider the following code fragment:Process Dateproc(Flag,Trig). . ....01 SubscriptionRecord.03 ExpirationDate PIC 9(6) Date Format yyxxxx....77 TodaysDate Pic 9(6) Date Format yyxxxx....If TodaysDate >= ExpirationDatePer<strong>for</strong>m SubscriptionExpiredSuppose that the application encounters the following values:v Today’s date is January 4, 2009, represented in TodaysDate as 090104.v One subscription record has a normal expiration date of December 31, 1999,represented in ExpirationDate as 991231.v Another subscription record has a special expiration date coded inExpirationDate as 999999.Because both dates are windowed, the first subscription is tested as if 20090104were compared with 19991231, and so the test succeeds. However, when thecompiler detects the special value, it uses trigger expansion instead of windowing.There<strong>for</strong>e, the test proceeds as if 20090104 were compared with 99999999. This testwill always fail.Chapter 33. Processing two-digit-year dates 649


Using sign conditionsSome applications use special values such as zeros in date fields to act as a trigger,that is, to signify that some special processing is required.For example, in an Orders file, a value of zero in Order-Date might signify that therecord is a customer totals record rather than an order record. The programcompares the date to zero, as follows:01 Order-Record.05 Order-Date Pic S9(5) Comp-3 Date Format yyxxx....If Order-Date Equal Zero Then ...However, if you are compiling with the NOTRIG suboption of the DATEPROC compileroption, this comparison is not valid because the literal value Zero is a nondate, andis there<strong>for</strong>e windowed against the assumed century window to give a value of1900000.Alternatively, you can use a sign condition instead of a literal comparison asfollows. With a sign condition, Order-Date is treated as a nondate, and the centurywindow is not considered.If Order-Date Is Zero Then ...This approach applies only if the operand in the sign condition is a simpleidentifier rather than an arithmetic expression. If an expression is specified, theexpression is evaluated first, with the century window being applied whereappropriate. The sign condition is then compared with the results of theexpression.You could use the UNDATE intrinsic function instead or the TRIG suboption of theDATEPROC compiler option to achieve the same result.RELATED CONCEPTS“Treatment of nondates” on page 647RELATED TASKS“Setting triggers and limits” on page 648“Controlling date processing explicitly” on page 653RELATED REFERENCES“DATEPROC” on page 315Sorting and merging by dateIf your sort product supports the Y2PAST option and the windowed year identifiers(Y2B, Y2C, Y2D, Y2S, and Y2Z), you can per<strong>for</strong>m sort and merge operations usingwindowed date fields as sort keys. Virtually all date fields that can be specifiedwith a DATE FORMAT clause are supported, including binary year fields and year-lastdate fields.The fields are sorted in windowed year sequence according to the century windowthat you specify in the YEARWINDOW compiler option. If your sort product alsosupports the date field identifiers Y2T, Y2U, Y2W, Y2X, and Y2Y, you can use the TRIGsuboption of the DATEPROC compiler option.650 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The special indicators that DFSORT recognizes match exactly those supported by<strong>COBOL</strong>: LOW-VALUE, HIGH-VALUE, and SPACE <strong>for</strong> alphanumeric date or year fields,and all zeros and all nines <strong>for</strong> numeric and alphanumeric date fields that have atleast one nonyear digit.DFSORT is the IBM licensed program <strong>for</strong> sorting and merging. Wherever DFSORTis mentioned here, you can use any equivalent product.“Example: sorting by date and time”RELATED TASKS“Sorting on windowed date fields” on page 223DFSORT Application <strong>Programming</strong> <strong>Guide</strong> (OPTION control statement: Y2PAST)RELATED REFERENCES“DATEPROC” on page 315“YEARWINDOW” on page 360Restrictions on using date fields (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: sorting by date and timeThe following example shows a transaction file that has the transaction recordssorted by date and time within account number. Trans-Date is a windowed Juliandate field.SDTransaction-FileRecord Contains 29 CharactersData Record is Transaction-Record01 Transaction-Record.05 Trans-Account PIC 9(8).05 Trans-Type PIC X.05 Trans-Date PIC 9(5) Date Format yyxxx.05 Trans-Time PIC 9(6).05 Trans-Amount PIC 9(7)V99....Sort Transaction-FileOn Ascending KeyUsing Input-FileGiving Sorted-File.Trans-AccountTrans-DateTrans-Time<strong>COBOL</strong> passes the relevant in<strong>for</strong>mation to DFSORT <strong>for</strong> it to per<strong>for</strong>m the sort. Inaddition to the in<strong>for</strong>mation <strong>COBOL</strong> always passes to DFSORT, <strong>COBOL</strong> also passesthe following in<strong>for</strong>mation, which DFSORT also uses:v Century window as the Y2PAST sort optionv Windowed year field and date <strong>for</strong>mat of Trans-DatePer<strong>for</strong>ming arithmetic on date fieldsYou can per<strong>for</strong>m arithmetic operations on numeric date fields in the same manneras on any numeric data item. Where appropriate, the century window will be usedin the calculation.However, there are some restrictions on where date fields can be used in arithmeticexpressions and statements. Arithmetic operations that include date fields arerestricted to:v Adding a nondate to a date fieldChapter 33. Processing two-digit-year dates 651


vvSubtracting a nondate from a date fieldSubtracting a date field from a compatible date field to give a nondate resultThe following arithmetic operations are not allowed:v Any operation between incompatible date fieldsv Adding two date fieldsv Subtracting a date field from a nondatev Unary minus applied to a date fieldv Multiplication, division, or exponentiation of or by a date fieldv Arithmetic expressions that specify a year-last date fieldv Arithmetic expressions that specify a year-last date field, except as a receivingdata item when the sending field is a nondateDate semantics are provided <strong>for</strong> the year parts of date fields but not <strong>for</strong> thenonyear parts. For example, adding 1 to a windowed Gregorian date field thatcontains the value 980831 gives a result of 980832, not 980901.RELATED TASKS“Allowing <strong>for</strong> overflow from windowed date fields”“Specifying the order of evaluation” on page 653Allowing <strong>for</strong> overflow from windowed date fieldsA (nonyear-last) windowed date field that participates in an arithmetic operation isprocessed as if the value of the year component of the field were first incrementedby 1900 or 2000, depending on the century window.01 Review-Record.03 Last-Review-Year Pic 99 Date Format yy.03 Next-Review-Year Pic 99 Date Format yy....Add 10 to Last-Review-Year Giving Next-Review-Year.In the example above, if the century window is 1910-2009, and the value ofLast-Review-Year is 98, then the computation proceeds as if Last-Review-Year isfirst incremented by 1900 to give 1998. Then the ADD operation is per<strong>for</strong>med, givinga result of 2008. This result is stored in Next-Review-Year as 08.However, the following statement would give a result of 2018:Add 20 to Last-Review-Year Giving Next-Review-Year.This result falls outside the range of the century window. If the result is stored inNext-Review-Year, it will be incorrect because later references to Next-Review-Yearwill interpret it as 1918. In this case, the result of the operation depends onwhether the ON SIZE ERROR phrase is specified on the ADD statement:vvIf SIZE ERROR is specified, the receiving field is not changed, and the SIZE ERRORimperative statement is executed.If SIZE ERROR is not specified, the result is stored in the receiving field with theleft-hand digits truncated.This consideration is important when you use internal bridging. When youcontract a four-digit-year date field back to two digits to write it to the output file,you need to ensure that the date falls within the century window. Then thetwo-digit-year date will be represented correctly in the field.652 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


To ensure appropriate calculations, use a COMPUTE statement to do the contraction,with a SIZE ERROR phrase to handle the out-of-window condition. For example:Compute Output-Date-YY = Work-Date-YYYYOn Size Error Per<strong>for</strong>m CenturyWindowOverflow.SIZE ERROR processing <strong>for</strong> windowed date receivers recognizes any year value thatfalls outside the century window. That is, a year value less than the starting year ofthe century window raises the SIZE ERROR condition, as does a year value greaterthan the ending year of the century window.If the DATEPROC(TRIG) compiler option is in effect, trigger values of zeros or ninesin the result also cause the SIZE ERROR condition, even though the year part of theresult (00 or 99, respectively) falls within the century window.RELATED TASKS“Using internal bridging” on page 639Specifying the order of evaluationBecause of the restrictions on date fields in arithmetic expressions, you might findthat programs that previously compiled successfully now produce diagnosticmessages when some of the data items are changed to date fields.01 Dates-Record.03 Start-Year-1 Pic 99 Date Format yy.03 End-Year-1 Pic 99 Date Format yy.03 Start-Year-2 Pic 99 Date Format yy.03 End-Year-2 Pic 99 Date Format yy....Compute End-Year-2 = Start-Year-2 + End-Year-1 - Start-Year-1.In the example above, the first arithmetic expression evaluated is:Start-Year-2 + End-Year-1However, the addition of two date fields is not permitted. To resolve these datefields, you should use parentheses to isolate the parts of the arithmetic expressionthat are allowed. For example:Compute End-Year-2 = Start-Year-2 + (End-Year-1 - Start-Year-1).In this case, the first arithmetic expression evaluated is:End-Year-1 - Start-Year-1The subtraction of one date field from another is permitted and gives a nondateresult. This nondate result is then added to the date field End-Year-1, giving a datefield result that is stored in End-Year-2.Controlling date processing explicitlyThere might be times when you want <strong>COBOL</strong> data items to be treated as datefields only under certain conditions or only in specific parts of the program. Oryour application might contain two-digit-year date fields that cannot be declaredas windowed date fields because of some interaction with another softwareproduct.Chapter 33. Processing two-digit-year dates 653


For example, if a date field is used in a context where it is recognized only by itstrue binary contents without further interpretation, the date in that field cannot bewindowed. Such date fields include:v A key in a VSAM filev A search field in a database system such as DB2v A key field in a CICS commandConversely, there might be times when you want a date field to be treated as anondate in specific parts of the program.<strong>COBOL</strong> provides two intrinsic functions to deal with these conditions:DATEVALConverts a nondate to a date fieldUNDATE Converts a date field to a nondateRELATED TASKS“Using DATEVAL”“Using UNDATE”Using DATEVALYou can use the DATEVAL intrinsic function to convert a nondate to a date field, sothat <strong>COBOL</strong> will apply the relevant date processing to the field.The first argument in the function is the nondate to be converted, and the secondargument specifies the date <strong>for</strong>mat. The second argument is a literal string with aspecification similar to that of the date pattern in the DATE FORMAT clause.In most cases, the compiler makes the correct assumption about the interpretationof a nondate but accompanies this assumption with a warning-level diagnosticmessage. This message typically happens when a windowed date is comparedwith a literal:03 When-Made Pic x(6) Date Format yyxxxx....If When-Made = "850701" Per<strong>for</strong>m Warranty-Check.The literal is assumed to be a compatible windowed date but with a centurywindow of 1900-1999, thus representing July 15, 1985. You can use the DATEVALintrinsic function to make the year of the literal date explicit and eliminate thewarning message:If When-Made = Function Dateval("19850701" "YYYYXXXX")Per<strong>for</strong>m Warranty-Check.“Example: DATEVAL” on page 655Using UNDATEYou can use the UNDATE intrinsic function to convert a date field to a nondate sothat it can be referenced without any date processing.Attention: Avoid using UNDATE except as a last resort, because the compiler willlose the flow of date fields in your program. This problem could result in datecomparisons not being windowed properly.654 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Use more DATE FORMAT clauses instead of function UNDATE <strong>for</strong> MOVE and COMPUTE.“Example: UNDATE”Example: DATEVALThis example shows a case where it is better to leave a field as a nondate, and usethe DATEVAL intrinsic function in a comparison statement.Assume that a field Date-Copied is referenced many times in a program, but thatmost of the references just move the value between records or re<strong>for</strong>mat it <strong>for</strong>printing. Only one reference relies on it to contain a date (<strong>for</strong> comparison withanother date). In this case, it is better to leave the field as a nondate, and use theDATEVAL intrinsic function in the comparison statement. For example:03 Date-Distributed Pic 9(6) Date Format yyxxxx.03 Date-Copied Pic 9(6)....If Function DATEVAL(Date-Copied "YYXXXX") Less than Date-Distributed ...In this example, DATEVAL converts Date-Copied to a date field so that thecomparison will be meaningful.RELATED REFERENCESDATEVAL (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: UNDATEThe following example shows a case where you might want to convert a date fieldto a nondate.The field Invoice-Date is a windowed Julian date. In some records, it contains thevalue 00999 to indicate that the record is not a true invoice record, but insteadcontains file-control in<strong>for</strong>mation.Invoice-Date has a DATE FORMAT clause because most of its references in theprogram are date-specific. However, when it is checked <strong>for</strong> the existence of acontrol record, the value 00 in the year component will lead to some confusion. Ayear value of 00 in Invoice-Date could represent either 1900 or 2000, depending onthe century window. This is compared with a nondate (the literal 00999 in theexample), which will always be windowed against the assumed century windowand there<strong>for</strong>e always represents the year 1900.To ensure a consistent comparison, you should use the UNDATE intrinsic function toconvert Invoice-Date to a nondate. There<strong>for</strong>e, if the IF statement is not comparingdate fields, it does not need to apply windowing. For example:01 Invoice-Record.03 Invoice-Date Pic x(5) Date Format yyxxx....If FUNCTION UNDATE(Invoice-Date) Equal "00999" ...RELATED REFERENCESUNDATE (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 33. Processing two-digit-year dates 655


Analyzing and avoiding date-related diagnostic messagesWhen the DATEPROC(FLAG) compiler option is in effect, the compiler producesdiagnostic messages <strong>for</strong> every statement that defines or references a date field.As with all compiler-generated messages, each date-related message has one of thefollowing severity levels:v In<strong>for</strong>mation-level, to draw your attention to the definition or use of a date field.vvvWarning-level, to indicate that the compiler has had to make an assumptionabout a date field or nondate because of inadequate in<strong>for</strong>mation coded in theprogram, or to indicate the location of date logic that should be manuallychecked <strong>for</strong> correctness. Compilation proceeds, with any assumptions continuingto be applied.Error-level, to indicate that the usage of the date field is incorrect. Compilationcontinues, but runtime results are unpredictable.Severe-level, to indicate that the usage of the date field is incorrect. Thestatement that caused this error is discarded from the compilation.The easiest way to use the MLE messages is to compile with a FLAG option settingthat embeds the messages in the source listing after the line to which the messagesrefer. You can choose to see all MLE messages or just certain severities.To see all MLE messages, specify the FLAG(I,I) and DATEPROC(FLAG) compileroptions. Initially, you might want to see all of the messages to understand howMLE is processing the date fields in your program. For example, if you want to doa static analysis of the date usage in a program by using the compile listing, useFLAG (I,I).However, it is recommended that you specify FLAG(W,W) <strong>for</strong> MLE-specific compiles.You must resolve all severe-level (S-level) error messages, and you should resolveall error-level (E-level) messages as well. For the warning-level (W-level) messages,you need to examine each message and use the following guidelines to eithereliminate the message or, <strong>for</strong> unavoidable messages, ensure that the compilermakes correct assumptions:vvvThe diagnostic messages might indicate some date data items that should havehad a DATE FORMAT clause. Either add DATE FORMAT clauses to these items or usethe DATEVAL intrinsic function in references to them.Pay particular attention to literals in relation conditions that involve date fieldsor in arithmetic expressions that include date fields. You can use the DATEVALfunction on literals (as well as nondate data items) to specify a DATE FORMATpattern to be used. As a last resort, you can use the UNDATE function to enable adate field to be used in a context where you do not want date-oriented behavior.With the REDEFINES and RENAMES clauses, the compiler might produce awarning-level diagnostic message if a date field and a nondate occupy the samestorage location. You should check these cases carefully to confirm that all usesof the aliased data items are correct, and that none of the perceived nondateredefinitions actually is a date or can adversely affect the date logic in theprogram.In some cases, a the W-level message might be acceptable, but you might want tochange the code to get a compile with a return code of zero.To avoid warning-level diagnostic messages, follow these guidelines:656 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvvvvvAdd DATE FORMAT clauses to any data items that will contain dates, even if theitems are not used in comparisons. But see the related references below aboutrestrictions on using date fields. For example, you cannot use the DATE FORMATclause on a data item that is described implicitly or explicitly as USAGE NATIONAL.Do not specify a date field in a context where a date field does not make sense,such as a FILE STATUS, PASSWORD, ASSIGN USING, LABEL RECORD, orLINAGE item. Ifyou do, you will get a warning-level message and the date field will be treatedas a nondate.Ensure that implicit or explicit aliases <strong>for</strong> date fields are compatible, such as in agroup item that consists solely of a date field.Ensure that if a date field is defined with a VALUE clause, the value is compatiblewith the date field definition.Use the DATEVAL intrinsic function if you want a nondate treated as a date field,such as when moving a nondate to a date field or when comparing a windoweddate with a nondate and you want a windowed date comparison. If you do notuse DATEVAL, the compiler will make an assumption about the use of the nondateand produce a warning-level diagnostic message. Even if the assumption iscorrect, you might want to use DATEVAL to eliminate the message.Use the UNDATE intrinsic function if you want a date field treated as a nondate,such as moving a date field to a nondate, or comparing a nondate and awindowed date field when you do not want a windowed comparison.RELATED TASKS“Controlling date processing explicitly” on page 653<strong>COBOL</strong> Millennium Language Extensions <strong>Guide</strong> (Analyzing date-relateddiagnostic messages)RELATED REFERENCESRestrictions on using date fields (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Avoiding problems in processing datesWhen you change a <strong>COBOL</strong> program to use the millennium language extensions,you might find that some parts of the program need special attention to resolveun<strong>for</strong>eseen changes in behavior. For example, you might need to avoid problemswith packed-decimal fields and problems that occur if you move from expanded towindowed date fields.RELATED TASKS“Avoiding problems with packed-decimal fields”“Moving from expanded to windowed date fields” on page 658Avoiding problems with packed-decimal fieldsCOMPUTATIONAL-3 fields (packed-decimal <strong>for</strong>mat) are often defined as having an oddnumber of digits even if the field will not be used to hold a number of thatmagnitude. The internal representation of packed-decimal numbers always allows<strong>for</strong> an odd number of digits.A field that holds a six-digit Gregorian date, <strong>for</strong> example, can be declared as PICS9(6) COMP-3. This declaration will reserve 4 bytes of storage. But a programmermight have declared the field as PIC S9(7), knowing that this would reserve 4bytes with the high-order digit always containing a zero.Chapter 33. Processing two-digit-year dates 657


If you add a DATE FORMAT YYXXXX clause to this field, the compiler will issue adiagnostic message because the number of digits in the PICTURE clause does notmatch the size of the date <strong>for</strong>mat specification. In this case, you need to carefullycheck each use of the field. If the high-order digit is never used, you can simplychange the field definition to PIC S9(6). If it is used (<strong>for</strong> example, if the same fieldcan hold a value other than a date), you need to take some other action, such as:vvvUsing a REDEFINES clause to define the field as both a date and a nondate (thisusage will also produce a warning-level diagnostic message)Defining another WORKING-STORAGE field to hold the date, and moving thenumeric field to the new fieldNot adding a DATE FORMAT clause to the data item, and using the DATEVALintrinsic function when referring to it as a date fieldMoving from expanded to windowed date fieldsWhen you move an expanded alphanumeric date field to a windowed date field,the move does not follow the normal <strong>COBOL</strong> conventions <strong>for</strong> alphanumericmoves. When both the sending and receiving fields are date fields, the move isright justified, not left justified as normal. For an expanded-to-windowed(contracting) move, the leading two digits of the year are truncated.Depending on the contents of the sending field, the results of such a move mightbe incorrect. For example:77 Year-Of-Birth-Exp Pic x(4) Date Format yyyy.77 Year-Of-Birth-Win Pic xx Date Format yy....Move Year-Of-Birth-Exp to Year-Of-Birth-Win.If Year-Of-Birth-Exp contains ’1925’, Year-Of-Birth-Win will contain ’25’.However, if the century window is 1930-2029, subsequent references toYear-Of-Birth-Win will treat it as 2025, which is incorrect.658 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 8. Improving per<strong>for</strong>mance and productivityChapter 34. Tuning your program . . . . . . 661Using an optimal programming style . . . . . 662Using structured programming . . . . . . 662Factoring expressions. . . . . . . . . . 662Using symbolic constants . . . . . . . . 663Grouping constant computations . . . . . . 663Grouping duplicate computations . . . . . 663Choosing efficient data types . . . . . . . . 664Choosing efficient computational data items . . 664Using consistent data types. . . . . . . . 665Making arithmetic expressions efficient . . . . 665Making exponentiations efficient . . . . . . 665Handling tables efficiently . . . . . . . . . 665Optimization of table references . . . . . . 667Optimization of constant and variable items 667Optimization of duplicate items . . . . . 668Optimization of variable-length items . . . 668Comparison of direct and relative indexing 668Optimizing your code . . . . . . . . . . 669Optimization . . . . . . . . . . . . 669Contained program procedure integration 670PERFORM procedure integration . . . . . 670Example: PERFORM procedure integration 670Choosing compiler features to enhanceper<strong>for</strong>mance. . . . . . . . . . . . . . 671Per<strong>for</strong>mance-related compiler options . . . . 672Evaluating per<strong>for</strong>mance . . . . . . . . . 675Running efficiently with CICS, IMS, or VSAM . . 676Chapter 35. Simplifying coding. . . . . . . 679Eliminating repetitive coding . . . . . . . . 679Example: using the COPY statement. . . . . 680Using Language Environment callable services . . 681Sample list of Language Environment callableservices . . . . . . . . . . . . . . 682Calling Language Environment services . . . 683Example: Language Environment callableservices . . . . . . . . . . . . . . 684© Copyright IBM Corp. 1991, 2009 659


660 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 34. Tuning your programWhen a program is comprehensible, you can assess its per<strong>for</strong>mance. A programthat has a tangled control flow is difficult to understand and maintain. The tangledcontrol flow also inhibits the optimization of the code.There<strong>for</strong>e, be<strong>for</strong>e you try to improve the per<strong>for</strong>mance directly, you need to assesscertain aspects of your program:1. Examine the underlying algorithms <strong>for</strong> your program. For top per<strong>for</strong>mance, asound algorithm is essential. For example, a sophisticated algorithm <strong>for</strong> sortinga million items can be hundreds of thousands times faster than a simplealgorithm.2. Look at the data structures. They should be appropriate <strong>for</strong> the algorithm.When your program frequently accesses data, reduce the number of stepsneeded to access the data wherever possible.3. After you have improved the algorithm and data structures, look at otherdetails of the <strong>COBOL</strong> source code that affect per<strong>for</strong>mance.You can write programs that result in better generated code sequences and usesystem services better. These areas affect program per<strong>for</strong>mance:vvvvvCoding techniques. These include using a programming style that helps theoptimizer, choosing efficient data types, and handling tables efficiently.Optimization. You can optimize your code by using the OPTIMIZE compileroption.Compiler options and USE FOR DEBUGGING ON ALL PROCEDURES. Certain compileroptions and language affect the efficiency of your program.Runtime environment. Carefully consider your choice of runtime options andother runtime considerations that control how your compiled program runs.Running under CICS, IMS, or using VSAM. Various tips can help make theseprograms run efficiently.RELATED CONCEPTS“Optimization” on page 669<strong>Enterprise</strong> <strong>COBOL</strong> Version 3 Per<strong>for</strong>mance TuningRELATED TASKS“Using an optimal programming style” on page 662“Choosing efficient data types” on page 664“Handling tables efficiently” on page 665“Optimizing your code” on page 669“Choosing compiler features to enhance per<strong>for</strong>mance” on page 671“Running efficiently with CICS, IMS, or VSAM” on page 676Language Environment <strong>Programming</strong> <strong>Guide</strong> (Specifying run-time options)RELATED REFERENCES“Per<strong>for</strong>mance-related compiler options” on page 672Language Environment <strong>Programming</strong> <strong>Guide</strong> (Storage per<strong>for</strong>mance considerations)© Copyright IBM Corp. 1991, 2009 661


Using an optimal programming styleThe coding style you use can affect how the optimizer handles your code. You canimprove optimization by using structured programming techniques, factoringexpressions, using symbolic constants, and grouping constant and duplicatecomputations.RELATED TASKS“Using structured programming”“Factoring expressions”“Using symbolic constants” on page 663“Grouping constant computations” on page 663“Grouping duplicate computations” on page 663Using structured programmingUsing structured programming statements, such as EVALUATE and inline PERFORM,makes your program more comprehensible and generates a more linear controlflow. As a result, the optimizer can operate over larger regions of the program,which gives you more efficient code.Use top-down programming constructs. Out-of-line PERFORM statements are anatural means of doing top-down programming. Out-of-line PERFORM statementscan often be as efficient as inline PERFORM statements, because the optimizer cansimplify or remove the linkage code.Avoid using the following constructs:v ALTER statementv Backward branches (except as needed <strong>for</strong> loops <strong>for</strong> which PERFORM is unsuitable)v PERFORM procedures that involve irregular control flow (such as preventingcontrol from passing to the end of the procedure and returning to the PERFORMstatement)Factoring expressionsBy factoring expressions in your programs, you can potentially eliminate a lot ofunnecessary computation.For example, the first block of code below is more efficient than the second blockof code:MOVE ZERO TO TOTALPERFORM VARYING I FROM 1 BY 1 UNTIL I=10COMPUTE TOTAL = TOTAL + ITEM(I)END-PERFORMCOMPUTE TOTAL = TOTAL * DISCOUNTMOVE ZERO TO TOTALPERFORM VARYING I FROM 1 BY 1 UNTIL I=10COMPUTE TOTAL = TOTAL + ITEM(I) * DISCOUNTEND-PERFORMThe optimizer does not factor expressions.662 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Using symbolic constantsTo have the optimizer recognize a data item as a constant throughout the program,initialize it with a VALUE clause and do not change it anywhere in the program.If you pass a data item to a subprogram BY REFERENCE, the optimizer treats it as anexternal data item and assumes that it is changed at every subprogram call.If you move a literal to a data item, the optimizer recognizes the data item as aconstant only in a limited area of the program after the MOVE statement.Grouping constant computationsWhen several items in an expression are constant, ensure that the optimizer is ableto optimize them. The compiler is bound by the left-to-right evaluation rules of<strong>COBOL</strong>. There<strong>for</strong>e, either move all the constants to the left side of the expressionor group them inside parentheses.For example, if V1, V2, and V3 are variables and C1, C2, and C3 are constants, theexpressions on the left below are preferable to the corresponding expressions onthe right:More efficientV1*V2*V3*(C1*C2*C3)C1+C2+C3+V1+V2+V3Less efficientV1*V2*V3*C1*C2*C3V1+C1+V2+C2+V3+C3In production programming, there is often a tendency to place constant factors onthe right-hand side of expressions. However, such placement can result in lessefficient code because optimization is lost.Grouping duplicate computationsWhen components of different expressions are duplicates, ensure that the compileris able to optimize them. For arithmetic expressions, the compiler is bound by theleft-to-right evaluation rules of <strong>COBOL</strong>. There<strong>for</strong>e, either move all the duplicates tothe left side of the expressions or group them inside parentheses.If V1 through V5 are variables, the computation V2*V3*V4is a duplicate (knownas a common subexpression) in the following two statements:COMPUTE A=V1*(V2*V3*V4)COMPUTE B=V2*V3*V4*V5In the following example, V2+V3is a common subexpression:COMPUTE C=V1+(V2+V3)COMPUTE D=V2+V3+V4In the following example, there is no common subexpression:COMPUTE A=V1*V2*V3*V4COMPUTE B=V2*V3*V4*V5COMPUTE C=V1+(V2+V3)COMPUTE D=V4+V2+V3The optimizer can eliminate duplicate computations. You do not need to introduceartificial temporary computations; a program is often more comprehensible withoutthem.Chapter 34. Tuning your program 663


Choosing efficient data typesChoosing the appropriate data type and PICTURE clause can produce more efficientcode, as can avoiding USAGE DISPLAY and USAGE NATIONAL data items in areas thatare heavily used <strong>for</strong> computations.Consistent data types can reduce the need <strong>for</strong> conversions during operations ondata items. You can also improve program per<strong>for</strong>mance by carefully determiningwhen to use fixed-point and floating-point data types.RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49RELATED TASKS“Choosing efficient computational data items”“Using consistent data types” on page 665“Making arithmetic expressions efficient” on page 665“Making exponentiations efficient” on page 665Choosing efficient computational data itemsWhen you use a data item mainly <strong>for</strong> arithmetic or as a subscript, code USAGEBINARY on the data description entry <strong>for</strong> the item. The operations <strong>for</strong> manipulatingbinary data are faster than those <strong>for</strong> manipulating decimal data.However, if a fixed-point arithmetic statement has intermediate results with a largeprecision (number of significant digits), the compiler uses decimal arithmeticanyway, after converting the operands to packed-decimal <strong>for</strong>m. For fixed-pointarithmetic statements, the compiler normally uses binary arithmetic <strong>for</strong> simplecomputations with binary operands if the precision is eight or fewer digits. Above18 digits, the compiler always uses decimal arithmetic. With a precision of nine to18 digits, the compiler uses either <strong>for</strong>m.To produce the most efficient code <strong>for</strong> a BINARY data item, ensure that it has:v A sign (an S in its PICTURE clause)v Eight or fewer digitsFor a data item that is larger than eight digits or is used with DISPLAY or NATIONALdata items, use PACKED-DECIMAL. The code generated <strong>for</strong> PACKED-DECIMAL data itemscan be as fast as that <strong>for</strong> BINARY data items in some cases, especially if thestatement is complicated or specifies rounding.To produce the most efficient code <strong>for</strong> a PACKED-DECIMAL data item, ensure that ithas:v A sign (an S in its PICTURE clause)vvAn odd number of digits (9s inthePICTURE clause), so that it occupies an exactnumber of bytes without a half byte left over15 or fewer digits in the PICTURE specification to avoid using library routines <strong>for</strong>multiplication and division664 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Using consistent data typesIn operations on operands of different types, one of the operands must beconverted to the same type as the other. Each conversion requires severalinstructions. For example, one of the operands might need to be scaled to give itthe appropriate number of decimal places.You can largely avoid conversions by using consistent data types and by givingboth operands the same usage and also appropriate PICTURE specifications. That is,you should ensure that two numbers to be compared, added, or subtracted notonly have the same usage but also the same number of decimal places (9s after theV in the PICTURE clause).Making arithmetic expressions efficientComputation of arithmetic expressions that are evaluated in floating point is mostefficient when the operands need little or no conversion. Use operands that areCOMP-1 or COMP-2 to produce the most efficient code.Declare integer items as BINARY or PACKED-DECIMAL with nine or fewer digits toaf<strong>for</strong>d quick conversion to floating-point data. Also, conversion from a COMP-1 orCOMP-2 item to a fixed-point integer with nine or fewer digits, without SIZE ERRORin effect, is efficient when the value of the COMP-1 or COMP-2 item is less than1,000,000,000.Making exponentiations efficientHandling tables efficientlyUse floating point <strong>for</strong> exponentiations <strong>for</strong> large exponents to achieve fasterevaluation and more accurate results.For example, the first statement below is computed more quickly and accuratelythan the second statement:COMPUTE fixed-point1 = fixed-point2 ** 100000.E+00COMPUTE fixed-point1 = fixed-point2 ** 100000A floating-point exponent causes floating-point arithmetic to be used to computethe exponentiation.You can use several techniques to improve the efficiency of table-handlingoperations, and to influence the optimizer. The return <strong>for</strong> your ef<strong>for</strong>ts can besignificant, particularly when table-handling operations are a major part of anapplication.The following two guidelines affect your choice of how to refer to table elements:v Use indexing rather than subscripting.Although the compiler can eliminate duplicate indexes and subscripts, theoriginal reference to a table element is more efficient with indexes (even if thesubscripts were BINARY). The value of an index has the element size factored intoit, whereas the value of a subscript must be multiplied by the element size whenthe subscript is used. The index already contains the displacement from the startChapter 34. Tuning your program 665


vof the table, and this value does not have to be calculated at run time. However,subscripting might be easier to understand and maintain.Use relative indexing.Relative index references (that is, references in which an unsigned numericliteral is added to or subtracted from the index-name) are executed at least asfast as direct index references, and sometimes faster. There is no merit inkeeping alternative indexes with the offset factored in.Whether you use indexes or subscripts, the following coding guidelines can helpyou get better per<strong>for</strong>mance:v Put constant and duplicate indexes or subscripts on the left.You can reduce or eliminate runtime computations this way. Even when all theindexes or subscripts are variable, try to use your tables so that the rightmostsubscript varies most often <strong>for</strong> references that occur close to each other in theprogram. This practice also improves the pattern of storage references and alsopaging. If all the indexes or subscripts are duplicates, then the entire index orsubscript computation is a common subexpression.v Specify the element length so that it matches that of related tables.When you index or subscript tables, it is most efficient if all the tables have thesame element length. That way, the stride <strong>for</strong> the last dimension of the tables isthe same, and the optimizer can reuse the rightmost index or subscriptcomputed <strong>for</strong> one table. If both the element lengths and the number ofoccurrences in each dimension are equal, then the strides <strong>for</strong> dimensions otherthan the last are also equal, resulting in greater commonality between theirsubscript computations. The optimizer can then reuse indexes or subscripts otherthan the rightmost.vAvoid errors in references by coding index and subscript checks into yourprogram.If you need to validate indexes and subscripts, it might be faster to code yourown checks than to use the SSRANGE compiler option.You can also improve the efficiency of tables by using these guidelines:v Use binary data items <strong>for</strong> all subscripts.When you use subscripts to address a table, use a BINARY signed data item witheight or fewer digits. In some cases, using four or fewer digits <strong>for</strong> the data itemmight also improve processing time.v Use binary data items <strong>for</strong> variable-length table items.For tables with variable-length items, you can improve the code <strong>for</strong> OCCURSDEPENDING ON (ODO). To avoid unnecessary conversions each time thevariable-length items are referenced, specify BINARY <strong>for</strong> OCCURS . . . DEPENDINGON objects.v Use fixed-length data items whenever possible.Copying variable-length data items into a fixed-length data item be<strong>for</strong>e a periodof high-frequency use can reduce some of the overhead associated with usingvariable-length data items.v Organize tables according to the type of search method used.If the table is searched sequentially, put the data values most likely to satisfy thesearch criteria at the beginning of the table. If the table is searched using abinary search algorithm, put the data values in the table sorted alphabetically onthe search key field.666 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED CONCEPTS“Optimization of table references”RELATED TASKS“Referring to an item in a table” on page 72“Choosing efficient data types” on page 664RELATED REFERENCES“SSRANGE” on page 347Optimization of table referencesThe <strong>COBOL</strong> compiler optimizes table references in several ways.For the table element reference ELEMENT(S1 S2 S3), where S1, S2, and S3 aresubscripts, the compiler evaluates the following expression:comp_s1 * d1 + comp_s2 * d2 + comp_s3 * d3 + base_addressHere comp_s1 is the value of S1 after conversion to binary, comp-s2 is the value ofS2 after conversion to binary, and so on. The strides <strong>for</strong> each dimension are d1, d2,and d3. The stride of a given dimension is the distance in bytes between tableelements whose occurrence numbers in that dimension differ by 1 and whose otheroccurrence numbers are equal. For example, the stride d2 of the second dimensionin the above example is the distance in bytes between ELEMENT(S1 1 S3) andELEMENT(S1 2 S3).Index computations are similar to subscript computations, except that nomultiplication needs to be done. Index values have the stride factored into them.They involve loading the indexes into registers, and these data transfers can beoptimized, much as the individual subscript computation terms are optimized.Because the compiler evaluates expressions from left to right, the optimizer findsthe most opportunities to eliminate computations when the constant or duplicatesubscripts are the leftmost.Optimization of constant and variable itemsAssume that C1, C2, ...areconstant data items and that V1, V2, ...arevariabledata items. Then, <strong>for</strong> the table element reference ELEMENT(V1 C1 C2) the compilercan eliminate only the individual terms comp_c1 * d2 and comp_c2 * d3 asconstant from the expression:comp_v1 * d1 + comp_c1 * d2 + comp_c2 * d3 + base_addressHowever, <strong>for</strong> the table element reference ELEMENT(C1 C2 V1) the compiler caneliminate the entire subexpression comp_c1 * d1 + comp_c2 * d2 as constant fromthe expression:comp_c1 * d1 + comp_c2 * d2 + comp_v1 * d3 + base_addressIn the table element reference ELEMENT(C1 C2 C3), all the subscripts are constant,and so no subscript computation is done at run time. The expression is:comp_c1 * d1 + comp_c2 * d2 + comp_c3 * d3 + base_addressWith the optimizer, this reference can be as efficient as a reference to a scalar(nontable) item.Chapter 34. Tuning your program 667


Optimization of duplicate itemsIn the table element references ELEMENT(V1 V3 V4) and ELEMENT(V2 V3 V4) only theindividual terms comp_v3 * d2 and comp_v4 * d3 are common subexpressions inthe expressions needed to reference the table elements:comp_v1 * d1 + comp_v3 * d2 + comp_v4 * d3 + base_addresscomp_v2 * d1 + comp_v3 * d2 + comp_v4 * d3 + base_addressHowever, <strong>for</strong> the two table element references ELEMENT(V1 V2 V3) and ELEMENT(V1V2 V4) the entire subexpression comp_v1 * d1 + comp_v2 * d2 is common betweenthe two expressions needed to reference the table elements:comp_v1 * d1 + comp_v2 * d2 + comp_v3 * d3 + base_addresscomp_v1 * d1 + comp_v2 * d2 + comp_v4 * d3 + base_addressIn the two references ELEMENT(V1 V2 V3) and ELEMENT(V1 V2 V3), the expressionsare the same:comp_v1 * d1 + comp_v2 * d2 + comp_v3 * d3 + base_addresscomp_v1 * d1 + comp_v2 * d2 + comp_v3 * d3 + base_addressWith the optimizer, the second (and any subsequent) reference to the same elementcan be as efficient as a reference to a scalar (nontable) item.Optimization of variable-length itemsA group item that contains a subordinate OCCURS DEPENDING ON data item has avariable length. The program must per<strong>for</strong>m special code every time avariable-length data item is referenced.Because this code is out-of-line, it might interrupt optimization. Furthermore, thecode to manipulate variable-length data items is much less efficient than that <strong>for</strong>fixed-size data items and can significantly increase processing time. For instance,the code to compare or move a variable-length data item might involve calling alibrary routine and is much slower than the same code <strong>for</strong> fixed-length data items.Comparison of direct and relative indexingRelative index references are as fast as or faster than direct index references.The direct indexing in ELEMENT (I5, J3, K2) requires this preprocessing:SET I5 TO ISET I5 UP BY 5SET J3 TO JSET J3 DOWN BY 3SET K2 TO KSET K2 UP BY 2This processing makes the direct indexing less efficient than the relative indexingin ELEMENT (I + 5, J-3,K+2).RELATED CONCEPTS“Optimization” on page 669RELATED TASKS“Handling tables efficiently” on page 665668 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Optimizing your codeWhen your program is ready <strong>for</strong> final testing, specify the OPTIMIZE compiler optionso that the tested code and the production code are identical.You might also want to use this compiler option during development if a programis used frequently without recompilation. However, the overhead <strong>for</strong> OPTIMIZEmight outweigh its benefits if you recompile frequently, unless you are using theassembler language expansion (LIST compiler option) to fine-tune the program.For unit-testing a program, you will probably find it easier to debug code that hasnot been optimized.To see how the optimizer works on a program, compile it with and without theOPTIMIZE option and compare the generated code. (Use the LIST compiler option torequest the assembler listing of the generated code.)RELATED CONCEPTS“Optimization”RELATED REFERENCES“LIST” on page 328“OPTIMIZE” on page 336OptimizationTo improve the efficiency of the generated code, you can use the OPTIMIZE compileroption.OPTIMIZE causes the <strong>COBOL</strong> optimizer to do the following optimizations:v Eliminate unnecessary transfers of control and inefficient branches, includingthose generated by the compiler that are not evident from looking at the sourceprogram.v Simplify the compiled code <strong>for</strong> both a PERFORM statement and a CALL statement toa contained (nested) program. Where possible, the optimizer places thestatements inline, eliminating the need <strong>for</strong> linkage code. This optimization isknown as procedure integration. If procedure integration cannot be done, theoptimizer uses the simplest linkage possible (perhaps as few as two instructions)to get to and from the called program.v Eliminate duplicate computations (such as subscript computations and repeatedstatements) that have no effect on the results of the program.v Eliminate constant computations by per<strong>for</strong>ming them when the program iscompiled.v Eliminate constant conditional expressions.v Aggregate moves of contiguous items (such as those that often occur with theuse of MOVE CORRESPONDING) into a single move. Both the source and target mustbe contiguous <strong>for</strong> the moves to be aggregated.v Delete from the program, and identify with a warning message, code that cannever be per<strong>for</strong>med (unreachable code elimination).v Discard unreferenced data items from the DATA DIVISION, and suppressgeneration of code to initialize these data items to their VALUE clauses. (Theoptimizer takes this action only when you use the FULL suboption.)Chapter 34. Tuning your program 669


Contained program procedure integrationIn contained program procedure integration, the contained program code replacesa CALL to a contained program. The resulting program runs faster without theoverhead of CALL linkage and with more linear control flow.Program size: If several CALL statements call contained programs and theseprograms replace each such statement, the containing program can become large.The optimizer limits this increase to no more than 50 percent, after which it nolonger integrates the programs. The optimizer then chooses the next bestoptimization <strong>for</strong> the CALL statement. The linkage overhead can be as few as twoinstructions.Unreachable code: As a result of this integration, one contained program might berepeated several times. As further optimization proceeds on each copy of theprogram, portions might be found to be unreachable, depending on the contextinto which the code was copied.RELATED CONCEPTS“Optimization of table references” on page 667“PERFORM procedure integration”RELATED REFERENCES“OPTIMIZE” on page 336PERFORM procedure integrationPERFORM procedure integration is the process whereby a PERFORM statement isreplaced by its per<strong>for</strong>med procedures. The advantage is that the resulting programruns faster without the overhead of PERFORM linkage and with more linear controlflow.Program size: If the per<strong>for</strong>med procedures are invoked by several PERFORMstatements and replace each such statement, the program could become large. Theoptimizer limits this increase to no more than 50 percent, after which it no longerintegrates these procedures. If you are concerned about program size, you canprevent procedure integration in specific instances by using a priority number onsection names.If you do not want a PERFORM statement to be replaced by its per<strong>for</strong>medprocedures, put the PERFORM statement in one section and put the per<strong>for</strong>medprocedures in another section with a different priority number. The optimizer thenchooses the next best optimization <strong>for</strong> the PERFORM statement. The linkage overheadcan be as few as two instructions.Unreachable code: Because of procedure integration, one PERFORM procedure mightbe repeated several times. As further optimization proceeds on each copy of theprocedure, portions might be found to be unreachable, depending on the contextinto which the code was copied.“Example: PERFORM procedure integration”Example: PERFORM procedure integrationThe following example shows code that will be trans<strong>for</strong>med by procedureintegration.All the PERFORM statements in the following program will be trans<strong>for</strong>med:670 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


1 SECTION 5.11. PERFORM 12STOP RUN.12. PERFORM 21PERFORM 21.2 SECTION 5.21.IFA


Important: Confer with your system programmer about how to tune <strong>COBOL</strong>programs. Doing so will ensure that the options you choose are appropriate <strong>for</strong>programs at your site.Another compiler feature to consider is the USE FOR DEBUGGING ON ALL PROCEDURESstatement. It can greatly affect the compiler optimizer. The ON ALL PROCEDURESoption generates extra code at each transfer to a procedure name. Although veryuseful <strong>for</strong> debugging, it can make the program significantly larger and inhibitoptimization substantially.Although <strong>COBOL</strong> allows segmentation language, you will not improve storageallocation by using it, because <strong>COBOL</strong> does not per<strong>for</strong>m overlay.RELATED CONCEPTS“Optimization” on page 669RELATED TASKS“Optimizing your code” on page 669“Getting listings” on page 377RELATED REFERENCES“Per<strong>for</strong>mance-related compiler options”Per<strong>for</strong>mance-related compiler optionsIn the table below you can see a description of the purpose of each option, itsper<strong>for</strong>mance advantages and disadvantages, and usage notes where applicable.Table 93. Per<strong>for</strong>mance-related compiler optionsCompileroptionPurposePer<strong>for</strong>manceadvantagesPer<strong>for</strong>mancedisadvantagesUsage notesARITH(EXTEND)(see “ARITH”on page 306)To increase themaximum numberof digits allowed<strong>for</strong> decimalnumbersIn general, noneARITH(EXTEND)causes somedegradation inper<strong>for</strong>mance <strong>for</strong> alldecimal data typesdue to largerintermediateresults.The amount of degradation thatyou experience depends directlyon the amount of decimal datathat you use.||“AWO” onpage 307To get optimumuse of buffer anddevice space <strong>for</strong>QSAM filesCan result inper<strong>for</strong>mance savings,because this optionresults in fewer callsto data managementservices to handleinput and outputIn general, noneIf you use AWO, the APPLYWRITE-ONLY clause is in effect <strong>for</strong>all QSAM files in the programthat have V-mode records.|||||||“BLOCK0” onpage 307To take advantageofsystem-determinedblock size <strong>for</strong>QSAM output filesCan result inenhanced processingspeed and minimizedstorage requirements<strong>for</strong> QSAM outputfilesIn general, noneIf you use BLOCK0, aBLOCKCONTAINS 0 clause is activated<strong>for</strong> all QSAM files in theprogram that specify neitherBLOCK CONTAINS nor RECORDINGMODE U in the file descriptionentry.672 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 93. Per<strong>for</strong>mance-related compiler options (continued)CompileroptionDATA(31)(see “DATA”on page 314)“DYNAM” onpage 320“FASTSRT” onpage 322NUMPROC(PFD)(see“NUMPROC”on page 333)OPTIMIZE(STD)(see“OPTIMIZE”on page 336)OPTIMIZE(FULL)(see“OPTIMIZE”on page 336)PurposeTo have DFSMSallocate QSAMbuffers above the16-MB line (byusing the RENT andDATA(31) compileroptions)To havesubprograms(called through theCALL statement)dynamically loadedat run timeTo specify that theIBM DFSORTproduct (orequivalent) willhandle all of theinput and outputTo have invalidsign processingbypassed <strong>for</strong>numeric operationsTo optimizegenerated code <strong>for</strong>better per<strong>for</strong>manceTo optimizegenerated code <strong>for</strong>better per<strong>for</strong>manceand also optimizethe DATA DIVISIONPer<strong>for</strong>manceadvantagesBecauseextended-<strong>for</strong>matQSAM data sets canrequire many buffers,allocating the buffersin unrestrictedstorage avoids virtualstorage constraintproblems.Subprograms areeasier to maintain,because theapplication does nothave to be link-editedagain if a subprogramis changed.Eliminates theoverhead of returningto <strong>Enterprise</strong> <strong>COBOL</strong>after each record isprocessedGeneratessignificantly moreefficient code <strong>for</strong>numeric comparisonsGenerally results inmore efficientruntime codeGenerally results inmore efficientruntime code and lessstorage usagePer<strong>for</strong>mancedisadvantagesIn general, noneThere is a slightper<strong>for</strong>mancepenalty, because thecall must gothrough aLanguageEnvironmentroutine.NoneFor most referencesto COMP-3 andDISPLAY numericdata items,NUMPROC(PFD)inhibits extra codefrom beinggenerated to ″fixup″ signs. Thisextra code mightalso inhibit someother types ofoptimizations. Theextra code isgenerated withNUMPROC(MIG) andNUMPROC(NOPFD).Longer compiletime: OPTIMIZErequires moreprocessing time <strong>for</strong>compiles thanNOOPTIMIZE.Longer compiletime: OPTIMIZErequires moreprocessing time <strong>for</strong>compiles thanNOOPTIMIZE.Usage notesOn a z/<strong>OS</strong> system with DFSMS,if your application processesstriped extended-<strong>for</strong>mat QSAMdata sets, use the RENT andDATA(31) compiler options tohave the input-output buffers <strong>for</strong>your QSAM files allocated fromstorage above the 16-MB line.To free virtual storage that is nolonger needed, issue the CANCELstatement.FASTSRT is recommended ifdirect work files are used <strong>for</strong> thesort work files. Not all sorts areeligible <strong>for</strong> this option.If you use NUMPROC(PFD), thecompiler assumes that the datahas the correct sign andbypasses the sign ″fix-up″process. Because not all externaldata files contain the proper sign<strong>for</strong> COMP-3 or DISPLAY signednumeric data, NUMPROC(PFD)might not be applicable <strong>for</strong> allprograms. Forper<strong>for</strong>mance-sensitiveapplications, NUMPROC(PFD) isrecommended.NOOPTIMIZE is generally usedduring program developmentwhen frequent compiles areneeded; it also allows <strong>for</strong>symbolic debugging. Forproduction runs, OPTIMIZE isrecommended.OPT(FULL) deletes unused dataitems, which might beundesirable in the case of timestamps or data items that areused only as markers <strong>for</strong> dumpreading.Chapter 34. Tuning your program 673


Table 93. Per<strong>for</strong>mance-related compiler options (continued)Compileroption“RENT” onpage 341RMODE(ANY)(see “RMODE”on page 342)N<strong>OS</strong>SRANGE(see“SSRANGE”on page 347)TEST(NOHOOK)or NOTEST(see “TEST” onpage 349)“THREAD” onpage 352PurposeTo generate areentrant programTo let the programbe loadedanywhereTo verify that alltable references andreferencemodificationexpressions are inproper boundsTo avoid theadditional objectcode that is neededto take fulladvantage ofDebug Tool, useTEST(NOHOOK) orNOTEST. WithTEST(NOHOOK), youcan also use the SEPsuboption tofurther reduce thesize of your objectcode.To enable programs<strong>for</strong> execution in aLanguageEnvironmentenclave that hasmultiple P<strong>OS</strong>IXthreads or PL/ItasksPer<strong>for</strong>manceadvantagesEnables the programto be placed in sharedstorage (LPA/ELPA)<strong>for</strong> faster executionRMODE(ANY) withNORENT lets theprogram and itsWORKING-STORAGE belocated above the16-MB line, relievingstorage below theline.SSRANGE generatesadditional code <strong>for</strong>verifying tablereferences. UsingN<strong>OS</strong>SRANGE causes thatcode not to begenerated.Because TEST(HOOK)generates additionalcode, it can causesignificantper<strong>for</strong>mancedegradation whenused in a productionenvironment.NonePer<strong>for</strong>mancedisadvantagesGeneratesadditional code toensure that theprogram isreentrantIn general, noneNoneNoneThere is a slightper<strong>for</strong>mancepenalty because ofthe overhead ofserialization logic.Usage notesIn general, if you need to verifythe table references only a fewtimes instead of at everyreference, coding your ownchecks might be faster thanusing SSRANGE. You can turn offSSRANGE at run time by using theCHECK(OFF) runtime option. Forper<strong>for</strong>mance-sensitiveapplications, N<strong>OS</strong>SRANGE isrecommended.TEST without the suboptionNOHOOK <strong>for</strong>ces compiler optionNOOPT into effect. For productionruns, using NOTEST orTEST(NOHOOK) with or withoutthe SEP suboption isrecommended. This results inoverlay hooks rather thancompiled-in hooks.If during a production run, youwant a symbolic dump of thedata items in a <strong>for</strong>matted dumpif the program abends, compileusing TEST(NOHOOK) with orwithout the SEP suboption.This is true <strong>for</strong> a threaded or anonthreaded environment.674 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 93. Per<strong>for</strong>mance-related compiler options (continued)CompileroptionTRUNC(OPT)(see “TRUNC”on page 353)PurposeTo avoid havingcode generated totruncate thereceiving fields ofarithmeticoperationsPer<strong>for</strong>manceadvantagesDoes not generateextra code andgenerally improvesper<strong>for</strong>mancePer<strong>for</strong>mancedisadvantagesBoth TRUNC(BIN)and TRUNC(STD)generate extra codewhenever a BINARYdata item ischanged.TRUNC(BIN) isusually the slowestof these options,though itsper<strong>for</strong>mance wasimproved in<strong>COBOL</strong> <strong>for</strong> <strong>OS</strong>/390& VM V2R2.Usage notesTRUNC(STD) con<strong>for</strong>ms toStandard <strong>COBOL</strong> 85, butTRUNC(BIN) and TRUNC(OPT) donot. With TRUNC(OPT), thecompiler assumes that the datacon<strong>for</strong>ms to the PICTURE andUSAGE specifications. TRUNC(OPT)is recommended where possible.RELATED CONCEPTS“Optimization” on page 669“Storage and its addressability” on page 42RELATED TASKS“Generating a list of compiler messages” on page 279“Evaluating per<strong>for</strong>mance”“Optimizing buffer and device space” on page 12“Choosing compiler features to enhance per<strong>for</strong>mance” on page 671“Improving sort per<strong>for</strong>mance with FASTSRT” on page 225“Using striped extended-<strong>for</strong>mat QSAM data sets” on page 172“Handling tables efficiently” on page 665RELATED REFERENCES“Sign representation of zoned and packed-decimal data” on page 55“Allocation of buffers <strong>for</strong> QSAM files” on page 173Chapter 17, “Compiler options,” on page 301“Conflicting compiler options” on page 304Evaluating per<strong>for</strong>manceFill in the following worksheet to help you evaluate the per<strong>for</strong>mance of yourprogram. If you answer yes to each question, you are probably improving theper<strong>for</strong>mance.In thinking about the per<strong>for</strong>mance tradeoff, be sure you understand the function ofeach option as well as the per<strong>for</strong>mance advantages and disadvantages. You mightprefer function over increased per<strong>for</strong>mance in many instances.Table 94. Per<strong>for</strong>mance-tuning worksheetCompiler option Consideration Yes?AWODo you use the AWO option when possible?DATAWhen you use QSAM striped data sets, do you use theRENT and DATA(31) options? Is the load module AMODE 31?Are you running with ALL31(ON)?Chapter 34. Tuning your program 675


Table 94. Per<strong>for</strong>mance-tuning worksheet (continued)Compiler option Consideration Yes?DYNAMCan you use NODYNAM? Consider the per<strong>for</strong>mancetradeoffs.FASTSRTWhen you use direct work files <strong>for</strong> the sort work files,did you use the FASTSRT option?NUMPROCDo you use NUMPROC(PFD) when possible?OPTIMIZEDo you use OPTIMIZE <strong>for</strong> production runs? Can you useOPTIMIZE(FULL)?RENTConsider the per<strong>for</strong>mance tradeoffs of RENT versusNORENT.RMODE(ANY)Do you use RMODE(ANY) with your NORENT programs?Consider the per<strong>for</strong>mance tradeoffs with storage usage.SSRANGEDo you use N<strong>OS</strong>SRANGE <strong>for</strong> production runs?TESTDo you use NOTEST, TEST(NOHOOK), orTEST(NOHOOK,SEP)<strong>for</strong> production runs?TRUNCDo you use TRUNC(OPT) when possible?RELATED CONCEPTS“Storage and its addressability” on page 42RELATED TASKS“Choosing compiler features to enhance per<strong>for</strong>mance” on page 671RELATED REFERENCES“Per<strong>for</strong>mance-related compiler options” on page 672Running efficiently with CICS, IMS, or VSAMYou can improve per<strong>for</strong>mance <strong>for</strong> online programs running under CICS or IMS, orprograms that use VSAM, by following these tips.CICS: If your application runs under CICS, convert EXEC CICS LINK commands to<strong>COBOL</strong> CALL statements to improve transaction response time.IMS: If your application runs under IMS, preloading the application program andthe library routines can help reduce the overhead of loading and searching. It canalso reduce the input-output activity.For better system per<strong>for</strong>mance, use the RENT compiler option and preload theapplications and library routines when possible. You can also use the LanguageEnvironment library routine retention (LRR) function to improve per<strong>for</strong>mance inIMS/TM regions.VSAM: When you use VSAM files, increase the number of data buffers <strong>for</strong>sequential access or index buffers <strong>for</strong> random access. Also, select a control intervalsize (CISZ) that is appropriate <strong>for</strong> the application. A smaller CISZ results in fasterretrieval <strong>for</strong> random processing at the expense of inserts. A larger CISZ is moreefficient <strong>for</strong> sequential processing.676 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


For better per<strong>for</strong>mance, access the records sequentially and avoid using multiplealternate indexes when possible. If you use alternate indexes, access methodservices builds them more efficiently than the AIXBLD runtime option.RELATED TASKS“Coding <strong>COBOL</strong> programs to run under CICS” on page 407Chapter 22, “Developing <strong>COBOL</strong> programs <strong>for</strong> IMS,” on page 431“Improving VSAM per<strong>for</strong>mance” on page 203Language Environment CustomizationRELATED REFERENCESLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (Specifying run-time options)Chapter 34. Tuning your program 677


678 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Chapter 35. Simplifying codingYou can use coding techniques to improve your productivity. By using the COPYstatement, <strong>COBOL</strong> intrinsic functions, and Language Environment callable services,you can avoid repetitive coding and having to code many arithmetic calculationsor other complex tasks.If your program contains frequently used code sequences (such as blocks ofcommon data items, input-output routines, error routines, or even entire <strong>COBOL</strong>programs), write the code sequences once and put them in a <strong>COBOL</strong> copy library.You can use the COPY statement to retrieve these code sequences and have themincluded in your program at compile time. Using copybooks in this mannereliminates repetitive coding.<strong>COBOL</strong> provides various capabilities <strong>for</strong> manipulating strings and numbers. Thesecapabilities can help you simplify your coding.The Language Environment date and time callable services store dates as fullwordbinary integers and store timestamps as long (64-bit) floating-point values. These<strong>for</strong>mats let you do arithmetic calculations on date and time values simply andefficiently. You do not need to write special subroutines that use services outsidethe language library to per<strong>for</strong>m such calculations.Eliminating repetitive codingRELATED TASKS“Using numeric intrinsic functions” on page 59“Using math-oriented callable services” on page 60“Using date callable services” on page 62“Eliminating repetitive coding”“Converting data items (intrinsic functions)” on page 112“Evaluating data items (intrinsic functions)” on page 115“Using Language Environment callable services” on page 681Use the COPY statement in any program division and at any code sequence level toinclude stored source statements in a program. You can nest COPY statements to anydepth.To specify more than one copy library, use either multiple system definitions or acombination of multiple definitions and the IN/OF phrase (IN/OF library-name):z/<strong>OS</strong> batchUse JCL to concatenate data sets in your SYSLIB DD statement.Alternatively, define multiple DD statements and use the IN/OF phrase ofthe COPY statement.TSOUNIXUse the ALLOCATE command to concatenate data sets <strong>for</strong> SYSLIB.Alternatively, issue multiple ALLOCATE statements and use the IN/OF phraseof the COPY statement.Use the SYSLIB environment variable to define multiple paths to yourcopybooks. Alternatively, use multiple environment variables and use theIN/OF phrase of the COPY statement.© Copyright IBM Corp. 1991, 2009 679


For example:COPY MEMBER1 OF COPYLIBIf you omit this qualifying phrase, the default is SYSLIB.COPY and debugging line: In order <strong>for</strong> the text copied to be treated as debug lines,<strong>for</strong> example, as if there were a D inserted in column 7, put the D on the first line ofthe COPY statement. A COPY statement itself cannot be a debugging line; if itcontains a D and WITH DEBUGGING mode is not specified, the COPY statement isnevertheless processed.“Example: using the COPY statement”RELATED REFERENCESChapter 18, “Compiler-directing statements,” on page 363Example: using the COPY statementThese examples show how you can use the COPY statement to include library textin a program.Suppose the library entry CFILEA consists of the following FD entries:BLOCK CONTAINS 20 RECORDSRECORD CONTAINS 120 CHARACTERSLABEL RECORDS ARE STANDARDDATA RECORD IS FILE-OUT.01 FILE-OUT PIC X(120).You can retrieve the text-name CFILEA by using the COPY statement in a sourceprogram as follows:FD FILEACOPY CFILEA.The library entry is copied into your program, and the resulting program listinglooks like this:FD FILEACOPY CFILEA.C BLOCK CONTAINS 20 RECORDSC RECORD CONTAINS 120 CHARACTERSC LABEL RECORDS ARE STANDARDC DATA RECORD IS FILE-OUT.C 01 FILE-OUT PIC X(120).In the compiler source listing, the COPY statement prints on a separate line. Cprecedes copied lines.Assume that a copybook with the text-name DOWORK is stored by using thefollowing statements:COMPUTE QTY-ON-HAND = TOTAL-USED-NUMBER-ON-HANDMOVE QTY-ON-HAND to PRINT-AREATo retrieve the copybook identified as DOWORK, code:paragraph-name.COPY DOWORK.The statements that are in the DOWORK procedure will follow paragraph-name.680 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


If you use the EXIT compiler option to provide a LIBEXIT module, your resultsmight differ from those shown here.RELATED TASKS“Eliminating repetitive coding” on page 679RELATED REFERENCESChapter 18, “Compiler-directing statements,” on page 363Using Language Environment callable servicesLanguage Environment callable services make many types of programming taskseasier. You call them by using the CALL statement.Language Environment services help you with the following tasks:v Handling conditionsThe Language Environment condition-handling facilities enable <strong>COBOL</strong>applications to react to unexpected errors. You can use language constructs orruntime options to select the level at which to handle each condition. Forexample, you can handle a particular error in your <strong>COBOL</strong> program, letLanguage Environment take care of it, or have the operating system handle it.In support of Language Environment condition handling, <strong>COBOL</strong> providesprocedure-pointer data items.v Managing dynamic storageThese services enable you to get, free, and reallocate storage. You can also createyour own storage pools.v Calculating dates and timesIf you use the date and time services, you can get the current local time anddate in several <strong>for</strong>mats, and per<strong>for</strong>m date and time conversions. Two callableservices, CEEQCEN and CEESCEN, provide a predictable way to handletwo-digit years, such as 91 <strong>for</strong> 1991 or 09 <strong>for</strong> 2009.v Making math calculationsCalculations that are easy to per<strong>for</strong>m with mathematical callable services includelogarithmic, exponential, trigonometric, square root, and integer functions.<strong>COBOL</strong> also supports a set of intrinsic functions that include some of the samemathematical and date functions as those provided by the callable services. TheLanguage Environment callable services and intrinsic functions provideequivalent results, with a few exceptions. You should be familiar with thesedifferences be<strong>for</strong>e deciding which to use.v Handling messagesMessage-handling services include services <strong>for</strong> getting, dispatching, and<strong>for</strong>matting messages. Messages <strong>for</strong> non-CICS applications can be directed to filesor printers. CICS messages are directed to a CICS transient data queue.Language Environment splits messages to accommodate the record length of thedestination, and presents messages in the correct national language such asJapanese or English.v Supporting national languagesThese services make it easy <strong>for</strong> your applications to support the language thatapplication users want. You can set the language and country, and obtain defaultdate, time, number, and currency <strong>for</strong>mats. For example, you might want dates toappear as 23 June 09 or as 6,23,09.Chapter 35. Simplifying coding 681


vGeneral services such as starting Debug Tool and obtaining a LanguageEnvironment <strong>for</strong>matted dumpDebug Tool provides advanced debugging functions <strong>for</strong> <strong>COBOL</strong> applications,including both batch and interactive debugging of CICS programs. Debug Toolenables you to debug a <strong>COBOL</strong> application from the host or, in conjunction withthe Debug Perspective of Rational Developer <strong>for</strong> System z, from aWindows-based workstation.Depending on the options that you select, the Language Environment <strong>for</strong>matteddump might contain the names and values of data items, and in<strong>for</strong>mation aboutconditions, program tracebacks, control blocks, storage, and files. All LanguageEnvironment dumps have a common, well-labeled, easy-to-read <strong>for</strong>mat.“Example: Language Environment callable services” on page 684RELATED CONCEPTS“Sample list of Language Environment callable services”RELATED TASKS“Using numeric intrinsic functions” on page 59“Using math-oriented callable services” on page 60“Using date callable services” on page 62“Calling Language Environment services” on page 683“Using procedure and function pointers” on page 462Sample list of Language Environment callable servicesThe following table shows some examples of the callable services that are availablewith Language Environment. Many more services are available than those listed.Table 95. Language Environment callable servicesFunction type Service PurposeCondition CEEHDLR To register a user condition handlerhandlingCEESGL To raise or signal a conditionCEEMRCR To indicate where the program will resume running afterthe condition handler has finishedDynamic storage CEEGTST To get storageCEECZST To change the size of a previously allocated storage blockCEEFRST To free storageDate and time CEECBLDY To convert a string that represents a date into <strong>COBOL</strong>integer date <strong>for</strong>mat, which represents a date as thenumber of days since 31 December 1600CEEQCEN,CEESCENCEEGMTOCEELOCTTo query and set the Language Environment centurywindow, which is valuable when a program uses twodigits to express a yearTo calculate the difference between the local system timeand Greenwich Mean TimeTo get the current local time in your choice of three<strong>for</strong>matsMath CEESIABS To calculate the absolute value of an integerCEESSNWN To calculate the nearest whole number <strong>for</strong> asingle-precision floating-point numberCEESSC<strong>OS</strong> To calculate the cosine of an angle682 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 95. Language Environment callable services (continued)Function type Service PurposeMessage CEEMOUT To dispatch a messagehandlingCEEMGET To retrieve a messageNational CEE3LNG To change or query the current national languagelanguage supportCEE3CTY To change or query the current national countryCEE3MCS To obtain the default currency symbol <strong>for</strong> a givencountryGeneral CEE3DMP To obtain a Language Environment <strong>for</strong>matted dumpCEETEST To start a debugging tool, such as Debug ToolRELATED REFERENCESLanguage Environment <strong>Programming</strong> ReferenceCalling Language Environment servicesTo invoke a Language Environment service, use a CALL statement with the correctparameters <strong>for</strong> that service. Define the variables <strong>for</strong> the CALL statement in the DATADIVISION with the definitions that are required by that service.77 argument comp-1.77 feedback-code pic x(12) display.77 result comp-1....CALL "CEESSSQT" using argument, feedback-code, resultIn the example above, Language Environment service CEESSSQT calculates thevalue of the square root of the variable argument and returns this value in thevariable result.You can choose whether to specify the feedback code parameter. If you specify it,the value returned in feedback-code indicates whether the service completedsuccessfully. If you specify OMITTED instead of the feedback code, and the service isnot successful, a Language Environment condition is automatically signaled to theLanguage Environment condition manager. You can handle such a condition byrecovery logic implemented in a user-written condition handler, or allow thedefault Language Environment processing <strong>for</strong> unhandled conditions to occur. Ineither case, you avoid having to write logic to check the feedback code explicitlyafter each call.If you call a Language Environment callable service and specify OMITTED <strong>for</strong> thefeedback code, the RETURN-CODE special register is set to 0 if the service issuccessful.It is not altered if the service is unsuccessful. If you do not specifyOMITTED <strong>for</strong> the feedback code, the RETURN-CODE special register is always set to 0regardless of whether the service completed successfully.“Example: Language Environment callable services” on page 684RELATED CONCEPTSLanguage Environment <strong>Programming</strong> <strong>Guide</strong> (General callable services)RELATED REFERENCESLanguage Environment <strong>Programming</strong> Reference (General callable services)CALL statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Chapter 35. Simplifying coding 683


Example: Language Environment callable servicesThis example shows a <strong>COBOL</strong> program that uses the Language Environmentservices CEEDAYS and CEEDATE to <strong>for</strong>mat and display a date from the results ofa <strong>COBOL</strong> ACCEPT statement.Using CEEDAYS and CEEDATE reduces the coding that would be requiredwithout Language Environment.ID DIVISION.PROGRAM-ID. HOHOHO.************************************************************* FUNCTION: DISPLAY TODAY'S DATE IN THE FOLLOWING FORMAT: ** WWWWWWWWW, MMMMMMMM DD, YYYY ** ** For example: TUESDAY, SEPTEMBER 15, 2009 ** *************************************************************ENVIRONMENT DIVISION.DATA DIVISION.WORKING-STORAGE SECTION.01 CHRDATE.05 CHRDATE-LENGTH PIC S9(4) COMP VALUE 10.05 CHRDATE-STRING PIC X(10).01 PICSTR.05 PICSTR-LENGTH PIC S9(4) COMP.05 PICSTR-STRING PIC X(80).*77 LILIAN PIC S9(9) COMP.77 FORMATTED-DATE PIC X(80).*PROCEDURE DIVISION.**************************************************************** USE LANGUAGE ENVIRONMENT CALLABLE SERVICES TO PRINT OUT ** TODAY'S DATE FROM <strong>COBOL</strong> ACCEPT STATEMENT. ****************************************************************ACCEPT CHRDATE-STRING FROM DATE.*MOVE "YYMMDD" TO PICSTR-STRING.MOVE 6 TO PICSTR-LENGTH.CALL "CEEDAYS" USING CHRDATE , PICSTR , LILIAN , OMITTED.*MOVE " WWWWWWWWWZ, MMMMMMMMMZ DD, YYYY " TO PICSTR-STRING.MOVE 50 TO PICSTR-LENGTH.CALL "CEEDATE" USING LILIAN , PICSTR , FORMATTED-DATE ,OMITTED.*DISPLAY "******************************".DISPLAY FORMATTED-DATE.DISPLAY "******************************".*STOP RUN.684 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Part 9. Appendixes© Copyright IBM Corp. 1991, 2009 685


686 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix A. Intermediate results and arithmetic precisionThe compiler handles arithmetic statements as a succession of operationsper<strong>for</strong>med according to operator precedence, and sets up intermediate fields tocontain the results of those operations. The compiler uses algorithms to determinethe number of integer and decimal places to reserve.Intermediate results are possible in the following cases:v In an ADD or SUBTRACT statement that contains more than one operandimmediately after the verbv In a COMPUTE statement that specifies a series of arithmetic operations or multipleresult fieldsv In an arithmetic expression contained in a conditional statement or in areference-modification specificationv In an ADD, SUBTRACT, MULTIPLY, orDIVIDE statement that uses the GIVING optionand multiple result fieldsv In a statement that uses an intrinsic function as an operand“Example: calculation of intermediate results” on page 689The precision of intermediate results depends on whether you compile using thedefault option ARITH(COMPAT) (referred to as compatibility mode) or usingARITH(EXTEND) (referred to as extended mode).In compatibility mode, evaluation of arithmetic operations is unchanged from thatin releases of IBM <strong>COBOL</strong> be<strong>for</strong>e <strong>COBOL</strong> <strong>for</strong> <strong>OS</strong>/390 & VM Version 2 Release 2:v A maximum of 30 digits is used <strong>for</strong> fixed-point intermediate results.vvvFloating-point intrinsic functions return long-precision (64-bit) floating-pointresults.Expressions that contain floating-point operands, fractional exponents, orfloating-point intrinsic functions are evaluated as if all operands that are not infloating point are converted to long-precision floating point and floating-pointoperations are used to evaluate the expression.Floating-point literals and external floating-point data items are converted tolong-precision floating point <strong>for</strong> processing.In extended mode, evaluation of arithmetic operations has the followingcharacteristics:v A maximum of 31 digits is used <strong>for</strong> fixed-point intermediate results.vvvFloating-point intrinsic functions return extended-precision (128-bit)floating-point results.Expressions that contain floating-point operands, fractional exponents, orfloating-point intrinsic functions are evaluated as if all operands that are not infloating point are converted to extended-precision floating point andfloating-point operations are used to evaluate the expression.Floating-point literals and external floating-point data items are converted toextended-precision floating point <strong>for</strong> processing.© Copyright IBM Corp. 1991, 2009 687


RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49“Fixed-point contrasted with floating-point arithmetic” on page 64RELATED REFERENCES“Fixed-point data and intermediate results” on page 689“Floating-point data and intermediate results” on page 694“Arithmetic expressions in nonarithmetic statements” on page 695“ARITH” on page 306Terminology used <strong>for</strong> intermediate resultsTo understand this in<strong>for</strong>mation about intermediate results, you need to understandthe following terminology.idThe number of integer places carried <strong>for</strong> an intermediate result. (If you usethe ROUNDED phrase, one more integer place might be carried <strong>for</strong> accuracy ifnecessary.)The number of decimal places carried <strong>for</strong> an intermediate result. (If youuse the ROUNDED phrase, one more decimal place might be carried <strong>for</strong>accuracy if necessary.)dmax In a particular statement, the largest of the following items:v The number of decimal places needed <strong>for</strong> the final result field or fieldsv The maximum number of decimal places defined <strong>for</strong> any operand,except divisors or exponentsv The outer-dmax <strong>for</strong> any function operandinner-dmaxIn reference to a function, the largest of the following items:v The number of decimal places defined <strong>for</strong> any of its elementaryargumentsv The dmax <strong>for</strong> any of its arithmetic expression argumentsv The outer-dmax <strong>for</strong> any of its embedded functionsouter-dmaxThe number of decimal places that a function result contributes tooperations outside of its own evaluation (<strong>for</strong> example, if the function is anoperand in an arithmetic expression, or an argument to another function).op1 The first operand in a generated arithmetic statement (in division, thedivisor).op2 The second operand in a generated arithmetic statement (in division, thedividend).i1, i2 The number of integer places in op1 and op2, respectively.d1, d2 The number of decimal places in op1 and op2, respectively.ir The intermediate result when a generated arithmetic statement oroperation is per<strong>for</strong>med. (Intermediate results are generated either inregisters or storage locations.)ir1, ir2 Successive intermediate results. (Successive intermediate results might havethe same storage location.)688 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED REFERENCESROUNDED phrase (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: calculation of intermediate resultsThe following example shows how the compiler per<strong>for</strong>ms an arithmetic statementas a succession of operations, storing intermediate results as needed.COMPUTE Y=A+B*C-D/E+F**GThe result is calculated in the following order:1. Exponentiate F by G yielding ir1.2. Multiply B by C yielding ir2.3. Divide E into D yielding ir3.4. Add A to ir2 yielding ir4.5. Subtract ir3 from ir4 yielding ir5.6. Add ir5 to ir1 yielding Y.RELATED TASKS“Using arithmetic expressions” on page 58RELATED REFERENCES“Terminology used <strong>for</strong> intermediate results” on page 688Fixed-point data and intermediate resultsThe compiler determines the number of integer and decimal places in anintermediate result.Addition, subtraction, multiplication, and divisionThe following table shows the precision theoretically possible as the result ofaddition, subtraction, multiplication, or division.Operation Integer places Decimal places+or- (i1 or i2) + 1, whichever is greater d1 or d2, whichever is greater* i1 + i2 d1 + d2/ i2 + d1 (d2 - d1) ordmax, whichever isgreaterYou must define the operands of any arithmetic statements with enough decimalplaces to obtain the accuracy you want in the final result.The following table shows the number of places the compiler carries <strong>for</strong>fixed-point intermediate results of arithmetic operations that involve addition,subtraction, multiplication, or division in compatibility mode (that is, when thedefault compiler option ARITH(COMPAT) is in effect):Value of i +Value of i + d Value of d dmaxNumber of places carried <strong>for</strong> ir


Value of i + d Value of dValue of i +dmaxNumber of places carried <strong>for</strong> ir>30 dmax 30 30-dmax integer and dmax decimalplacesThe following table shows the number of places the compiler carries <strong>for</strong>fixed-point intermediate results of arithmetic operations that involve addition,subtraction, multiplication, or division in extended mode (that is, when the compileroption ARITH(EXTEND) is in effect):Value of i + d Value of dValue of i +dmaxNumber of places carried <strong>for</strong> ir31 dmax 31 31-dmax integer and dmax decimalplacesExponentiationExponentiation is represented by the expression op1 ** op2. Based on thecharacteristics of op2, the compiler handles exponentiation of fixed-point numbersin one of three ways:v When op2 is expressed with decimals, floating-point instructions are used.v When op2 is an integral literal or constant, the value d is computed asd = d1 *|op2|and the value i is computed based on the characteristics of op1:– When op1 is a data-name or variable,i = i1 *|op2|– When op1 is a literal or constant, i is set equal to the number of integers inthe value of op1 ** |op2|.In compatibility mode (compilation using ARITH(COMPAT)), the compiler havingcalculated i and d takes the action indicated in the table below to handle theintermediate results ir of the exponentiation.Value of i + d Other conditions Action taken30 Any Same action as when op2 is an integral data-name orvariable (shown below)690 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


In extended mode (compilation using ARITH(EXTEND)), the compiler havingcalculated i and d takes the action indicated in the table below to handle theintermediate results ir of the exponentiation.Value of i + d Other conditions Action taken31 Any Same action as when op2 is an integral data-name orvariable (shown below). Exception: <strong>for</strong> a 31-digitinteger raised to the power of literal 1, i integer andd decimal places are carried <strong>for</strong> ir.vIf op2 is negative, the value of 1 is then divided by the result produced by thepreliminary computation. The values of i and d that are used are calculatedfollowing the division rules <strong>for</strong> fixed-point data already shown above.When op2 is an integral data-name or variable, dmax decimal places and 30-dmax(compatibility mode) or 31-dmax (extended mode) integer places are used. op1 ismultiplied by itself (|op2| - 1) times <strong>for</strong> nonzero op2.If op2 is equal to 0, the result is 1. Division-by-0 and exponentiation SIZE ERRORconditions apply.Fixed-point exponents with more than nine significant digits are always truncatedto nine digits. If the exponent is a literal or constant, an E-level compiler diagnosticmessage is issued; otherwise, an in<strong>for</strong>mational message is issued at run time.“Example: exponentiation in fixed-point arithmetic”RELATED REFERENCES“Terminology used <strong>for</strong> intermediate results” on page 688“Truncated intermediate results” on page 692“Binary data and intermediate results” on page 692“Floating-point data and intermediate results” on page 694“Intrinsic functions evaluated in fixed-point arithmetic” on page 692“ARITH” on page 306SIZE ERROR phrases (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Example: exponentiation in fixed-point arithmeticThe following example shows how the compiler per<strong>for</strong>ms an exponentiation to anonzero integer power as a succession of multiplications, storing intermediateresults as needed.COMPUTE Y=A**BIf B is equal to 4, the result is computed as shown below. The values of i and d thatare used are calculated according to the multiplication rules <strong>for</strong> fixed-point dataand intermediate results (referred to below).1. Multiply A by A yielding ir1.2. Multiply ir1 by A yielding ir2.3. Multiply ir2 by A yielding ir3.4. Move ir3 to ir4.ir4 has dmax decimal places. Because B is positive, ir4 is moved to Y. IfB wereequal to -4, however, an additional fifth step would be per<strong>for</strong>med:5. Divide ir4 into 1 yielding ir5.Appendix A. Intermediate results and arithmetic precision 691


ir5 has dmax decimal places, and would then be moved to Y.RELATED REFERENCES“Terminology used <strong>for</strong> intermediate results” on page 688“Fixed-point data and intermediate results” on page 689Truncated intermediate resultsWhenever the number of digits in an intermediate result exceeds 30 incompatibility mode or 31 in extended mode, the compiler truncates to 30(compatibility mode) or 31 (extended mode) digits and issues a warning. Iftruncation occurs at run time, a message is issued and the program continuesrunning.If you want to avoid the truncation of intermediate results that can occur infixed-point calculations, use floating-point operands (COMP-1 or COMP-2) instead.RELATED CONCEPTS“Formats <strong>for</strong> numeric data” on page 49RELATED REFERENCES“Fixed-point data and intermediate results” on page 689“ARITH” on page 306Binary data and intermediate resultsIf an operation that involves binary operands requires intermediate results longerthan 18 digits, the compiler converts the operands to internal decimal be<strong>for</strong>eper<strong>for</strong>ming the operation. If the result field is binary, the compiler converts theresult from internal decimal to binary.Binary operands are most efficient when intermediate results will not exceed ninedigits.RELATED REFERENCES“Fixed-point data and intermediate results” on page 689“ARITH” on page 306Intrinsic functions evaluated in fixed-point arithmeticThe compiler determines the inner-dmax and outer-dmax values <strong>for</strong> an intrinsicfunction from the characteristics of the function.Integer functionsInteger intrinsic functions return an integer; thus their outer-dmax is always zero.For those integer functions whose arguments must all be integers, the inner-dmax isthus also always zero.The following table summarizes the inner-dmax and the precision of the functionresult.Function Inner-dmax Digit precision of function resultDATE-OF-INTEGER 0 8692 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Function Inner-dmax Digit precision of function resultDATE-TO-YYYYMMDD 0 8DAY-OF-INTEGER 0 7DAY-TO-YYYYDDD 0 7FACTORIAL 0 30 in compatibility mode, 31 in extended modeINTEGER-OF-DATE 0 7INTEGER-OF-DAY 0 7LENGTH n/a 9MOD 0 min(i1 i2)ORD n/a 3ORD-MAX 9ORD-MIN 9YEAR-TO-YYYY 0 4INTEGERINTEGER-PARTFor a fixed-point argument: one more digit than inthe argument. For a floating-point argument: 30 incompatibility mode, 31 in extended mode.For a fixed-point argument: same number of digitsas in the argument. For a floating-point argument: 30in compatibility mode, 31 in extended mode.Mixed functionsA mixed intrinsic function is a function whose result type depends on the type ofits arguments. A mixed function is fixed point if all of its arguments are numericand none of its arguments is floating point. (If any argument of a mixed function isfloating point, the function is evaluated with floating-point instructions and returnsa floating-point result.) When a mixed function is evaluated with fixed-pointarithmetic, the result is integer if all of the arguments are integer; otherwise, theresult is fixed point.For the mixed functions MAX, MIN, RANGE, REM, and SUM, the outer-dmax is alwaysequal to the inner-dmax (and both are thus zero if all the arguments are integer). Todetermine the precision of the result returned <strong>for</strong> these functions, apply the rules<strong>for</strong> fixed-point arithmetic and intermediate results (as referred to below) to eachstep in the algorithm.MAXMIN1. Assign the first argument to the function result.2. For each remaining argument, do the following steps:a. Compare the algebraic value of the function result with theargument.b. Assign the greater of the two to the function result.1. Assign the first argument to the function result.2. For each remaining argument, do the following steps:a. Compare the algebraic value of the function result with theargument.b. Assign the lesser of the two to the function result.Appendix A. Intermediate results and arithmetic precision 693


RANGEREMSUM1. Use the steps <strong>for</strong> MAX to select the maximum argument.2. Use the steps <strong>for</strong> MIN to select the minimum argument.3. Subtract the minimum argument from the maximum.4. Assign the difference to the function result.1. Divide argument one by argument two.2. Remove all noninteger digits from the result of step 1.3. Multiply the result of step 2 by argument two.4. Subtract the result of step 3 from argument one.5. Assign the difference to the function result.1. Assign the value 0 to the function result.2. For each argument, do the following steps:a. Add the argument to the function result.b. Assign the sum to the function result.RELATED REFERENCES“Terminology used <strong>for</strong> intermediate results” on page 688“Fixed-point data and intermediate results” on page 689“Floating-point data and intermediate results”“ARITH” on page 306Floating-point data and intermediate resultsIf any operation in an arithmetic expression is computed in floating-pointarithmetic, the entire expression is computed as if all operands were converted tofloating point and the operations were per<strong>for</strong>med using floating-point instructions.Floating-point instructions are used to compute an arithmetic expression if any ofthe following conditions is true of the expression:vvvvA receiver or operand is COMP-1, COMP-2, external floating point, or afloating-point literal.An exponent contains decimal places.An exponent is an expression that contains an exponentiation or divisionoperator, and dmax is greater than zero.An intrinsic function is a floating-point function.In compatibility mode, if an expression is computed in floating-point arithmetic,the precision used to evaluate the arithmetic operations is determined as follows:vvSingle precision is used if all receivers and operands are COMP-1 data items andthe expression contains no multiplication or exponentiation operations.In all other cases, long precision is used.Whenever long-precision floating point is used <strong>for</strong> one operation in an arithmeticexpression, all operations in the expression are computed as if long floating-pointinstructions were used.In extended mode, if an expression is computed in floating-point arithmetic, theprecision used to evaluate the arithmetic operations is determined as follows:694 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


vvvSingle precision is used if all receivers and operands are COMP-1 data items andthe expression contains no multiplication or exponentiation operations.Long precision is used if all receivers and operands are COMP-1 or COMP-2 dataitems, at least one receiver or operand is a COMP-2 data item, and the expressioncontains no multiplication or exponentiation operations.In all other cases, extended precision is used.Whenever extended-precision floating point is used <strong>for</strong> one operation in anarithmetic expression, all operations in the expression are computed as ifextended-precision floating-point instructions were used.Alert: If a floating-point operation has an intermediate result field in whichexponent overflow occurs, the job is abnormally terminated.Exponentiations evaluated in floating-point arithmeticIn compatibility mode, floating-point exponentiations are always evaluated usinglong floating-point arithmetic. In extended mode, floating-point exponentiationsare always evaluated using extended-precision floating-point arithmetic.The value of a negative number raised to a fractional power is undefined in<strong>COBOL</strong>. For example, (-2) ** 3 is equal to -8, but (-2) ** (3.000001) is undefined.When an exponentiation is evaluated in floating point and there is a possibilitythat the result is undefined, the exponent is evaluated at run time to determine if ithas an integral value. If not, a diagnostic message is issued.Intrinsic functions evaluated in floating-point arithmeticIn compatibility mode, floating-point intrinsic functions always return a long(64-bit) floating-point value. In extended mode, floating-point intrinsic functionsalways return an extended-precision (128-bit) floating-point value.Mixed functions that have at least one floating-point argument are evaluated usingfloating-point arithmetic.RELATED REFERENCES“Terminology used <strong>for</strong> intermediate results” on page 688“ARITH” on page 306Arithmetic expressions in nonarithmetic statementsArithmetic expressions can appear in contexts other than arithmetic statements. Forexample, you can use an arithmetic expression with the IF or EVALUATE statement.In such statements, the rules <strong>for</strong> intermediate results with fixed-point data and <strong>for</strong>intermediate results with floating-point data apply, with the following changes:vvAbbreviated IF statements are handled as though the statements were notabbreviated.In an explicit relation condition where at least one of the comparands is anarithmetic expression, dmax is the maximum number of decimal places <strong>for</strong> anyoperand of either comparand, excluding divisors and exponents. The rules <strong>for</strong>floating-point arithmetic apply if any of the following conditions is true:Appendix A. Intermediate results and arithmetic precision 695


v– Any operand in either comparand is COMP-1, COMP-2, external floating point,or a floating-point literal.– An exponent contains decimal places.– An exponent is an expression that contains an exponentiation or divisionoperator, and dmax is greater than zero.For example:IF operand-1 = expression-1 THEN...If operand-1 is a data-name defined to be COMP-2, the rules <strong>for</strong> floating-pointarithmetic apply to expression-1 even if it contains only fixed-point operands,because it is being compared to a floating-point operand.When the comparison between an arithmetic expression and another data itemor arithmetic expression does not use a relational operator (that is, there is noexplicit relation condition), the arithmetic expression is evaluated without regardto the attributes of its comparand. For example:EVALUATE expression-1WHEN expression-2 THRU expression-3WHEN expression-4...END-EVALUATEIn the statement above, each arithmetic expression is evaluated in fixed-point orfloating-point arithmetic based on its own characteristics.RELATED CONCEPTS“Fixed-point contrasted with floating-point arithmetic” on page 64RELATED REFERENCES“Terminology used <strong>for</strong> intermediate results” on page 688“Fixed-point data and intermediate results” on page 689“Floating-point data and intermediate results” on page 694IF statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)EVALUATE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Conditional expressions (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)696 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix B. Complex OCCURS DEPENDING ONSeveral types of complex OCCURS DEPENDING ON (complex ODO) are possible.Complex ODO is supported as an extension to Standard <strong>COBOL</strong> 85.The basic <strong>for</strong>ms of complex ODO permitted by the compiler are as follows:v Variably located item or group: A data item described by an OCCURS clause withthe DEPENDING ON phrase is followed by a nonsubordinate elementary or groupdata item.v Variably located table: A data item described by an OCCURS clause with theDEPENDING ON phrase is followed by a nonsubordinate data item described by anOCCURS clause.v Table that has variable-length elements: A data item described by an OCCURSclause contains a subordinate data item described by an OCCURS clause with theDEPENDING ON phrase.v Index name <strong>for</strong> a table that has variable-length elements.v Element of a table that has variable-length elements.“Example: complex ODO”RELATED TASKS“Preventing index errors when changing ODO object value” on page 699“Preventing overlay when adding elements to a variable table” on page 699Example: complex ODORELATED REFERENCES“Effects of change in ODO object value” on page 698OCCURS DEPENDING ON clause (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)The following example illustrates the possible types of occurrence of complexODO.01 FIELD-A.02 COUNTER-1 PIC S99.02 COUNTER-2 PIC S99.02 TABLE-1.03 RECORD-1 OCCURS 1 TO 5 TIMESDEPENDING 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 TIMESDEPENDING ON COUNTER-2.04 DATA-NUM PIC S99.Definition: In the example, COUNTER-1 is an ODO object, that is, it is the object ofthe 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 asfollows:© Copyright IBM Corp. 1991, 2009 697


(1) A variably located item: EMPLOYEE-NUMBER is a data item that follows, but isnot 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 notsubordinate 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 asubordinate data item, RECORD-2, whose number of occurrences variesdepending on the content of its ODO object.(4) An index-name, INDX, <strong>for</strong> a table that has variable-length elements.(5) An element, TABLE-ITEM, of a table that has variable-length elements.How length is calculatedThe length of the variable portion of each record is the product of its ODO objectand the length of its ODO subject. For example, whenever a reference is made toone of the complex ODO items shown above, the actual length, if used, iscomputed as follows:vvvThe length of TABLE-1 is calculated by multiplying the contents of COUNTER-1 (thenumber of occurrences of RECORD-1) by 3 (the length of RECORD-1).The length of TABLE-2 is calculated by multiplying the contents of COUNTER-2 (thenumber of occurrences of RECORD-2) by 2 (the length of RECORD-2), and addingthe length of TABLE-ITEM.The length of FIELD-A is calculated by adding the lengths of COUNTER-1,COUNTER-2, TABLE-1, EMPLOYEE-NUMBER, and TABLE-2 times 5.Setting values of ODO objectsYou must set every ODO object in a group item be<strong>for</strong>e you reference any complexODO item in the group. For example, be<strong>for</strong>e you refer to EMPLOYEE-NUMBER in thecode above, you must set COUNTER-1 and COUNTER-2 even though EMPLOYEE-NUMBERdoes not directly depend on either ODO object <strong>for</strong> its value.Restriction: An ODO object cannot be variably located.Effects of change in ODO object valueIf a data item that is described by an OCCURS clause with the DEPENDING ON phraseis followed in the same group by one or more nonsubordinate data items (a <strong>for</strong>mof complex ODO), any change in value of the ODO object affects subsequentreferences to complex ODO items in the record.For example:v The size of any group that contains the relevant ODO clause reflects the newvalue of the ODO object.v A MOVE to a group that contains the ODO subject is made based on the newvalue of the ODO object.v The location of any nonsubordinate items that follow the item described withthe ODO clause is affected by the new value of the ODO object. (To preserve thecontents of the nonsubordinate items, move them to a work area be<strong>for</strong>e thevalue of the ODO object changes, then move them back.)698 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


The value of an ODO object can change when you move data to the ODO object orto the group in which it is contained. The value can also change if the ODO objectis contained in a record that is the target of a READ statement.RELATED TASKS“Preventing index errors when changing ODO object value”“Preventing overlay when adding elements to a variable table”Preventing index errors when changing ODO object valueBe careful if you reference a complex-ODO index-name, that is, an index-name <strong>for</strong>a table that has variable-length elements, after having changed the value of theODO object <strong>for</strong> a subordinate data item in the table.When you change the value of an ODO object, the byte offset in an associatedcomplex-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 areference to the index-name such as:v A reference to an element of the tablev A SET statement of the <strong>for</strong>m SET integer-data-item TO index-name (<strong>for</strong>mat 1)v A SET statement of the <strong>for</strong>m SET index-name UP|DOWN BY integer (<strong>for</strong>mat 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 correspondsto 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 animplicit conversion: the index-name receives the offset that corresponds to thetable element occurrence number in the integer item. The offset is computedaccording 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 697) when the ODO object COUNTER-2 changes.77 INTEGER-DATA-ITEM-1 PIC 99....SET INDX TO 5.* INDX is valid at this point.SET INTEGER-DATA-ITEM-1 TO INDX.* INTEGER-DATA-ITEM-1 now has the* occurrence number that corresponds to INDX.MOVE NEW-VALUE TO COUNTER-2.* INDX is not valid at this point.SET INDX TO INTEGER-DATA-ITEM-1.* INDX is now valid, containing the offset* that corresponds to INTEGER-DATA-ITEM-1, and* can be used with the expected results.RELATED REFERENCESSET statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)Preventing overlay when adding elements to a variable tableBe careful if you increase the number of elements in a variable-occurrence tablethat is followed by one or more nonsubordinate data items in the same group.Appendix B. Complex OCCURS DEPENDING ON 699


When you increment the value of the ODO object and add an element to a table,you can inadvertently overlay the variably located data items that follow the table.To avoid this type of error, do these steps:1. Save the variably located data items that follow the table in another data area.2. Increment the value of the ODO object.3. Move data into the new table element (if needed).4. Restore the variably located data items from the data area where you savedthem.In the following example, suppose you want to add an element to the tableVARY-FIELD-1, whose number of elements depends on the ODO object CONTROL-1.VARY-FIELD-1 is followed by the nonsubordinate variably located data itemGROUP-ITEM-1, whose elements could potentially be overlaid.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 TIMESDEPENDING ON CONTROL-1PIC X(5).05 GROUP-ITEM-1.10 VARY-FIELD-2OCCURS 1 TO 10 TIMESDEPENDING ON CONTROL-2 PIC X(9).01 STORE-VARY-FIELD-2.05 GROUP-ITEM-2.10 VARY-FLD-2OCCURS 1 TO 10 TIMESDEPENDING ON CONTROL-2 PIC X(9).Each element of VARY-FIELD-1 has 5 bytes, and each element of VARY-FIELD-2 has 9bytes. If CONTROL-1 and CONTROL-2 both contain the value 3, you can picture storage<strong>for</strong> VARY-FIELD-1 and VARY-FIELD-2 as follows:VARY-FIELD-1(1)VARY-FIELD-1(2)VARY-FIELD-1(3)VARY-FIELD-2(1)VARY-FIELD-2(2)VARY-FIELD-2(3)To add a fourth element to VARY-FIELD-1, code as follows to prevent overlaying thefirst 5 bytes of VARY-FIELD-2. (GROUP-ITEM-2 serves as temporary storage <strong>for</strong> thevariably located GROUP-ITEM-1.)MOVE GROUP-ITEM-1 TO GROUP-ITEM-2.ADD 1 TO CONTROL-1.MOVE five-byte-field TOVARY-FIELD-1 (CONTROL-1).MOVE GROUP-ITEM-2 TO GROUP-ITEM-1.You can picture the updated storage <strong>for</strong> VARY-FIELD-1 and VARY-FIELD-2 as follows:700 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


VARY-FIELD-1(1)VARY-FIELD-1(2)VARY-FIELD-1(3)VARY-FIELD-1(4)VARY-FIELD-2(1)VARY-FIELD-2(2)VARY-FIELD-2(3)Note that the fourth element of VARY-FIELD-1 did not overlay the first element ofVARY-FIELD-2.Appendix B. Complex OCCURS DEPENDING ON 701


702 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix C. Converting double-byte character set (DBCS)dataThe Language Environment service routines IGZCA2D and IGZCD2A wereintended <strong>for</strong> converting alphanumeric data items that contain DBCS data to andfrom pure DBCS data items in order to reliably per<strong>for</strong>m operations such as STRING,UNSTRING, and reference modification.These service routines continue to be provided <strong>for</strong> compatibility; however, usingnational data items and the national conversion operations is now recommendedinstead <strong>for</strong> this purpose.The service routines do not support a code-page argument and are not sensitive tothe code page specified by the CODEPAGE compiler option. The DBCS compiler optiondoes not affect their operation.RELATED TASKS“Converting to or from national (Unicode) representation” on page 134“Processing alphanumeric data items that contain DBCS data” on page 143DBCS notationRELATED REFERENCES“DBCS notation”“Alphanumeric to DBCS data conversion (IGZCA2D)”“DBCS to alphanumeric data conversion (IGZCD2A)” on page 706“CODEPAGE” on page 310The symbols shown below are used in the DBCS data conversion examples todescribe DBCS items.SymbolsMeaning< and > Shift-out (SO) and shift-in (SI), respectivelyD0,D1,D2,...,DnAny DBCS character except <strong>for</strong> double-byte EBCDICcharacters that correspond to single-byte EBCDICcharacters.A,.B,.C,...Anydouble-byte EBCDIC character that correspondsto a single-byte EBCDIC character. The period (.)represents the value X’42’.A single letter, such as A, B, or s Any single-byte EBCDIC characterAlphanumeric to DBCS data conversion (IGZCA2D)The Language Environment IGZCA2D service routine converts alphanumeric datathat contains double-byte characters to pure DBCS data.© Copyright IBM Corp. 1991, 2009 703


IGZCA2D syntaxTo use the IGZCA2D service routine, pass the following four parameters to theroutine by using the CALL statement:parameter-1The sending field <strong>for</strong> the conversion, handled as an alphanumeric dataitem.parameter-2The receiving field <strong>for</strong> the conversion, handled as a DBCS data item.You cannot use reference modification with parameter-2.parameter-3The number of bytes in parameter-1 to be converted.It can be the LENGTH OF special register of parameter-1, or a 4-byte USAGE ISBINARY data item containing the number of bytes of parameter-1 to beconverted. Shift codes count as 1 byte each.parameter-4The number of bytes in parameter-2 that will receive the converted data.It can be the LENGTH OF special register of parameter-2, or a 4-byte USAGE ISBINARY data item containing the number of bytes of parameter-2 to receivethe converted data.Usage notesv You can pass parameter-1, parameter-3, and parameter-4 to the routine BYREFERENCE or BY CONTENT, but you must pass parameter-2 BY REFERENCE.v The compiler does not per<strong>for</strong>m syntax checking on these parameters. Ensure thatthe parameters are correctly set and passed in the CALL statement to theconversion routine. Otherwise, results are unpredictable.v When creating parameter-2 from parameter-1, IGZCA2D makes these changes:– Removes the shift codes, leaving the DBCS data unchanged– Converts the single-byte (nonspace) EBCDIC character X’nn’ to a characterrepresented by X’42nn’– Converts the single-byte space (X’40’) to DBCS space (X’4040’), instead ofX’4240’v IGZCA2D does not change the contents of parameter-1, parameter-3, orparameter-4.v The valid range <strong>for</strong> the contents of parameter-3 and <strong>for</strong> the contents ofparameter-4 is 1 to 134,217,727.“Example: IGZCA2D” on page 705RELATED REFERENCES“IGZCA2D return codes”IGZCA2D return codesIGZCA2D sets the RETURN-CODE special register to reflect the status of the conversion.704 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 96. IGZCA2D return codesReturn code Explanation0 parameter-1 was converted and the results were placed in parameter-2.2 parameter-1 was converted and the results were placed in parameter-2.parameter-2 was padded on the right with DBCS spaces.4 parameter-1 was converted and the results were placed in parameter-2. TheDBCS data placed in parameter-2 was truncated on the right.6 parameter-1 was converted and the results were placed in parameter-2. Asingle-byte character in the range X’00’ to X’3F’ or X’FF’ wasencountered. The valid single-byte character was converted into anout-of-range DBCS character.8 parameter-1 was converted and the results were placed in parameter-2. Asingle-byte character in the range X’00’ to X’3F’ or X’FF’ wasencountered. The valid single-byte character was converted into anout-of-range DBCS character.parameter-2 was padded on the right with DBCS spaces.10 parameter-1 was converted and the results were placed in parameter-2. Asingle-byte character in the range X’00’ to X’3F’ or X’FF’ wasencountered. The valid single-byte character was converted into anout-of-range DBCS character.The DBCS data in parameter-2 was truncated on the right.12 An odd number of bytes was found between paired shift codes inparameter-1. No conversion occurred.13 Unpaired or nested shift codes were found in parameter-1. No conversionoccurred.14 parameter-1 and parameter-2 were overlapping. No conversion occurred.15 The value provided <strong>for</strong> parameter-3 or parameter-4 was out of range. Noconversion occurred.16 An odd number of bytes was coded in parameter-4. No conversionoccurred.Example: IGZCA2DThis example CALL statement converts the alphanumeric data in alpha-item toDBCS data. The results of the conversion are placed in dbcs-item.CALL "IGZCA2D" USING BY REFERENCE alpha-item dbcs-itemBY CONTENT LENGTH OF alpha-item LENGTH OF dbcs-itemSuppose the contents of alpha-item and dbcs-item and the lengths be<strong>for</strong>e theconversion are:alpha-item = ABCDdbcs-item = D4D5D6D7D8D9D0LENGTH OF alpha-item = 12LENGTH OF dbcs-item = 14Then after the conversion, alpha-item and dbcs-item will contain:alpha-item = ABCDdbcs-item = .A.BD1D2D3.C.DThe content of the RETURN-CODE register is 0.Appendix C. Converting double-byte character set (DBCS) data 705


RELATED REFERENCES“DBCS notation” on page 703DBCS to alphanumeric data conversion (IGZCD2A)The Language Environment IGZCD2A routine converts pure DBCS data toalphanumeric data that can contain double-byte characters.IGZCD2A syntaxTo use the IGZCD2A service routine, pass the following four parameters to theroutine using the CALL statement:parameter-1The sending field <strong>for</strong> the conversion, handled as a DBCS data item.parameter-2The receiving field <strong>for</strong> the conversion, handled as an alphanumeric dataitem.parameter-3The number of bytes in parameter-1 to be converted.It can be the LENGTH OF special register of parameter-1, or a 4-byte USAGE ISBINARY data item containing the number of bytes of parameter-1 to beconverted.parameter-4The number of bytes in parameter-2 that will receive the converted data.It can be the LENGTH OF special register of parameter-2, or a 4-byte USAGE ISBINARY data item containing the number of bytes of parameter-2 to receivethe converted data. Shift codes count as 1 byte each.Usage notesv You can pass parameter-1, parameter-3, and parameter-4 to the routine BYREFERENCE or BY CONTENT, but you must pass parameter-2 BY REFERENCE.v The compiler does not per<strong>for</strong>m syntax checking on these parameters. Ensure thatthe parameters are correctly set and passed to the conversion routine. Otherwise,results are unpredictable.v When creating parameter-2 from parameter-1, IGZCD2A makes these changes:– Inserts shift codes around DBCS characters that do not correspond tosingle-byte EBCDIC characters– Converts DBCS characters to single-byte characters when the DBCS characterscorrespond to single-byte EBCDIC characters– Converts the DBCS space (X’4040’) to a single-byte space (X’40’)v IGZCD2A does not change the contents of parameter-1, parameter-3, orparameter-4.v If the converted data contains double-byte characters, shift codes are counted inthe length of parameter-2.v The valid range <strong>for</strong> the contents of parameter-3 and <strong>for</strong> the contents ofparameter-4 is 1 to 134,217,727.“Example: IGZCD2A” on page 707706 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED REFERENCES“IGZCD2A return codes”IGZCD2A return codesIGZCD2A sets the RETURN-CODE special register to reflect the status of the conversion.Table 97. IGZCD2A return codesReturn code Explanation0 parameter-1 was converted and the results were placed in parameter-2.2 parameter-1 was converted and the results were placed in parameter-2.parameter-2 was padded on the right with single-byte spaces.4 parameter-1 was converted and the results were placed in parameter-2.parameter-2 was truncated on the right. 114 parameter-1 and parameter-2 were overlapping. No conversion occurred.15 The value of parameter-3 or parameter-4 was out of range. No conversionoccurred.16 An odd number of bytes was coded in parameter-3. No conversionoccurred.1. If a truncation occurs within the DBCS characters, the truncation is on an even-byteboundary and a shift-in (SI) is inserted. If necessary, the alphanumeric data is paddedwith a single-byte space after the shift-in.Example: IGZCD2AThis example CALL statement converts the DBCS data in dbcs-item to alphanumericdata with double-byte characters. The results of the conversion are placed inalpha-item.CALL "IGZCD2A" USING BY REFERENCE dbcs-item alpha-itemBY CONTENT LENGTH OF dbcs-item LENGTH OF alpha-itemSuppose the contents of dbcs-item and alpha-item and the lengths be<strong>for</strong>e theconversion are:dbcs-item = .A.BD1D2D3.C.Dalpha-item = ssssssssssssLENGTH OF dbcs-item = 14LENGTH OF alpha-item = 12Then after the conversion, dbcs-item and alpha-item will contain:dbcs-item = .A.BD1D2D3.C.Dalpha-item = ABCDThe content of the RETURN-CODE register is 0.RELATED REFERENCES“DBCS notation” on page 703Appendix C. Converting double-byte character set (DBCS) data 707


708 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix D. XML reference materialThe following in<strong>for</strong>mation describes the XML exception codes that might bereturned during XML parsing or XML generation.RELATED REFERENCES“XML PARSE exceptions with XMLPARSE(XMLSS) in effect”“XML PARSE exceptions with XMLPARSE(COMPAT) in effect” on page 711“XML GENERATE exceptions” on page 718XML specificationXML PARSE exceptions with XMLPARSE(XMLSS) in effect||||||||When the z/<strong>OS</strong> XML System Services parser passes control to your processingprocedure <strong>for</strong> an exception event, the XML-CODE special register contains theexception code, which is <strong>for</strong>med from a return code and a reason code.The return code and reason code are each a halfword binary value. The exceptioncode is the concatenation of those two values: the return code in the high-orderhalfword, and the reason code in the low-order halfword.The return codes and reason codes are documented as hexadecimal values in thez/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and Reference, referenced below.After an exception event, the parser does not continue processing; the value inXML-CODE at the end of the XML PARSE statement is the original exception code setby the parser. (For an exception event, any changes that you make to XML-CODE inthe processing procedure are ignored.)When the processing procedure returns to the parser after the exception event,control transfers to the statement specified in the ON EXCEPTION phrase, or to theend of the XML PARSE statement if you did not code an ON EXCEPTION phrase.|Validation exceptions:If you code an XML PARSE statement that contains the VALIDATING phrase, and thez/<strong>OS</strong> XML System Services parser determines that the document is not valid, theparser generates return code 24 (hexadecimal 18, XRC_NOT_VALID).|||||||||||Exceptions that are unique to <strong>Enterprise</strong> <strong>COBOL</strong>:Some exceptions are unique to <strong>Enterprise</strong> <strong>COBOL</strong> and thus are not documented inthe z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and Reference, <strong>for</strong> example, errors thatoccur during XML schema retrieval. The exception codes <strong>for</strong> such errors are<strong>for</strong>med from return code 16 (hexadecimal 0010, XRC_FATAL) and the reason codesthat are shown in the following table.Table 98. Reason codes <strong>for</strong> XML PARSE exceptions that are unique to <strong>Enterprise</strong><strong>COBOL</strong>Reason code(hexadecimal) Description700 VALIDATING WITH FILE is not supported under CICS.© Copyright IBM Corp. 1991, 2009 709


||||||||||||||||||||||||||||||||||Table 98. Reason codes <strong>for</strong> XML PARSE exceptions that are unique to <strong>Enterprise</strong><strong>COBOL</strong> (continued)Reason code(hexadecimal) Description701 The optimized XML schema that was read in was too short, or the filewas empty.702 The file identifier <strong>for</strong> the schema was not a ddname orenvironment-variable name.703 The DSN value contained a space character in a position where a space isnot allowed.704 The DSN value specified a temporary data set.705 The PATH value contained an unescaped space character.706 The PATH value contained a path name that was not an absolute path.707 Memory allocation <strong>for</strong> the XML schema buffer failed.708 The environment variable was null or contained only spaces.709 The environment variable contained an invalid keyword.710 The DSN value contained an invalid character after the member name.711 The DSN value did not specify a member name.712 The DSN value did not specify a data set name, or parentheses were notspecified correctly.713 The PATH value did not specify a path name, or parentheses were notspecified correctly.714 The DSN value contained an extra parenthesis.715 The PATH value contained an extra parenthesis.716 The DSN value was missing the closing parenthesis.717 The PATH value was missing the closing parenthesis.718 The DSN value contained an escape character.720 A character reference <strong>for</strong> an unrepresentable character was not resolved.721 An unrepresentable character reference in the document type declarationis not supported.900 Internal error. Report the error to your service representative.For any of the reason codes except 900, correct the error and then retry yourprogram.RELATED CONCEPTS“XML-CODE” on page 511RELATED TASKS“Handling XML PARSE exceptions” on page 526RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)XML PARSE statement (<strong>Enterprise</strong> <strong>COBOL</strong> Language Reference)z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> and Reference710 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


XML PARSE exceptions with XMLPARSE(COMPAT) in effect|||||When an exception event occurs, the XML parser that is provided with the<strong>Enterprise</strong> <strong>COBOL</strong> library sets special register XML-CODE to a value that identifiesthe exception. Depending on the value in XML-CODE, the parser might or might notbe able to continue processing after the exception, as detailed in the in<strong>for</strong>mationreferenced below.RELATED REFERENCES“XML PARSE exceptions that allow continuation”“XML PARSE exceptions that do not allow continuation” on page 715XML PARSE exceptions that allow continuation|||||If the XMLPARSE(COMPAT) compiler option is in effect, whether the XML parser cancontinue processing after an exception event depends upon the value of theexception code.The parser can continue processing if the exception code, which is in specialregister XML-CODE, is within one of the following ranges:v 1-99v 100,001 - 165,535The following table describes each exception, and identifies the actions that theparser takes if you request that it continue after the exception. Some of thedescriptions use the following terms:v Actual document encodingv Document encoding declarationFor definitions of the terms, see the related concept about XML input documentencoding.|||||||Table 99. XML PARSE exceptions that allow continuation (<strong>for</strong> XMLPARSE(COMPAT))Exceptioncode(decimal) Description Parser action on continuation1 The parser found an invalidcharacter while scanning whitespace outside element content.For further in<strong>for</strong>mation aboutwhite space, see the relatedconcept about XML inputdocument encoding.2 The parser found an invalidstart of a processinginstruction, element, comment,or document type declarationoutside element content.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.Appendix D. XML reference material 711


|||Table 99. XML PARSE exceptions that allow continuation (<strong>for</strong>XMLPARSE(COMPAT)) (continued)Exceptioncode(decimal) Description Parser action on continuation3 The parser found a duplicateattribute name.4 The parser found the markupcharacter ’’without the matching openingcharacter sequence’’.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.712 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


||||||Table 99. XML PARSE exceptions that allow continuation (<strong>for</strong>XMLPARSE(COMPAT)) (continued)Exceptioncode(decimal) Description Parser action on continuation11 The parser found an invalidcharacter in a processinginstruction data segment.12 The XML declaration was notat the beginning of thedocument.13 The parser found an invaliddigit in a hexadecimal characterreference (of the <strong>for</strong>m&#xdddd;).14 The parser found an invaliddigit in a decimal characterreference (of the <strong>for</strong>m &#dddd;).15 The encoding declaration valuein the XML declaration did notbegin with lowercase oruppercase A through Z.16 A character reference did notrefer to a legal XML character.17 The parser found an invalidcharacter in an entity referencename.18 The parser found an invalidcharacter in an attribute value.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.The parser continues detecting errors untilit reaches the end of the document orencounters an error that does not allowcontinuation. The parser does not signalany further normal events, except <strong>for</strong> theEND-OF-DOCUMENT event.Appendix D. XML reference material 713


|||Table 99. XML PARSE exceptions that allow continuation (<strong>for</strong>XMLPARSE(COMPAT)) (continued)Exceptioncode(decimal) Description Parser action on continuation70 The actual document encodingwas EBCDIC, and the CODEPAGEcompiler option specified asupported EBCDIC code page,but the document encodingdeclaration did not specify asupported EBCDIC code page.71 The actual document encodingwas EBCDIC, and thedocument encoding declarationspecified a supported EBCDICencoding, but the CODEPAGEcompiler option did not specifya supported EBCDIC codepage.72 The actual document encodingwas EBCDIC, the CODEPAGEcompiler option did not specifya supported EBCDIC codepage, and the document didnot contain an encodingdeclaration.73 The actual document encodingwas EBCDIC, but neither theCODEPAGE compiler option northe document encodingdeclaration specified asupported EBCDIC code page.82 The actual document encodingwas ASCII, but the documentdid not contain an encodingdeclaration.83 The actual document encodingwas ASCII, but the documentencoding declaration did notspecify code page 813, 819, or920.92 The document data item wasalphanumeric, but the actualdocument encoding wasUnicode UTF-16.100,001 -165,535The CODEPAGE compiler optionand the document encodingdeclaration specified differentsupported EBCDIC code pages.XML-CODE contains the codepage CCSID <strong>for</strong> the encodingdeclaration plus 100,000.The parser uses the encoding specified bytheCODEPAGE compiler option.The parser uses the encoding specified bythe document encoding declaration.The parser uses EBCDIC code page 1140(USA, Canada, ...EuroCountry ExtendedCode Page).The parser uses EBCDIC code page 1140(USA, Canada, ...EuroCountry ExtendedCode Page).The parser uses ASCII code page 819(ISO-8859-1 Latin 1/Open Systems).The parser uses ASCII code page 819(ISO-8859-1 Latin 1/Open Systems).The parser uses code page 1200 (UnicodeUTF-16).If you set XML-CODE to zero be<strong>for</strong>ereturning from the EXCEPTION event, theparser uses the encoding specified by theCODEPAGE compiler option. If you setXML-CODE to the CCSID <strong>for</strong> the documentencoding declaration (by subtracting100,000), the parser uses this encoding.714 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED CONCEPTS“XML-CODE” on page 511“XML input document encoding” on page 521RELATED TASKS“Handling XML PARSE exceptions” on page 526RELATED REFERENCES“XMLPARSE” on page 357 (compiler option)XML PARSE exceptions that do not allow continuation||||||If the XMLPARSE(COMPAT) compiler option is in effect, the XML parser cannotcontinue processing if any of the exceptions described below occurs.No further events are returned from the parser <strong>for</strong> any of these exceptions even ifthe processing procedure sets XML-CODE to zero be<strong>for</strong>e passing control back to theparser. The parser transfers control to the statement in the ON EXCEPTION phrase, ifspecified, otherwise to the end of the XML PARSE statement.Table 100. XML PARSE exceptions that do not allow continuation (<strong>for</strong>XMLPARSE(COMPAT))Exceptioncode (decimal) Description100 The parser reached the end of the document while scanning the start ofthe XML declaration.101 The parser reached the end of the document while looking <strong>for</strong> the end ofthe XML declaration.102 The parser reached the end of the document while looking <strong>for</strong> the rootelement.103 The parser reached the end of the document while looking <strong>for</strong> the versionin<strong>for</strong>mation in the XML declaration.104 The parser reached the end of the document while looking <strong>for</strong> the versionin<strong>for</strong>mation value in the XML declaration.106 The parser reached the end of the document while looking <strong>for</strong> theencoding declaration value in the XML declaration.108 The parser reached the end of the document while looking <strong>for</strong> thestandalone declaration value in the XML declaration.109 The parser reached the end of the document while scanning an attributename.110 The parser reached the end of the document while scanning an attributevalue.111 The parser reached the end of the document while scanning a characterreference or entity reference in an attribute value.112 The parser reached the end of the document while scanning an emptyelement tag.113 The parser reached the end of the document while scanning the rootelement name.114 The parser reached the end of the document while scanning an elementname.115 The parser reached the end of the document while scanning character datain element content.Appendix D. XML reference material 715


||||Table 100. XML PARSE exceptions that do not allow continuation (<strong>for</strong>XMLPARSE(COMPAT)) (continued)Exceptioncode (decimal) Description116 The parser reached the end of the document while scanning a processinginstruction in element content.117 The parser reached the end of the document while scanning a comment orCDATA section in element content.118 The parser reached the end of the document while scanning a comment inelement content.119 The parser reached the end of the document while scanning a CDATAsection in element content.120 The parser reached the end of the document while scanning a characterreference or entity reference in element content.121 The parser reached the end of the document while scanning after the closeof the root element.122 The parser found a possible invalid start of a document type declaration.123 The parser found a second document type declaration.124 The first character of the root element name was not a letter, ’_’, or ’:’.125 The first character of the first attribute name of an element was not aletter, ’_’, or ’:’.126 The parser found an invalid character either in or following an elementname.127 The parser found a character other than ’=’ following an attribute name.128 The parser found an invalid attribute value delimiter.130 The first character of an attribute name was not a letter, ’_’, or ’:’.131 The parser found an invalid character either in or following an attributename.132 An empty element tag was not terminated by a ’>’ following the ’/’.133 The first character of an element end tag name was not a letter, ’_’, or ’:’.134 An element end tag name was not terminated by a ’>’.135 The first character of an element name was not a letter, ’_’, or ’:’.136 The parser found an invalid start of a comment or CDATA section inelement content.137 The parser found an invalid start of a comment.138 The first character of a processing instruction target name was not a letter,’_’, or ’:’.139 The parser found an invalid character in or following a processinginstruction target name.140 A processing instruction was not terminated by the closing charactersequence ’?>’.141 The parser found an invalid character following ’&’ in a characterreference or entity reference.142 The version in<strong>for</strong>mation was not present in the XML declaration.143 ’version’ in the XML declaration was not followed by ’=’.144 The version declaration value in the XML declaration is either missing orimproperly delimited.716 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


||||Table 100. XML PARSE exceptions that do not allow continuation (<strong>for</strong>XMLPARSE(COMPAT)) (continued)Exceptioncode (decimal) Description145 The version in<strong>for</strong>mation value in the XML declaration specified a badcharacter, or the start and end delimiters did not match.146 The parser found an invalid character following the version in<strong>for</strong>mationvalue closing delimiter in the XML declaration.147 The parser found an invalid attribute instead of the optional encodingdeclaration in the XML declaration.148 ’encoding’ in the XML declaration was not followed by ’=’.149 The encoding declaration value in the XML declaration is either missingor improperly delimited.150 The encoding declaration value in the XML declaration specified a badcharacter, or the start and end delimiters did not match.151 The parser found an invalid character following the encoding declarationvalue closing delimiter in the XML declaration.152 The parser found an invalid attribute instead of the optional standalonedeclaration in the XML declaration.153 standalone in the XML declaration was not followed by =.154 The standalone declaration value in the XML declaration is either missingor improperly delimited.155 The standalone declaration value was neither ’yes’ nor ’no’ only.156 The standalone declaration value in the XML declaration specified a badcharacter, or the start and end delimiters did not match.157 The parser found an invalid character following the standalonedeclaration value closing delimiter in the XML declaration.158 The XML declaration was not terminated by the proper character sequence’?>’, or contained an invalid attribute.159 The parser found the start of a document type declaration after the end ofthe root element.160 The parser found the start of an element after the end of the root element.315 The actual document encoding was UTF-16 little-endian, which the parserdoes not support on this plat<strong>for</strong>m.316 The actual document encoding was UCS4, which the parser does notsupport.317 The parser cannot determine the document encoding. The documentmight be damaged.318 The actual document encoding was UTF-8, which the parser does notsupport.320 The document data item was national, but the actual document encodingwas EBCDIC.321 The document data item was national, but the actual document encodingwas ASCII.500 - 599 Internal error. Report the error to your service representative.RELATED CONCEPTS“XML-CODE” on page 511Appendix D. XML reference material 717


XML GENERATE exceptionsRELATED TASKS“Handling XML PARSE exceptions” on page 526One of several exception codes might be returned in the XML-CODE special registerduring XML generation. If one of these exceptions occurs, control is passed to thestatement in the ON EXCEPTION phrase, or to the end of the XML GENERATE statementif you did not code an ON EXCEPTION phrase.||||Table 101. XML GENERATE exceptionsExceptioncode (decimal) Description400 The receiver was too small to contain the generated XML document. TheCOUNT IN data item, if specified, contains the count of character positionsthat were actually generated.401 A DBCS data-name contained a character that, when converted toUnicode, was not valid in an XML element or attribute name.402 The first character of a DBCS data-name, when converted to Unicode, wasnot valid as the first character of an XML element or attribute name.403 The value of an OCCURS DEPENDING ON variable exceeded 16,777,215.410 The CCSID page specified by the CODEPAGE compiler option is notsupported <strong>for</strong> conversion to Unicode.411 The CCSID specified by the CODEPAGE compiler option is not a supportedsingle-byte EBCDIC CCSID.414 The CCSID specified <strong>for</strong> the XML document was invalid or was notsupported.415 The receiver was national, but the encoding specified <strong>for</strong> the documentwas not UTF-16.416 The XML namespace identifier contained invalid XML characters.417 Element character content or an attribute value contained characters thatare illegal in XML content. XML generation has continued, with theelement tag name or the attribute name prefixed with ’hex.’ and theoriginal data value represented in the document in hexadecimal.418 Substitution characters were generated by encoding conversion.419 The XML namespace prefix was invalid.600-699 Internal error. Report the error to your service representative.RELATED TASKS“Handling XML GENERATE exceptions” on page 548718 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix E. EXIT compiler option|||||Use the EXIT option to provide user-supplied modules in place of various compilerfunctions.For compiler input, use the INEXIT and LIBEXIT suboptions to provide modules inplace of SYSIN and SYSLIB (or copy library), respectively. For compiler output, usethe PRTEXIT suboption to provide a module in place of SYSPRINT.To provide a module that will be called <strong>for</strong> each SYSADATA record immediatelyafter the record has been written out to the file, use the ADEXIT suboption.|||||To customize compiler messages (change their severity or suppress them, includingconverting FIPS (FLAGSTD) messages to diagnostic messages to which you assign aseverity), use the MSGEXIT suboption. The module that you provide to customizethe messages will be called each time the compiler issues a diagnostic message or aFIPS message.EXIT option syntax|►►NOEXIT►◄EXIT( ▼)INEXIT(mod1)str1,NOINEXITLIBEXIT(mod2)str2,NOLIBEXITPRTEXIT(mod3)str3,NOPRTEXITADEXIT(mod4)str4,NOADEXITMSGEXIT(mod5)str5,NOMSGEXITDefault is: NOEXIT|Abbreviations are: EX(INX|NOINX, LIBX|NOLIBX, PRTX|NOPRTX, ADX|NOADX,MSGX|NOMSGX)You can specify the suboptions in any order, and can separate them by eithercommas or spaces. If you specify both the positive and negative <strong>for</strong>m of asuboption, the <strong>for</strong>m specified last takes effect. If you specify the same suboptionmore than once, the last one specified takes effect.© Copyright IBM Corp. 1991, 2009 719


If you specify the EXIT option without specifying at least one suboption, NOEXITwill be in effect.||||||||You can specify the EXIT option only at invocation in the JCL PARM field (underTSO/E, in a command argument) or at installation time. Do not specify the EXIToption in a PROCESS (CBL) statement.INEXIT(['str1',]mod1)The compiler reads source code from a user-supplied load module (wheremod1 is the module name) instead of SYSIN.LIBEXIT(['str2',]mod2)The compiler obtains copybooks from a user-supplied load module (wheremod2 is the module name) instead of library-name or SYSLIB. For use witheither COPY or BASIS statements.PRTEXIT(['str3',]mod3)The compiler passes printer-destined output to the user-supplied loadmodule (where mod3 is the module name) instead of SYSPRINT.ADEXIT(['str4',]mod4)The compiler passes the SYSADATA output to the user-supplied loadmodule (where mod4 is the module name).MSGEXIT(['str5',]mod5)The compiler passes the message number, and passes the default severityof a compiler diagnostic message, or the category (as a numeric code) of aFIPS compiler message, to the user-supplied load module (where mod5 isthe module name).The names mod1, mod2, mod3, mod4, and mod5 can refer to the same module.The suboptions str1, str2, str3, str4, and str5 are character strings that are passed tothe load module. These strings are optional. They can be up to 64 characters inlength, and you must enclose them in single quotation marks. You can use anycharacter in the strings, but any included single quotation marks must be doubled.Lowercase characters are folded to uppercase.If one of str1, str2, str3, str4, orstr5 is specified, that string is passed to theappropriate user-exit module in the following <strong>for</strong>mat, where LL is a halfword (on ahalfword boundary) that contains the length of the string.LLstring“Example: MSGEXIT user exit” on page 735RELATED TASKS“Using the user-exit work area” on page 721“Calling from exit modules” on page 721“Using the EXIT compiler option with CICS and SQL statements” on page 734RELATED REFERENCES“FLAGSTD” on page 323“Processing of INEXIT” on page 722“Processing of LIBEXIT” on page 723“Processing of PRTEXIT” on page 726“Processing of ADEXIT” on page 727720 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Using the user-exit work area“Processing of MSGEXIT” on page 729“Error handling <strong>for</strong> exit modules” on page 733When you use one of the user exits, the compiler provides a work area in whichyou can save the address of GETMAIN storage obtained by the exit module. Havingsuch a work area lets the module be reentrant.|The user-exit work area consists of 6 fullwords that reside on a fullword boundary.These fullwords are initialized to binary zeros be<strong>for</strong>e the first exit routine isinvoked. The address of the work area is passed to the exit module in a parameterlist. After initialization, the compiler makes no further reference to the work area.The words in the user-exit work area are used by the individual exit modules asshown in the following table.||Table 102. Layout of the user-exit work areaWord numberUsed by module:1 INEXIT2 LIBEXIT3 PRTEXIT4 ADEXIT5 (Reserved)6 MSGEXITCalling from exit modulesRELATED REFERENCES“Processing of INEXIT” on page 722“Processing of LIBEXIT” on page 723“Processing of PRTEXIT” on page 726“Processing of ADEXIT” on page 727“Processing of MSGEXIT” on page 729To call <strong>COBOL</strong> programs or library routines within your exit modules, usestandard <strong>COBOL</strong> linkage. You need to be aware of the register conventions inorder to trace the call chain correctly.When a call is made to a program or to a routine in an exit module, the registersare set up as follows:R1 Points to the parameter list passed to the called program or library routineR13 Points to the register save area provided by the calling program or routineR14 Holds the return address of the calling program or routineR15 Holds the address of the called program or routineExit modules must have RMODE attribute 24 and AMODE attribute ANY.RELATED CONCEPTS“Storage and its addressability” on page 42Appendix E. EXIT compiler option 721


Processing of INEXITThe INEXIT exit module is used to read source code from a user-supplied loadmodule in place of SYSIN.|Table 103. INEXIT processingAction by compilerLoads the exit module (mod1) duringinitializationCalls the exit module with an OPENoperation code (op code)Calls the exit module with a GET op codewhen a source statement is neededCalls the exit module with a CL<strong>OS</strong>E op codewhen the end-of-data is presentedAction by exit modulePrepares its source <strong>for</strong> processing. Passes thestatus of the OPEN request back to thecompiler.Returns either the address and length of thenext statement or the end-of-data indication(if no more source statements exist)Releases any resources that are related to itsoutputINEXIT parameters|||||||||||The compiler uses 10 parameters, passed by reference, to communicate with theexit module. The return code, data length, and data parameters are set by the exitmodule <strong>for</strong> return to the compiler; the other items are passed from the compiler tothe exit module.Table 104. INEXIT parametersParameternumber Parameter item Description of item1 User-exit type Halfword that identifies which user exit is to per<strong>for</strong>mthe operation.1=INEXIT2 Operation code Halfword that indicates the type of operation:v 0=OPENv 1=CL<strong>OS</strong>Ev 2=GET3 Return code Fullword, set by the exit module, that indicates thesuccess of the requested operation:v 0=Operation was successfulv 4=End-of-datav 12=Operation failed4 User-exit work area Six-fullword work area provided by the compiler <strong>for</strong>use by the user-exit module.First word: <strong>for</strong> use by INEXIT5 Data length Fullword, set by the exit module, that specifies thelength of the record being returned by the GEToperation (must be 80)722 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||||||Table 104. INEXIT parameters (continued)Parameternumber Parameter item Description of item6 Data or str1 Fullword, set by the exit module, that contains theaddress of the record in a user-owned buffer, <strong>for</strong> theGET operation.str1 applies only to OPEN. The first halfword (on ahalfword boundary) contains the length of the string,followed by the string.7 Not used (Used only by LIBEXIT and MSGEXIT)8 Not used (Used only by LIBEXIT)9 Not used (Used only by LIBEXIT)10 Not used (Used only by LIBEXIT)Processing of LIBEXITRELATED TASKS“Using the user-exit work area” on page 721“Calling from exit modules” on page 721“Using the EXIT compiler option with CICS and SQL statements” on page 734The LIBEXIT exit module is used in place of the SYSLIB, or library-name, data set.Calls are made to the module by the compiler to obtain copybooks whenever COPYor BASIS statements are encountered.If LIBEXIT is specified, the LIB compiler option must be in effect.|Table 105. LIBEXIT processingAction by compilerLoads the exit module (mod2)during initializationCalls the exit module with anOPEN operation code (op code)Calls the exit module with a FINDop code if the library-name wassuccessfully openedCalls the exit module with a GETop codeCalls the exit module with aCL<strong>OS</strong>E op code when theend-of-data is presentedAction by exit modulePrepares the specified library-name <strong>for</strong> processing.Passes the status of the OPEN request to thecompiler.Establishes positioning at the requested text-name (orbasis-name) in the specified library-name; this placebecomes the active copybook. Passes an appropriatereturn code to the compiler when positioning iscomplete.Passes the compiler either the length and address ofthe record to be copied from the active copybook orthe end-of-data indicatorReleases any resources that are related to its inputAppendix E. EXIT compiler option 723


Processing of LIBEXIT with nested COPY statementsAny record from the active copybook can contain a COPY statement. (However,nested COPY statements cannot contain the REPLACING phrase, and a COPY statementwith the REPLACING phrase cannot contain nested COPY statements.)You cannot make recursive calls to text-name. That is, a copybook can be namedonly once in a set of nested COPY statements until the end-of-data <strong>for</strong> thatcopybook is reached.The following table shows how the processing of LIBEXIT changes when there areone or more valid COPY statements that are not nested.|Table 106. LIBEXIT processing with nonnested COPY statementsAction by compilerAction by exit moduleLoads the exit module (mod2)during initializationCalls the exit module with anOPEN operation code (opcode)Calls the exit module with aFIND op code if thelibrary-name was successfullyopenedCalls the exit module with aFIND op code if thelibrary-name was successfullyopenedCalls the exit module with aGET op code. Verifies that thesame record was passed.Calls the exit module with aCL<strong>OS</strong>E op code when theend-of-data is presentedPrepares the specified library-name <strong>for</strong> processing. Passesthe status of the OPEN request to the compiler.Establishes positioning at the requested text-name (orbasis-name) in the specified library-name; this placebecomes the active copybook. Passes an appropriatereturn code to the compiler when positioning is complete.Reestablishes positioning at the previous active copybook.Passes an appropriate return code to the compiler whenpositioning is complete.Passes the compiler the same record as was passedpreviously from this copybook. After verification, passeseither the length and address of the record to be copiedfrom the active copybook or the end-of-data indicator.Releases any resources that are related to its inputThe following table shows how the processing of LIBEXIT changes when thecompiler encounters a valid nested COPY statement.|Table 107. LIBEXIT processing with nested COPY statementsAction by compilerAction by exit moduleIf the requested library-namefrom the nested COPY statementwas not previously opened,calls the exit module with anOPEN op codeCalls the exit module with aFIND op code <strong>for</strong> therequested new text-nameCalls the exit module with aGET op codePushes its control in<strong>for</strong>mation about the active copybookonto a stack. Completes the requested action (OPEN). Thenewly requested text-name (or basis-name) becomes theactive copybook.Pushes its control in<strong>for</strong>mation about the active copybookonto a stack. Completes the requested action (FIND). Thenewly requested text-name (or basis-name) becomes theactive copybook.Passes the compiler either the length and address of therecord to be copied from the active copybook or theend-of-data indicator. At end-of-data, pops its controlin<strong>for</strong>mation from the stack.724 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


LIBEXIT parameters|||||||||||||||The compiler uses 10 parameters, passed by reference, to communicate with theexit module. The return code, data length, and data parameters are set by the exitmodule <strong>for</strong> return to the compiler; the other items are passed from the compiler tothe exit module.Table 108. LIBEXIT parametersParameternumber Parameter item Description of item1 User-exit type Halfword that identifies which user exit is to per<strong>for</strong>mthe operation.2=LIBEXIT2 Operation code Halfword that indicates the type of operation:v 0=OPENv 1=CL<strong>OS</strong>Ev 2=GETv 4=FIND3 Return code Fullword, set by the exit module, that indicates thesuccess of the requested operation:v 0=Operation was successfulv 4=End-of-datav 12=Operation failed4 User-exit work area Six-fullword work area provided by the compiler <strong>for</strong>use by the user-exit module.Second word: <strong>for</strong> use by LIBEXIT5 Data length Fullword, set by the exit module, that specifies thelength of the record being returned by the GEToperation (must be 80)6 Data or str2 Fullword, set by the exit module, that contains theaddress of the record in a user-owned buffer, <strong>for</strong> theGET operation.str2 applies only to OPEN. The first halfword (on ahalfword boundary) contains the length of the string,followed by the string.7 System library-name Eight-character area that contains the library-name fromthe COPY statement. Processing and conversion rules<strong>for</strong> a program-name are applied. Padded with blanksif required. Applies to OPEN, CL<strong>OS</strong>E, and FIND.8 System text-name Eight-character area that contains the text-name fromthe COPY statement (basis-name from BASIS statement).Processing and conversion rules <strong>for</strong> a program-name areapplied. Padded with blanks if required. Applies onlyto FIND.9 Library-name Thirty-character area that contains the full library-namefrom the COPY statement. Padded with blanks ifrequired, and used as is (not folded to uppercase).Applies to OPEN, CL<strong>OS</strong>E, and FIND.Appendix E. EXIT compiler option 725


|||Table 108. LIBEXIT parameters (continued)Parameternumber Parameter item Description of item10 Text-name Thirty-character area that contains the full text-namefrom the COPY statement. Padded with blanks ifrequired, and used as is (not folded to uppercase).Applies only to FIND.RELATED TASKS“Using the user-exit work area” on page 721“Calling from exit modules” on page 721“Using the EXIT compiler option with CICS and SQL statements” on page 734RELATED REFERENCES“LIB” on page 327Processing of PRTEXITThe PRTEXIT exit module is used in place of the SYSPRINT data set.|Table 109. PRTEXIT processingAction by compilerLoads the exit module (mod3) duringinitializationCalls the exit module with an OPENoperation code (op code)Calls the exit modules with a PUT op codewhen a line is to be printed, supplying theaddress and length of the record that is to beprintedCalls the exit module with a CL<strong>OS</strong>E op codewhen the end-of-data is presentedAction by exit modulePrepares its output destination <strong>for</strong>processing. Passes the status of the OPENrequest to the compiler.Passes the status of the PUT request to thecompiler by a return code. The first byte ofthe record to be printed contains an ANSIprinter control character.Releases any resources that are related to itsoutput destinationPRTEXIT parameters|||||The compiler uses 10 parameters, passed by reference, to communicate with theexit module. The return code, data length, and data buffer parameters are set bythe exit module <strong>for</strong> return to the compiler; the other items are passed from thecompiler to the exit module.Table 110. PRTEXIT parametersParameternumber Parameter item Description of item1 User-exit type Halfword that identifies which user exit is to per<strong>for</strong>mthe operation.3=PRTEXIT726 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||||||||||||Table 110. PRTEXIT parameters (continued)Parameternumber Parameter item Description of item2 Operation code Halfword that indicates the type of operation:v 0=OPENv 1=CL<strong>OS</strong>Ev 3=PUT3 Return code Fullword, set by the exit module, that indicates thesuccess of the requested operation:v 0=Operation was successfulv 12=Operation failed4 User-exit work area Six-fullword work area provided by the compiler <strong>for</strong>use by the user-exit module.Third word: <strong>for</strong> use by PRTEXIT5 Data length Fullword that specifies the length of the record beingsupplied by the PUT operation (the compiler sets thisvalue to 133)6 Data buffer or str3 Fullword that contains the address of the data bufferwhere the compiler has placed the record to beprinted by the PUT operation.str3 applies only to OPEN. The first halfword (on ahalfword boundary) contains the length of the string,followed by the string.7 Not used (Used only by LIBEXIT and MSGEXIT)8 Not used (Used only by LIBEXIT)9 Not used (Used only by LIBEXIT)10 Not used (Used only by LIBEXIT)Processing of ADEXITRELATED TASKS“Using the user-exit work area” on page 721“Calling from exit modules” on page 721“Using the EXIT compiler option with CICS and SQL statements” on page 734||The ADEXIT module is called <strong>for</strong> each SYSADATA record immediately after therecord has been written out to the file.To use an ADEXIT module, you must compile using the ADATA option to produceSYSADATA output, and code the SYSADATA DD statement.|Table 111. ADEXIT processingAction by compilerLoads the exit module (mod4) duringinitializationCalls the exit module with an OPENoperation code (op code)Action by exit modulePrepares its output destination <strong>for</strong>processing. Passes the status of the OPENrequest to the compiler.Appendix E. EXIT compiler option 727


|Table 111. ADEXIT processing (continued)Action by compilerAction by exit moduleCalls the exit module with a PUT op code Passes the status of the PUT request to thewhen the compiler has written a SYSADATA compiler by a return coderecord, supplying the address and length ofthe SYSADATA recordCalls the exit module with a CL<strong>OS</strong>E op codewhen the end-of-data is presentedReleases any resourcesADEXIT parameters||||||||||||||||The compiler uses 10 parameters, passed by reference, to communicate with theexit module. The return code, data length, and data buffer parameters are set bythe exit module <strong>for</strong> return to the compiler; the other items are passed from thecompiler to the exit module.Table 112. ADEXIT parametersParameternumber Parameter item Description of item1 User-exit type Halfword that identifies which user exit is to per<strong>for</strong>mthe operation.4=ADEXIT2 Operation code Halfword that indicates the type of operation:v 0=OPENv 1=CL<strong>OS</strong>Ev 3=PUT3 Return code Fullword, set by the exit module, that indicates thesuccess of the requested operation:v 0=Operation was successfulv 12=Operation failed4 User-exit work area Six-fullword work area provided by the compiler <strong>for</strong>use by the user-exit module.Fourth word: <strong>for</strong> use by ADEXIT5 Data length Fullword that specifies the length of the record beingsupplied by the PUT operation6 Data buffer or str4 Fullword that contains the address of the data bufferwhere the compiler has placed the record to beprinted by the PUT operation.str4 applies only to OPEN. The first halfword (on ahalfword boundary) contains the length of the string,followed by the string.7 Not used (Used only by LIBEXIT and MSGEXIT)8 Not used (Used only by LIBEXIT)9 Not used (Used only by LIBEXIT)10 Not used (Used only by LIBEXIT)RELATED TASKS“Using the user-exit work area” on page 721728 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


“Calling from exit modules” on page 721“Using the EXIT compiler option with CICS and SQL statements” on page 734RELATED REFERENCES“ADATA” on page 305||||||||||||||||||||||||||||||||||||||Processing of MSGEXITThe MSGEXIT module is used to customize compiler diagnostic messages and FIPSmessages. The module can customize a message either by changing its severity orsuppressing it.If the MSGEXIT module assigns a severity to a FIPS message, the message isconverted into a diagnostic message. (The message is shown in the summary ofdiagnostic messages in the listing.)A MSGEXIT summary at the end of the compiler listing shows how manymessages were changed in severity and how many messages were suppressed.Table 113. MSGEXIT processingAction by compilerAction by exit moduleLoads the exit module (mod5)during initializationCalls the exit module with anOPEN operation code (op code)Calls the exit module with a One of the following actions:MSGSEV operation code (op code) vwhen the compiler is about to issuea diagnostic message or FIPSvmessageCalls the exit module with aCL<strong>OS</strong>E op codeDeletes the exit module (mod5)during compiler terminationMSGEXIT parametersOptionally processes str5 and passes the status of theOPEN request to the compilervIndicates no customization of the message (bysetting return code to 0)Specifies a new severity <strong>for</strong> (or suppression of) themessage, and sets return code to 4Indicates that the operation failed (by settingreturn code to 12)Optionally frees storage and passes the status of theCL<strong>OS</strong>E request to the compilerThe compiler uses 10 parameters, passed by reference, to communicate with theexit module. The return code and user-requested severity parameters are set by theexit module <strong>for</strong> return to the compiler; the other items are passed from thecompiler to the exit module.Table 114. MSGEXIT parametersParameternumber Parameter item Description of item1 User-exit type Halfword that identifies which user exit is to per<strong>for</strong>mthe operation.6=MSGEXITAppendix E. EXIT compiler option 729


|||||||||||||||||||||||||||||||||||||||||||||Table 114. MSGEXIT parameters (continued)Parameternumber Parameter item Description of item2 Operation code Halfword that indicates the type of operation:v 0=OPENv 1=CL<strong>OS</strong>Ev 5=MSGSEV: customize message severity3 Return code Fullword, set by the exit module, that indicates thesuccess of the requested operation.For op code MSGSEV:v 0=Message not customizedv 4=Message found and customizedv 12=Operation failed4 User-exit work area Six-fullword work area provided by the compiler <strong>for</strong>use by the user-exit module.Sixth word: <strong>for</strong> use by MSGEXIT5 Not used (Used by the other exits)6 Message exit data Three-halfword area (on a halfword boundary).v First halfword: the message number of the messageto be customizedv Second halfword: <strong>for</strong> a diagnostic message, thedefault severity; <strong>for</strong> a FIPS message, the FIPScategory as a numeric codev Third halfword: the user-requested severity <strong>for</strong> themessage (-1 to indicate suppression)7 str5 First halfword (on a halfword boundary): the length ofthe string, followed by the string8 Not used (Used only by LIBEXIT)9 Not used (Used only by LIBEXIT)10 Not used (Used only by LIBEXIT)“Example: MSGEXIT user exit” on page 735RELATED TASKS“Using the user-exit work area” on page 721“Calling from exit modules” on page 721“Customizing compiler-message severities”“Using the EXIT compiler option with CICS and SQL statements” on page 734Customizing compiler-message severitiesTo change the severities of compiler messages or suppress compiler messages(including FIPS messages), do the steps described below.1. Code and compile a <strong>COBOL</strong> program named ERRMSG. The program needs onlya PROGRAM-ID paragraph, as described in the related task.2. Review the ERRMSG listing, which contains a complete list of compiler messageswith their message numbers, severities, and message text.3. Decide which messages you want to customize.730 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


||||||||||||||||||||||||||||||||||||||||||||||To understand the customizations that are possible, see the related referenceabout customizable compiler-message severities.4. Code a MSGEXIT module to implement the customizations:a. Verify that the operation-code parameter indicates message-severitycustomization.b. Check the two input values in the message-exit-data parameter: the messagenumber; and the default severity <strong>for</strong> a diagnostic message or the FIPScategory <strong>for</strong> a FIPS message.The FIPS category is expressed as numeric code. For details, see the relatedreference about customizable compiler-message severities.c. For a message that you want to customize, set the user-requested severity inthe message-exit-data parameter to indicate either:v A new message severity, by coding severity 0, 4, 8, or 12v Message suppression, by coding severity -1d. Set the return code to one of the following values:v 0, to indicate that the message was not customizedv 4, to indicate that the message was found and customizedv 12, to indicate that the operation failed and that compilation should beterminated5. Compile and link your MSGEXIT module.6. Add the data set that contains your MSGEXIT module to the compilerconcatenation by using a STEPLIB or JOBLIB DD statement.7. Recompile program ERRMSG, but use compiler option EXIT(MSGEXIT(msgmod)),where msgmod is the name of your MSGEXIT module.8. Review the listing and check <strong>for</strong>:v Updated message severitiesv Suppressed messages (indicated by XX in place of the severity)vUnsupported severity changes or unsupported message suppression(indicated by a severity-U diagnostic message, and compiler termination withreturn code 16)RELATED TASKS“Generating a list of compiler messages” on page 279RELATED REFERENCES“Severity codes <strong>for</strong> compiler diagnostic messages” on page 281“Customizable compiler-message severities”“Effect of message customization on compilation return code” on page 732“Error handling <strong>for</strong> exit modules” on page 733Customizable compiler-message severitiesTo customize compiler-message severities, you need to understand the possibleseverities of compiler diagnostic messages, the levels or categories of FIPSmessages, and the permitted customizations of message severities.The possible severity codes <strong>for</strong> compiler diagnostic messages are described in therelated reference about severity codes.The eight categories of FIPS (FLAGSTD) messages are shown in the following table.The category of any given FIPS message is passed as a numeric code to theMSGEXIT module. Those numeric codes are shown in the second column.Appendix E. EXIT compiler option 731


||||||||||||||||||||||||||||||||||||||||||Table 115. FIPS (FLAGSTD) message categoriesFIPS level or category Numeric code DescriptionD 81 Debug module level 1E 82 Extension (IBM)H 83 High levelI 84 Intermediate levelN 85 Segmentation module level 1O 86 Obsolete elementsQ 87 High-level and obsolete elementsS 88 Segmentation module level 2FIPS messages have an implied severity of zero (severity I).Permitted message-severity customizations:You can change the severity of a compiler message in the following ways:v Severity-I and severity-W compiler diagnostic messages, and FIPS messages, canbe changed to have any severity from I through S.Assigning a severity to a FIPS message converts the FIPS message to adiagnostic message of the assigned severity.As examples, you can:– Lower an optimizer warning to severity I.– Disallow REDEFINING a smaller item with a larger item by raising the severityof message 1154.– Prevent inclusion of TEST in<strong>for</strong>mation in the object file, if the SYSDEBUG filecannot be opened, by raising the severity of message 4073.– Disallow complex OCCURS DEPENDING ON by changing FIPS message 8235 froma category-E FIPS message to a severity-S compiler diagnostic message.v Severity-E messages can be raised to severity S, but not lowered to severity I orW, because an error condition has occurred in the program.v Severity-S and severity-U messages cannot be changed to have a differentseverity.You can request suppression of compiler messages as follows:v I, W, and FIPS messages can be suppressed.v E and S messages cannot be suppressed.RELATED REFERENCES“Severity codes <strong>for</strong> compiler diagnostic messages” on page 281“FLAGSTD” on page 323“Effect of message customization on compilation return code”Effect of message customization on compilation return codeIf you use a MSGEXIT module, the final return code from the compilation of aprogram could be affected as described below.If you change the severity of a message, the return code from the compilationmight also be changed. For example, if a compilation produces one diagnostic732 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||||||||||||||||||||||||||||||||||||||||message, and it is a severity-E message, the compilation return code wouldnormally be 8. But if the MSGEXIT module changes the severity of that message toseverity S, then the return code from compilation would be 12.If you suppress a message, the return code from the compilation is no longeraffected by the severity of that message. For example, if a compilation producesone diagnostic message, and it is a severity-W message, the compilation returncode would normally be 4. But if the MSGEXIT module suppresses that message,then the return code from compilation would be 0.RELATED TASKS“Customizing compiler-message severities” on page 730RELATED REFERENCES“Severity codes <strong>for</strong> compiler diagnostic messages” on page 281Error handling <strong>for</strong> exit modulesThe conditions described below can occur during processing of the user exits.Exit load failure:Message IGYSI5207-U is written to the operator if a LOAD request <strong>for</strong> any of theuser exits fails:An error occurred while attempting to load user exit exit-name.Exit open failure:Message IGYSI5208-U is written to the operator if an OPEN request <strong>for</strong> any of theuser exits fails:An error occurred while attempting to open user exit exit-name.SYSPRINT PUT failure:v Message IGYSI5203-U is written to the listing:vA PUT request to the PRTEXIT user exit failed with return code nn.Message IGYSI5217-U is written to the operator:An error occurred in PRTEXIT user exit exit-name. Compiler terminated.SYSIN GET failures:The following messages might be written to the listing:v IGYSI5204-U:vvThe record address was not set by the exit-name user exit.IGYSI5205-U:A GET request from the INEXIT user exit failed with return code nn.IGYSI5206-U:The record length was not set by the exit-name user exit.ADEXIT PUT failure:v Message IGYSI5225-U is written to the operator:vAn error occurred in ADEXIT user exit exit-name. Compiler terminated.Message IGYSI5226-U is written to the listing:A PUT request to the ADEXIT user exit failed with return code nn.Appendix E. EXIT compiler option 733


||||||||||||||MSGEXIT failures:Customization failure: Message IGYPP5293-U is written to the listing if anunsupported severity change or unsupported message suppression is attempted:MSGEXIT user exit exit-name specified a message severity customization that isnot supported. The message number, default severity, and user-specified severitywere: mm, ds, us. Change MSGEXIT user exit exit-name to correct this error.General failure: Message IGYPP5064-U is written to the listing if the MSGEXITmodule sets the return code to a nonzero value other than 4:A call to the MSGEXIT user exit routine exit-name failed with return code nn.In the MSGEXIT messages, the two characters PP indicate the phase of thecompiler that issued the message that resulted in a call to the MSGEXIT module.RELATED TASKS“Customizing compiler-message severities” on page 730Using the EXIT compiler option with CICS and SQL statementsWhen you compile using suboptions of the EXIT compiler option, and yourprogram contains EXEC CICS or EXEC SQL statements, the actions that you can takein the exit modules depend on whether you use the separate CICS translator andDB2 precompiler, or the integrated CICS translator and DB2 coprocessor.The following table shows which actions you can take in the exit modulesdepending on whether you use the integrated or separate translators.Table 116. Actions possible in exit modules <strong>for</strong> CICS and SQL statementsCompilewithsuboptionTranslated withintegrated or separateCICS and DB2translators? Possible actions CommentsINEXIT Integrated Can process EXEC CICS and EXEC SQLstatements in the INEXIT moduleSeparateCan process the <strong>COBOL</strong> statementsthat are generated <strong>for</strong> the EXECstatements in the INEXIT moduleLIBEXIT Integrated Can process in the LIBEXIT modulethe statements that are brought in bythe EXEC SQL INCLUDE statements. Canprocess EXEC CICS source statementsin the LIBEXIT module.SeparateCan process the <strong>COBOL</strong> statementsthat are generated <strong>for</strong> the EXEC CICSstatements in the LIBEXIT modulePRTEXIT Integrated Can process the EXEC CICS and EXECSQL source statements from theSOURCE listing in the PRTEXIT moduleSeparateCan process the <strong>COBOL</strong> SOURCElisting statements that are generated<strong>for</strong> the EXEC statements in thePRTEXIT moduleThe INEXIT module does not getcontrol of the <strong>COBOL</strong> statements thatare generated <strong>for</strong> the EXEC statements.You can change the generatedstatements in the INEXIT module, butdoing so is not supported by IBM.EXEC SQL INCLUDE statements areprocessed like <strong>COBOL</strong> COPYstatements.You can process the input statementsthat are brought in by the EXEC SQLINCLUDE statements only by using theINEXIT suboption.The PRTEXIT module does not haveaccess to the <strong>COBOL</strong> statements thatare generated.734 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


||||||Table 116. Actions possible in exit modules <strong>for</strong> CICS and SQL statements (continued)CompilewithsuboptionTranslated withintegrated or separateCICS and DB2translators? Possible actions CommentsADEXIT Integrated Can process the EXEC CICS and EXECSQL source statements in the ADEXITmoduleSeparateCan process the <strong>COBOL</strong> SYSADATAstatements that are generated <strong>for</strong> theEXEC statements in the ADEXITmoduleMSGEXIT Integrated Can process CICS and DB2 messagesin the MSGEXIT moduleSeparateCannot process CICS and DB2messages in the MSGEXIT moduleThe ADEXIT module does not haveaccess to the <strong>COBOL</strong> statements thatare generated.Messages from CICS are shown in theseparate CICS translator listing;messages from DB2 are shown in theDB2 precompiler listing.RELATED CONCEPTS“Integrated CICS translator” on page 413“DB2 coprocessor” on page 419RELATED TASKS“Compiling with the CICS option” on page 411“Compiling with the SQL option” on page 423RELATED REFERENCES“Processing of INEXIT” on page 722“Processing of LIBEXIT” on page 723“Processing of PRTEXIT” on page 726“Processing of ADEXIT” on page 727“Processing of MSGEXIT” on page 729||||||||||||||||||||Example: MSGEXIT user exitThe following example shows a MSGEXIT user-exit module that changes messageseverities and suppresses messages.For helpful tips about using a message-exit module, see the comments within thecode.****************************************************************** IGYMSGXT - Sample <strong>COBOL</strong> program <strong>for</strong> MSGEXIT ******************************************************************* Function: This is a SAMPLE user exit <strong>for</strong> the MSGEXIT ** suboption of the EXIT compiler option. This exit ** can be used to customize the severity of or ** suppress compiler diagnostic messages and FIPS ** messages. This example program includes several ** sample customizations to show how customizations ** are done. If you do not want the sample ** customizations then either delete the unwanted ** lines of code or comment them out with a comment ** indicator in column 7 (*). ** **---------------------------------------------------------------*Appendix E. EXIT compiler option 735


|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||* ** USAGE NOTE: To use this user exit program, make the ** link-edited load module available to your ** compiles that will use the MSGEXIT suboption of ** the EXIT compiler option. Also, the name should ** be changed, since IBM recommends that you avoid ** having programs with names that start with IGY. ** Sample steps to take: ** 1) Make your customizations ** 2) Change program name (E.G. MSGEXT) ** 3) Compile and link into a dataset ** 4) Include that dataset in your compile ** JCL concatenation <strong>for</strong> the compile step. ** If you link into USER.<strong>COBOL</strong>LIB: ** ** //<strong>COBOL</strong>.STEPLIB DD DSNAME=SYS1.SIGYCOMP,DISP=SHR ** // DD DSNAME=USER.<strong>COBOL</strong>LIB,DISP=SHR ** ** LINKAGE NOTE: To improve compile per<strong>for</strong>mance, you can link ** this user exit program with the CEEUOPT ** CSECT, with the RTEREUS option specified: ** ** CEEUOPT CSECT ** CEEUOPT AMODE ANY ** CEEUOPT RMODE ANY ** CEEXOPT RTEREUS=(ON) ** END ** ** See the Language Environment <strong>for</strong> z/<strong>OS</strong> ** <strong>Programming</strong> <strong>Guide</strong> and <strong>Programming</strong> Reference ** <strong>for</strong> more in<strong>for</strong>mation. ** There is a sample job to assemble CEEUOPT in ** the sample library, member CEEWUOPT, ** described in the Language Environment ** Customization guide. ** ** Include the following JCL in your link-edit of IGYMSGXT: ** ** //LKED.SYSIN DD * ** INCLUDE DDNAME(CEEUOPT) ** /* ** ******************************************************************Id Division.Program-Id. IGYMSGXT.Data Division.Working-Storage Section.****************************************************************** ** Local variables. ** ******************************************************************77 EXIT-TYPEN PIC 9(4).77 EXIT-DEFAULT-SEV-FIPS PIC X.****************************************************************** ** Definition of the User-Exit Parameter List, which is ** passed from the <strong>COBOL</strong> compiler to the user-exit module. ** ******************************************************************Linkage Section.01 EXIT-TYPE PIC 9(4) COMP.736 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||01 EXIT-OPERATION PIC 9(4) COMP.01 EXIT-RETURNCODE PIC 9(9) COMP.01 EXIT-WORK-AREA.02 EXIT-WORK-AREA-PTR OCCURS 6 POINTER.01 EXIT-DUMMY POINTER.01 EXIT-MESSAGE-PARMS.02 EXIT-MESSAGE-NUM PIC 9(4) COMP.02 EXIT-DEFAULT-SEV PIC 9(4) COMP.02 EXIT-USER-SEV PIC S9(4) COMP.01 EXIT-STRING.02 EXIT-STR-LEN PIC 9(4) COMP.02 EXIT-STR-TXT PIC X(64).*********************************************************************************************************************************** ** Begin PROCEDURE DIVISION ** ** Check parameters and per<strong>for</strong>m the operation requested. ** ***********************************************************************************************************************************Procedure Division Using EXIT-TYPE EXIT-OPERATIONEXIT-RETURNCODE EXIT-WORK-AREAEXIT-DUMMY EXIT-MESSAGE-PARMSEXIT-STRING EXIT-DUMMYEXIT-DUMMY EXIT-DUMMY.Compute EXIT-RETURNCODE = 0Evaluate TRUE****************************************************************** Handle a bad invocation of this exit by the compiler. ** This could happen if this routine was used <strong>for</strong> one of the ** other EXITs, such as INEXIT, PRTEXIT or LIBEXIT. ******************************************************************When EXIT-TYPE Not = 6Move EXIT-TYPE to EXIT-TYPENDisplay '**** Invalid exit routine identifier'Display '**** EXIT TYPE = ' EXIT-TYPECompute EXIT-RETURNCODE = 16****************************************************************** Handle the OPEN call to this exit by the compiler ** Display the exit string (str5 in syntax diagram) from ** the EXIT(MSGEXIT('str5',mod5)) option specification. ******************************************************************When EXIT-OPERATION = 0* Display 'Opening MSGEXIT'* If EXIT-STR-LEN Not Zero Then* Display ' str5 len = ' EXIT-STR-LEN* Display ' str5 = ' EXIT-STR-TXT(1:EXIT-STR-LEN)* End-IfContinue****************************************************************** Handle the CL<strong>OS</strong>E call to this exit by the compiler ** Do STOP RUN to clean up the RTEREUS environment ******************************************************************When EXIT-OPERATION = 1* Display 'Closing MSGEXIT'Stop Run****************************************************************** Handle the customize message severity call to this exit *Appendix E. EXIT compiler option 737


|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||* Display in<strong>for</strong>mation about every customized severity. ******************************************************************When EXIT-OPERATION = 5* Display 'MSGEXIT called with MSGSEV'If EXIT-MESSAGE-NUM < 8000 ThenPer<strong>for</strong>m Error-Messages-SeverityElsePer<strong>for</strong>m FIPS-Messages-SeverityEnd-If* If EXIT-RETURNCODE = 4 Then* Display '>>>> Customizing message ' EXIT=MESSAGE-NUM* ' with new severity ' EXIT-USER-SEV '


|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||* the warnings you get and then change them to I-level when* the analysis is complete.*****************************************************************When(3188) When(3189)Compute EXIT-USER-SEV = 12****************************************************************** Change severity of message 4073(W) to 12 ('S')* Prevent inclusion of TEST in<strong>for</strong>mation in object* if SYSDEBUG file cannot be opened, raise severity* of message 4073(W) to 12 ('S')* This is IBM Req # MR0716082134*****************************************************************When(4073)Compute EXIT-USER-SEV = 12****************************************************************** Message severity Not customized*****************************************************************When OtherCompute EXIT-RETURNCODE = 0End-Evaluate.****************************************************************** FIPS MESSAGE PROCESSOR ******************************************************************Fips-Messages-Severity.* Assume message severity will be customized...Compute EXIT-RETURNCODE = 4* Convert numeric FIPS(FLAGSTD) 'category' to character* See the <strong>Programming</strong> <strong>Guide</strong> <strong>for</strong> decription of FIPS categoryEVALUATE EXIT-DEFAULT-SEVWhen 81MOVE 'D' To EXIT-DEFAULT-SEV-FIPSWhen 82MOVE 'E' To EXIT-DEFAULT-SEV-FIPSWhen 83MOVE 'H' To EXIT-DEFAULT-SEV-FIPSWhen 84MOVE 'I' To EXIT-DEFAULT-SEV-FIPSWhen 85MOVE 'N' To EXIT-DEFAULT-SEV-FIPSWhen 86MOVE 'O' To EXIT-DEFAULT-SEV-FIPSWhen 87MOVE 'Q' To EXIT-DEFAULT-SEV-FIPSWhen 88MOVE 'S' To EXIT-DEFAULT-SEV-FIPSWhen OtherContinueEnd-Evaluate****************************************************************** Example of using FIPS category to <strong>for</strong>ce coding* restrictions. This is not a recommendation!* Change severity of all OBSOLETE item FIPS* messages to 'S'****************************************************************** If EXIT-DEFAULT-SEV-FIPS = 'O' Then* Display '>>>> Default customizing FIPS category '* EXIT-DEFAULT-SEV-FIPS ' msg ' EXIT-MESSAGE-NUM '


|||||||||||||||||||||||||||||||||||||||||||||Evaluate EXIT-MESSAGE-NUM****************************************************************** Change severity of message 8062(O) to 8 ('E')* 8062 = GO TO without proc name*****************************************************************When(8062)Compute EXIT-USER-SEV = 8****************************************************************** Change severity of message 8193(E) to 0('I')* 8193 = GOBACK*****************************************************************When(8193)Compute EXIT-USER-SEV = 0****************************************************************** Change severity of message 8235(E) to 8 (Error)* to disallow Complex Occurs Depending On* 8235 = Complex Occurs Depending On*****************************************************************When(8235)Compute EXIT-USER-SEV = 08****************************************************************** Change severity of message 8270(O) to -1 (Suppress)* 8270 = SERVICE LABEL*****************************************************************When(8270)Compute EXIT-USER-SEV = -1****************************************************************** Message severity Not customized*****************************************************************When Other* For the default set 'O' to 'S' case...* If EXIT-USER-SEV = 12 Then* Compute EXIT-RETURNCODE = 4* ElseCompute EXIT-RETURNCODE = 0* End-IfEnd-Evaluate.END PROGRAM IGYMSGXT.|740 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix F. JNI.cpyThis listing shows the copybook JNI.cpy, which you can use to access the JavaNative Interface (JNI) services from your <strong>COBOL</strong> programs.JNI.cpy contains sample <strong>COBOL</strong> data definitions that correspond to the Java JNItypes, and contains JNINativeInterface, the JNI environment structure that containsfunction pointers <strong>for</strong> accessing the JNI callable services.JNI.cpy is in the z/<strong>OS</strong> UNIX file system in the include subdirectory of the <strong>COBOL</strong>install directory (typically /usr/lpp/cobol/include). JNI.cpy is analogous to theheader file jni.h that C programmers use to access the JNI.****************************************************************** <strong>COBOL</strong> declarations <strong>for</strong> Java native method interoperation ** ** To use the Java Native Interface callable services from a ** <strong>COBOL</strong> program: ** 1) Use a COPY statement to include this file into the ** the Linkage Section of the program, e.g. ** Linkage Section. ** Copy JNI ** 2) Code the following statements at the beginning of the ** Procedure Division: ** Set address of JNIEnv to JNIEnvPtr ** Set address of JNINativeInterface to JNIEnv ******************************************************************** Sample JNI type definitions in <strong>COBOL</strong>**01 jboolean1 pic X.* 88 jboolean1-true value X'01' through X'FF'.* 88 jboolean1-false value X'00'.**01 jbyte1 pic X.**01 jchar1 pic N usage national.**01 jshort1 pic s9(4) comp-5.*01 jint1 pic s9(9) comp-5.*01 jlong1 pic s9(18) comp-5.**01 jfloat1 comp-1.*01 jdouble1 comp-2.**01 jobject1 object reference.*01 jclass1 object reference.*01 jstring1 object reference jstring.*01 jarray1 object reference jarray.**01 jbooleanArray1 object reference jbooleanArray.*01 jbyteArray1 object reference jbyteArray.*01 jcharArray1 object reference jcharArray.*01 jshortArray1 object reference jshortArray.*01 jintArray1 object reference jintArray.*01 jlongArray1 object reference jlongArray.*01 floatArray1 object reference floatArray.*01 jdoubleArray1 object reference jdoubleArray.*01 jobjectArray1 object reference jobjectArray.* Possible return values <strong>for</strong> JNI functions.© Copyright IBM Corp. 1991, 2009 741


01 JNI-RC pic S9(9) comp-5.* success88 JNI-OK value 0.* unknown error88 JNI-ERR value -1.* thread detached from the VM88 JNI-EDETACHED value -2.* JNI version error88 JNI-EVERSION value -3.* not enough memory88 JNI-ENOMEM value -4.* VM already created88 JNI-EEXIST value -5.* invalid arguments88 JNI-EINVAL value -6.* Used in ReleaseScalarArrayElements01 releaseMode pic s9(9) comp-5.88 JNI-COMMIT value 1.88 JNI-ABORT value 2.01 JNIenv pointer.* JNI Native Method Interface - environment structure.01 JNINativeInterface.02 pointer.02 pointer.02 pointer.02 pointer.02 GetVersion function-pointer.02 DefineClass function-pointer.02 FindClass function-pointer.02 FromReflectedMethod function-pointer.02 FromReflectedField function-pointer.02 ToReflectedMethod function-pointer.02 GetSuperclass function-pointer.02 IsAssignableFrom function-pointer.02 ToReflectedField function-pointer.02 Throw function-pointer.02 ThrowNew function-pointer.02 ExceptionOccurred function-pointer.02 ExceptionDescribe function-pointer.02 ExceptionClear function-pointer.02 FatalError function-pointer.02 PushLocalFrame function-pointer.02 PopLocalFrame function-pointer.02 NewGlobalRef function-pointer.02 DeleteGlobalRef function-pointer.02 DeleteLocalRef function-pointer.02 IsSameObject function-pointer.02 NewLocalRef function-pointer.02 EnsureLocalCapacity function-pointer.02 AllocObject function-pointer.02 NewObject function-pointer.02 NewObjectV function-pointer.02 NewObjectA function-pointer.02 GetObjectClass function-pointer.02 IsInstanceOf function-pointer.02 GetMethodID function-pointer.02 CallObjectMethod function-pointer.02 CallObjectMethodV function-pointer.02 CallObjectMethodA function-pointer.02 CallBooleanMethod function-pointer.02 CallBooleanMethodV function-pointer.02 CallBooleanMethodA function-pointer.02 CallByteMethod function-pointer.02 CallByteMethodV function-pointer.742 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


02 CallByteMethodA function-pointer.02 CallCharMethod function-pointer.02 CallCharMethodV function-pointer.02 CallCharMethodA function-pointer.02 CallShortMethod function-pointer.02 CallShortMethodV function-pointer.02 CallShortMethodA function-pointer.02 CallIntMethod function-pointer.02 CallIntMethodV function-pointer.02 CallIntMethodA function-pointer.02 CallLongMethod function-pointer.02 CallLongMethodV function-pointer.02 CallLongMethodA function-pointer.02 CallFloatMethod function-pointer.02 CallFloatMethodV function-pointer.02 CallFloatMethodA function-pointer.02 CallDoubleMethod function-pointer.02 CallDoubleMethodV function-pointer.02 CallDoubleMethodA function-pointer.02 CallVoidMethod function-pointer.02 CallVoidMethodV function-pointer.02 CallVoidMethodA function-pointer.02 CallNonvirtualObjectMethod function-pointer.02 CallNonvirtualObjectMethodV function-pointer.02 CallNonvirtualObjectMethodA function-pointer.02 CallNonvirtualBooleanMethod function-pointer.02 CallNonvirtualBooleanMethodV function-pointer.02 CallNonvirtualBooleanMethodA function-pointer.02 CallNonvirtualByteMethod function-pointer.02 CallNonvirtualByteMethodV function-pointer.02 CallNonvirtualByteMethodA function-pointer.02 CallNonvirtualCharMethod function-pointer.02 CallNonvirtualCharMethodV function-pointer.02 CallNonvirtualCharMethodA function-pointer.02 CallNonvirtualShortMethod function-pointer.02 CallNonvirtualShortMethodV function-pointer.02 CallNonvirtualShortMethodA function-pointer.02 CallNonvirtualIntMethod function-pointer.02 CallNonvirtualIntMethodV function-pointer.02 CallNonvirtualIntMethodA function-pointer.02 CallNonvirtualLongMethod function-pointer.02 CallNonvirtualLongMethodV function-pointer.02 CallNonvirtualLongMethodA function-pointer.02 CallNonvirtualFloatMethod function-pointer.02 CallNonvirtualFloatMethodV function-pointer.02 CallNonvirtualFloatMethodA function-pointer.02 CallNonvirtualDoubleMethod function-pointer.02 CallNonvirtualDoubleMethodV function-pointer.02 CallNonvirtualDoubleMethodA function-pointer.02 CallNonvirtualVoidMethod function-pointer.02 CallNonvirtualVoidMethodV function-pointer.02 CallNonvirtualVoidMethodA function-pointer.02 GetFieldID function-pointer.02 GetObjectField function-pointer.02 GetBooleanField function-pointer.02 GetByteField function-pointer.02 GetCharField function-pointer.02 GetShortField function-pointer.02 GetIntField function-pointer.02 GetLongField function-pointer.02 GetFloatField function-pointer.02 GetDoubleField function-pointer.02 SetObjectField function-pointer.02 SetBooleanField function-pointer.02 SetByteField function-pointer.02 SetCharField function-pointer.02 SetShortField function-pointer.Appendix F. JNI.cpy 743


744 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>02 SetIntField function-pointer.02 SetLongField function-pointer.02 SetFloatField function-pointer.02 SetDoubleField function-pointer.02 GetStaticMethodID function-pointer.02 CallStaticObjectMethod function-pointer.02 CallStaticObjectMethodV function-pointer.02 CallStaticObjectMethodA function-pointer.02 CallStaticBooleanMethod function-pointer.02 CallStaticBooleanMethodV function-pointer.02 CallStaticBooleanMethodA function-pointer.02 CallStaticByteMethod function-pointer.02 CallStaticByteMethodV function-pointer.02 CallStaticByteMethodA function-pointer.02 CallStaticCharMethod function-pointer.02 CallStaticCharMethodV function-pointer.02 CallStaticCharMethodA function-pointer.02 CallStaticShortMethod function-pointer.02 CallStaticShortMethodV function-pointer.02 CallStaticShortMethodA function-pointer.02 CallStaticIntMethod function-pointer.02 CallStaticIntMethodV function-pointer.02 CallStaticIntMethodA function-pointer.02 CallStaticLongMethod function-pointer.02 CallStaticLongMethodV function-pointer.02 CallStaticLongMethodA function-pointer.02 CallStaticFloatMethod function-pointer.02 CallStaticFloatMethodV function-pointer.02 CallStaticFloatMethodA function-pointer.02 CallStaticDoubleMethod function-pointer.02 CallStaticDoubleMethodV function-pointer.02 CallStaticDoubleMethodA function-pointer.02 CallStaticVoidMethod function-pointer.02 CallStaticVoidMethodV function-pointer.02 CallStaticVoidMethodA function-pointer.02 GetStaticFieldID function-pointer.02 GetStaticObjectField function-pointer.02 GetStaticBooleanField function-pointer.02 GetStaticByteField function-pointer.02 GetStaticCharField function-pointer.02 GetStaticShortField function-pointer.02 GetStaticIntField function-pointer.02 GetStaticLongField function-pointer.02 GetStaticFloatField function-pointer.02 GetStaticDoubleField function-pointer.02 SetStaticObjectField function-pointer.02 SetStaticBooleanField function-pointer.02 SetStaticByteField function-pointer.02 SetStaticCharField function-pointer.02 SetStaticShortField function-pointer.02 SetStaticIntField function-pointer.02 SetStaticLongField function-pointer.02 SetStaticFloatField function-pointer.02 SetStaticDoubleField function-pointer.02 NewString function-pointer.02 GetStringLength function-pointer.02 GetStringChars function-pointer.02 ReleaseStringChars function-pointer.02 NewStringUTF function-pointer.02 GetStringUTFLength function-pointer.02 GetStringUTFChars function-pointer.02 ReleaseStringUTFChars function-pointer.02 GetArrayLength function-pointer.02 NewObjectArray function-pointer.02 GetObjectArrayElement function-pointer.02 SetObjectArrayElement function-pointer.02 NewBooleanArray function-pointer.


02 NewByteArray function-pointer.02 NewCharArray function-pointer.02 NewShortArray function-pointer.02 NewIntArray function-pointer.02 NewLongArray function-pointer.02 NewFloatArray function-pointer.02 NewDoubleArray function-pointer.02 GetBooleanArrayElements function-pointer.02 GetByteArrayElements function-pointer.02 GetCharArrayElements function-pointer.02 GetShortArrayElements function-pointer.02 GetIntArrayElements function-pointer.02 GetLongArrayElements function-pointer.02 GetFloatArrayElements function-pointer.02 GetDoubleArrayElements function-pointer.02 ReleaseBooleanArrayElements function-pointer.02 ReleaseByteArrayElements function-pointer.02 ReleaseCharArrayElements function-pointer.02 ReleaseShortArrayElements function-pointer.02 ReleaseIntArrayElements function-pointer.02 ReleaseLongArrayElements function-pointer.02 ReleaseFloatArrayElements function-pointer.02 ReleaseDoubleArrayElements function-pointer.02 GetBooleanArrayRegion function-pointer.02 GetByteArrayRegion function-pointer.02 GetCharArrayRegion function-pointer.02 GetShortArrayRegion function-pointer.02 GetIntArrayRegion function-pointer.02 GetLongArrayRegion function-pointer.02 GetFloatArrayRegion function-pointer.02 GetDoubleArrayRegion function-pointer.02 SetBooleanArrayRegion function-pointer.02 SetByteArrayRegion function-pointer.02 SetCharArrayRegion function-pointer.02 SetShortArrayRegion function-pointer.02 SetIntArrayRegion function-pointer.02 SetLongArrayRegion function-pointer.02 SetFloatArrayRegion function-pointer.02 SetDoubleArrayRegion function-pointer.02 RegisterNatives function-pointer.02 UnregisterNatives function-pointer.02 MonitorEnter function-pointer.02 MonitorExit function-pointer.02 GetJavaVM function-pointer.02 GetStringRegion function-pointer.02 GetStringUTFRegion function-pointer.02 GetPrimitiveArrayCritical function-pointer.02 ReleasePrimitiveArrayCritical function-pointer.02 GetStringCritical function-pointer.02 ReleaseStringCritical function-pointer.02 NewWeakGlobalRef function-pointer.02 DeleteWeakGlobalRef function-pointer.02 ExceptionCheck function-pointer.RELATED TASKS“Compiling OO applications under z/<strong>OS</strong> UNIX” on page 291“Accessing JNI services” on page 607Appendix F. JNI.cpy 745


746 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix G. <strong>COBOL</strong> SYSADATA file contentsWhen you use the ADATA compiler option, the compiler produces a file thatcontains program data. You can use this file instead of the compiler listing toextract in<strong>for</strong>mation about the program. For example, you can extract in<strong>for</strong>mationabout the program <strong>for</strong> symbolic debugging tools or cross-reference tools.“Example: SYSADATA” on page 749RELATED REFERENCES“ADATA” on page 305“Existing compiler options that affect the SYSADATA file”“SYSADATA record types” on page 748“SYSADATA record descriptions” on page 750Existing compiler options that affect the SYSADATA fileSeveral compiler options could affect the contents of the SYSADATA file.COMPILENOCOMPILE(W|E|S) might stop compilation prematurely, resulting in the lossof specific messages.EXIT INEXIT prohibits identification of the compilation source file.LANGUAGELANGUAGE controls the message text (Uppercase English, Mixed-CaseEnglish, or Japanese). Selection of Japanese could result in DBCS characterswritten to Error Identification records.TEST TEST causes additional object text records to be created that also affect thecontents of the SYSADATA file.NUM NUM causes the compiler to use the contents of columns 1-6 in the sourcerecords <strong>for</strong> line numbering, rather than using generated sequence numbers.Any invalid (nonnumeric) or out-of-sequence numbers are replaced with anumber one higher than that of the previous record.The following SYSADATA fields contain line numbers whose contents differdepending on the NUM|NONUM setting:Type Field Record0020 AE_LINE External Symbol record0030 ATOK_LINE Token record0032 AF_STMT Source Error record0038 AS_STMT Source record0039 AS_REP_EXP_SLIN COPY REPLACING record0039 AS_REP_EXP_ELIN COPY REPLACING record0042 ASY_STMT Symbol record0044 AX_DEFN Symbol Cross Reference record0044 AX_STMT Symbol Cross Reference record© Copyright IBM Corp. 1991, 2009 747


Type Field Record0046 AN_STMT Nested Program recordThe Type 0038 Source record contains two fields that relate to line numbers andrecord numbers:v AS_STMT contains the compiler line number in both the NUM and NONUM cases.v AS_CUR_REC# contains the physical source record number.These two fields can always be used to correlate the compiler line numbers, usedin all the above fields, with physical source record numbers.The remaining compiler options have no direct effect on the SYSADATA file, butmight trigger generation of additional error messages associated with the specificoption, such as FLAGSAA, FLAGSTD, orSSRANGE.“Example: SYSADATA” on page 749SYSADATA record typesRELATED REFERENCES“SYSADATA record types”“COMPILE” on page 313“LANGUAGE” on page 326“NUMBER” on page 332“TEST” on page 349The SYSADATA file contains records classified into different record types. Eachtype of record provides in<strong>for</strong>mation about the <strong>COBOL</strong> program being compiled.Each record consists of two parts:v A 12-byte header section, which has the same structure <strong>for</strong> all record types, andcontains the record code that identifies the type of recordv A variable-length data section, which varies by record typeTable 117. SYSADATA record typesRecord type“Job identification record: X’0000’” on page752“ADATA identification record: X’0001’” onpage 753“Compilation unit start|end record:X’0002’” on page 753“Options record: X’0010’” on page 754“External symbol record: X’0020’” on page763“Parse tree record: X’0024’” on page 764“Token record: X’0030’” on page 779“Source error record: X’0032’” on page 792What it doesProvides in<strong>for</strong>mation about the environmentused to process the source dataProvides common in<strong>for</strong>mation about therecords in the SYSADATA fileMarks the beginning and ending ofcompilation units in a source fileDescribes the compiler options used <strong>for</strong> thecompilationDescribes all external names in the program,definitions, and referencesDefines a node in the parse tree of theprogramDefines a source tokenDescribes errors in source program statements748 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 117. SYSADATA record types (continued)Record typeWhat it does“Source record: X’0038’” on page 793 Describes a single source line“COPY REPLACING record: X’0039’” onpage 794“Symbol record: X’0042’” on page 794“Symbol cross-reference record: X’0044’”on page 807“Nested program record: X’0046’” on page808“Library record: X’0060’” on page 809“Statistics record: X’0090’” on page 809“EVENTS record: X’0120’” on page 810Describes an instance of text replacement as aresult of a match of COPY. . .REPLACINGoperand-1 with text in the copybookDescribes a single symbol defined in theprogram. There is one symbol record <strong>for</strong> eachsymbol defined in the program.Describes references to a single symbolDescribes the name and nesting level of aprogramDescribes the library files and members usedfrom each libraryDescribes the statistics about the compilationEVENTS records provide compatibility with<strong>COBOL</strong>/370. The record <strong>for</strong>mat is identicalwith that in <strong>COBOL</strong>/370, with the addition ofthe standard ADATA header at the beginningof the record and a field indicating the lengthof the EVENTS record data.Example: SYSADATAThe following sample shows part of the listing of a <strong>COBOL</strong> program. If this<strong>COBOL</strong> program were compiled with the ADATA option, the records produced inthe associated data file would be in the sequence shown in the table below.000001 IDENTIFICATION DIVISION. AD000020000002 PROGRAM-ID. AD04202. AD000030000003 ENVIRONMENT DIVISION. AD000040000004 DATA DIVISION. AD000050000005 WORKING-STORAGE SECTION. AD000060000006 77 COMP3-FLD2 pic S9(3)v9. AD000070000007 PROCEDURE DIVISION. AD000080000008 STOP RUN.TypeDescriptionX’0120’EVENTS Timestamp recordX’0120’EVENTS Processor recordX’0120’EVENTS File-ID recordX’0120’EVENTS Program recordX’0001’ADATA Identification recordX’0000’Job Identification recordX’0010’Options recordX’0038’ Source record <strong>for</strong> statement 1X’0038’ Source record <strong>for</strong> statement 2X’0038’ Source record <strong>for</strong> statement 3X’0038’ Source record <strong>for</strong> statement 4Appendix G. <strong>COBOL</strong> SYSADATA file contents 749


TypeDescriptionX’0038’ Source record <strong>for</strong> statement 5X’0038’ Source record <strong>for</strong> statement 6X’0038’ Source record <strong>for</strong> statement 7X’0038’ Source record <strong>for</strong> statement 8X’0020’External Symbol record <strong>for</strong> AD04202X’0044’Symbol Cross Reference record <strong>for</strong> STOPX’0044’Symbol Cross Reference record <strong>for</strong> COMP3-FLD2X’0044’Symbol Cross Reference record <strong>for</strong> AD04202X’0042’Symbol record <strong>for</strong> AD04202X’0042’Symbol record <strong>for</strong> COMP3-FLD2X’0090’Statistics recordX’0120’EVENTS FileEnd recordRELATED REFERENCES“SYSADATA record descriptions”SYSADATA record descriptionsThe <strong>for</strong>mats of the records written to the associated data file are shown in therelated references below.In the fields described in each of the record types, these symbols occur:C Indicates character (EBCDIC or ASCII) dataH Indicates 2-byte binary integer dataF Indicates 4-byte binary integer dataA Indicates 4-byte binary integer address and offset dataX Indicates hexadecimal (bit) data or 1-byte binary integer dataNo boundary alignments are implied by any data type, and the implied lengthsabove might be changed by the presence of a length indicator (Ln). All integer datais in big-endian or little-endian <strong>for</strong>mat depending on the indicator bit in the headerflag byte. Big-endian <strong>for</strong>mat means that bit 0 is always the most significant bit andbit n is the least significant bit. Little-endian refers to “byte-reversed” integers asseen on Intel ® processors.All undefined fields and unused values are reserved.RELATED REFERENCES“Common header section” on page 751“Job identification record: X’0000’” on page 752“ADATA identification record: X’0001’” on page 753“Compilation unit start|end record: X’0002’” on page 753“Options record: X’0010’” on page 754“External symbol record: X’0020’” on page 763“Parse tree record: X’0024’” on page 764“Token record: X’0030’” on page 779“Source error record: X’0032’” on page 792750 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Common header section“Source record: X’0038’” on page 793“COPY REPLACING record: X’0039’” on page 794“Symbol record: X’0042’” on page 794“Symbol cross-reference record: X’0044’” on page 807“Nested program record: X’0046’” on page 808“Library record: X’0060’” on page 809“Statistics record: X’0090’” on page 809“EVENTS record: X’0120’” on page 810The table below shows the <strong>for</strong>mat of the header section that is common <strong>for</strong> allrecord types. For MVS and VSE, each record is preceded by a 4-byte RDW(record-descriptor word) that is normally used only by access methods andstripped off by download utilities.Table 118. SYSADATA common header sectionField Size DescriptionLanguage code XL116 High Level Assembler17 <strong>COBOL</strong> on all plat<strong>for</strong>ms40 PL/I on supported plat<strong>for</strong>msRecord type HL2 The record type, which can be one of the following:Associated dataarchitecture levelXL1X’0000’ Job Identification record 1X’0001’X’0002’ADATA Identification recordCompilation unit start/end recordX’0010’ Options record 1X’0020’X’0024’X’0030’X’0032’X’0038’X’0039’X’0042’X’0044’X’0046’X’0060’External Symbol recordParse Tree recordToken recordSource Error recordSource recordCOPY REPLACING recordSymbol recordSymbol Cross-Reference recordNested Program recordLibrary recordX’0090’ Statistics record 1X’0120’EVENTS record3 Definition level <strong>for</strong> the header structureAppendix G. <strong>COBOL</strong> SYSADATA file contents 751


Table 118. SYSADATA common header section (continued)Field Size DescriptionFlagXL1.... ..1.ADATA record integers are in little-endian(Intel) <strong>for</strong>matAssociated datarecord edition levelXL1.... ...1This record is continued in the next record1111 11..Reserved <strong>for</strong> future useUsed to indicate a new <strong>for</strong>mat <strong>for</strong> a specific record type,usually 0Reserved CL4 Reserved <strong>for</strong> future useAssociated data field HL2 The length in bytes of the data following the headerlength1. When a batch compilation (sequence of programs) is run with the ADATA option, therewill be multiple Job Identification, Options, and Statistics records <strong>for</strong> each compilation.The mapping of the 12-byte header does not include the area used <strong>for</strong> thevariable-length record-descriptor word required by the access method on MVS andVSE.Job identification record: X’0000’The following table shows the contents of the job identification record.Table 119. SYSADATA job identification recordField Size DescriptionDate CL8 The date of the compilation in the <strong>for</strong>mat YYYYMMDDTime CL4 The time of the compilation in the <strong>for</strong>mat HHMMProduct number CL8 The product number of the compiler that produced theassociated data fileProduct version CL8 The version number of the product that produced theassociated data file, in the <strong>for</strong>m V.R.MPTF level CL8 The PTF level number of the product that produced theassociated data file. (This field is blank if the PTFnumber is not available.)System ID CL24 The system identification of the system on which thecompilation was runJob name CL8 The MVS job name of the compilation jobStep name CL8 The MVS step name of the compilation stepProc step CL8 The MVS procedure step name of the compilationprocedureNumber of inputfiles 1 HL2 The number of input files recorded in this record.The following group of seven fields will occur n timesdepending on the value in this field....Input file number HL2 The assigned sequence number of the file752 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 119. SYSADATA job identification record (continued)Field Size Description...Input file name HL2 The length of the following input file namelength...Volume serial HL2 The length of the volume serial numbernumber length...Member name HL2 The length of the member namelength...Input file name CL(n) The name of the input file <strong>for</strong> the compilation...Volume serialnumberCL(n)The volume serial number of the (first) volume on whichthe input file resides...Member name CL(n) Where applicable, the name of the member in the inputfile1. Where the number of input files would exceed the record size <strong>for</strong> the associated datafile, the record is continued on the next record. The current number of input files (<strong>for</strong>that record) is stored in the record, and the record is written to the associated data file.The next record contains the rest of the input files. The count of the number of inputfiles is a count <strong>for</strong> the current record.ADATA identification record: X’0001’The following table shows the contents of the ADATA identification record.Table 120. ADATA identification recordField Size DescriptionTime (binary) XL8 Universal Time (UT) as a binary number of microsecondssince midnight Greenwich Mean Time, with thelow-order bit representing 1 microsecond. This time canbe used as a time-zone-independent time stamp.On Windows and AIX systems, only bytes 5-8 of the fieldare used as a fullword binary field that contains the time.CCSID 1 XL2 Coded Character Set IdentifierCharacter-set flags XL1X’80’ EBCDIC (IBM-037)X’40’ ASCII (IBM-1252)Code-page name XL2 Length of the code-page name that followslengthCode-page name CL(n) Name of the code page1. The appropriate CCS flag will always be set. If the CCSID is set to nonzero, thecode-page name length will be zero. If the CCSID is set to zero, the code-page namelength will be nonzero and the code-page name will be present.Compilation unit start|end record: X’0002’The following table shows the contents of the compilation unit start|end record.Appendix G. <strong>COBOL</strong> SYSADATA file contents 753


Table 121. SYSADATA compilation unit start|end recordField Size DescriptionType HL2 Compilation unit type, which can be one of thefollowing:X’0000’Start compilation unitX’0001’ End compilation unitReserved CL2 Reserved <strong>for</strong> future useReserved FL4 Reserved <strong>for</strong> future useOptions record: X’0010’The following table shows the contents of the options record.Table 122. SYSADATA options recordField Size DescriptionOption byte 0 XL11111 1111Reserved <strong>for</strong> future useOption byte 1 XL11... ....Bit1=DECK,Bit0=NODECK.1.. ....Bit 1 = ADATA, Bit 0 = NOADATA..1. ....Bit1=COLLSEQ(EBCDIC), Bit 0 =COLLSEQ(LOCALE|BINARY) (Windows andAIX only)...1 ....Bit 1 = SEPOBJ, Bit 0 = N<strong>OS</strong>EPOBJ (Windowsand AIX only).... 1...Bit 1 = NAME, Bit 0 = NONAME.... .1..Bit1=OBJECT, Bit 0 = NOOBJECT.... ..1.Bit1=SQL,Bit0=N<strong>OS</strong>QL.... ...1Bit 1 = CICS, Bit 0 = NOCICS754 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 122. SYSADATA options record (continued)Field Size DescriptionOption byte 2 XL11... ....Bit1=OFFSET, Bit 0 = NOOFFSETOption byte 3XL1.1.. ....Bit 1 = MAP, Bit 0 = NOMAP..1. ....Bit 1 = LIST, Bit 0 = NOLIST...1 ....Bit1=DBCSXREF, Bit 0 = NODBCSXREF.... 1...Bit 1 = XREF(SHORT), Bit 0=notXREF(SHORT). This flag should be used incombination with the flag at bit 7. XREF(FULL)is indicated by this flag being off and the flag atbit 7 being on..... .1..Bit1=SOURCE,Bit0=N<strong>OS</strong>OURCE.... ..1.Bit1=VBREF, Bit 0 = NOVBREF.... ...1Bit 1 = XREF, Bit 0 = not XREF. See also flag atbit 4 above.1... ....Bit 1 = FLAG imbedded diagnostics levelspecified (a value y is specified as in FLAG(x,y)).1.. ....Bit 1 = FLAGSTD, Bit 0 = NOFLAGSTD..1. ....Bit 1 = NUM, Bit 0 = NONUM...1 ....Bit 1 = SEQUENCE, Bit 0 = N<strong>OS</strong>EQUENCE.... 1...Bit1=S<strong>OS</strong>I,Bit0=N<strong>OS</strong><strong>OS</strong>I(Windows andAIX only).... .1..Bit1=NSYMBOL(NATIONAL), Bit 0 =NSYMBOL(DBCS).... ..1.Bit 1 = PROFILE, Bit 0 = NOPROFILE (AIXonly).... ...1Bit 1 = WORD, Bit 0 = NOWORDAppendix G. <strong>COBOL</strong> SYSADATA file contents 755


Table 122. SYSADATA options record (continued)Field Size DescriptionOption byte 4 XL11... ....Bit 1 = ADV, Bit 0 = NOADVOption byte 5XL1.1.. ....Bit 1 = AP<strong>OS</strong>T, Bit 0 = QUOTE..1. ....Bit1=DYNAM, Bit 0 = NODYNAM...1 ....Bit 1 = AWO, Bit 0 = NOAWO.... 1...Bit1=RMODE specified, Bit 0 =RMODE(AUTO).... .1..Bit 1 = RENT, Bit 0 = NORENT.... ..1.Bit 1 = RES: this flag will always be set on <strong>for</strong><strong>COBOL</strong>..... ...1Bit1=RMODE(24), Bit 0=RMODE(ANY)1... ....Bit1=SQLCCSID,Bit0=N<strong>OS</strong>QLCCSID.1.. ....Bit1=OPT,Bit0=NOOPT..1. ....Bit 1 = LIB, Bit 0=NOLIB...1 ....Bit1=DBCS,Bit0=NODBCS.... 1...Bit1=OPT(FULL), Bit 0 = not OPT(FULL).... .1..Bit 1 = SSRANGE, Bit 0 = N<strong>OS</strong>SRANGE.... ..1.Bit 1 = TEST, Bit 0 = NOTEST.... ...1Bit 1 = PROBE, Bit 0 = NOPROBE (Windowsonly)756 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|||||Table 122. SYSADATA options record (continued)Field Size DescriptionOption byte 6 XL1..1. ....Bit 1 = NUMPROC(PFD), Bit 0 =NUMPROC(NOPFD)Option byte 7Option byte 8XL1XL1...1 ....Bit 1 = NUMCLS(ALT), Bit 0 = NUMCLS(PRIM).... .1..Bit 1 = BINARY(S390), Bit 0 =BINARY(NATIVE) (Windows and AIX only).... ..1.Bit 1 = TRUNC(STD), Bit 0 = TRUNC(OPT).... ...1Bit1=ZWB,Bit0=NOZWB11.. 1...Reserved <strong>for</strong> future use1... ....Bit 1 = ALOWCBL, Bit 0 = NOALOWCBL.1.. ....Bit 1 = TERM, Bit 0 = NOTERM..1. ....Bit 1 = DUMP, Bit 0 = NODUMP.... ..1.Bit 1 = CURRENCY, Bit 0 = NOCURRENCY...1 11.1Reserved <strong>for</strong> future use1... ....Bit1=XMLPARSE(XMLSS), Bit 0 =XMLPARSE(COMPAT).1.. ....Bit1=OPTFILE, Bit 0 = not OPTFILE..1. ....Bit 1 = ADDR(64), Bit 0 = ADDR(32) (AIX only).... 1...Bit 1 = BLOCK0, Bit 0 = NOBLOCK0...1 .111Reserved <strong>for</strong> future useAppendix G. <strong>COBOL</strong> SYSADATA file contents 757


Table 122. SYSADATA options record (continued)Field Size DescriptionOption byte 9 XL11... ....Bit1=DATA(24), Bit 0=DATA(31)Option byte AOption byte BOption byte CXL1XL1XL1.1.. ....Bit1=FASTSRT, Bit 0 = NOFASTSRT..1. ....Bit 1 = SIZE(MAX), Bit 0 = SIZE(nnnn) orSIZE(nnnnK).... .1..Bit1=THREAD,Bit0=NOTHREAD...1 1.11Reserved <strong>for</strong> future use1111 1111Reserved <strong>for</strong> future use1111 1111Reserved <strong>for</strong> future use1... ....Bit 1 = NCOLLSEQ(LOCALE) (Windows andAIX only).1.. ....Reserved <strong>for</strong> future use..1. ....Bit1=INTDATE(LILIAN), Bit 0 =INTDATE(ANSI)...1 ....Bit 1 = NCOLLSEQ(BINARY) (Windows andAIX only).... 1...Bit1=CHAR(EBCDIC), Bit 0 =CHAR(NATIVE) (Windows and AIX only).... .1..Bit 1 = FLOAT(HEX), Bit 0 = FLOAT(NATIVE)(Windows and AIX only).... ..1.Bit1=COLLSEQ(BINARY) (Windows and AIXonly).... ...1Bit1=COLLSEQ(LOCALE) (Windows and AIXonly)758 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 122. SYSADATA options record (continued)Field Size DescriptionOption byte D XL11... ....Bit1=DLLBit0=NODLLOption byte EOption byte FFlag levelXL1XL1XL1.1.. ....Bit 1 = EXPORTALL, Bit 0 = NOEXPORTALL..1. ....Bit 1 = CODEPAGE...1 ....Bit1=DATEPROC, Bit 0 = NODATEPROC.... 1...Bit1=DATEPROC(FLAG), Bit 0 =DATEPROC(NOFLAG).... .1..Bit 1 = YEARWINDOW.... ..1.Bit1=WSCLEAR,Bit0=NOWSCLEAR(Windows and AIX only).... ...1Bit 1 = BEOPT, Bit 0 = NOBEOPT (Windowsand AIX only)1... ....Bit1=DATEPROC(TRIG), Bit 0 =DATEPROC(NOTRIG).1.. ....Bit1=DIAGTRUNC, Bit 0 = NODIAGTRUNC.... .1..Bit 1 = LSTFILE(UTF-8), Bit 0 =LSTFILE(LOCALE) (Windows and AIX only).... ..1.Bit 1 = MDECK, Bit 0 = NOMDECK.... ...1Bit 1 = MDECK(NOCOMPILE)..11 1...Reserved <strong>for</strong> future use1111 1111Reserved <strong>for</strong> future useX’00’X’04’X’08’X’0C’X’10’X’FF’Flag(I)Flag(W)Flag(E)Flag(S)Flag(U)NoflagAppendix G. <strong>COBOL</strong> SYSADATA file contents 759


Table 122. SYSADATA options record (continued)Field Size DescriptionImbedded diagnostic XL1levelX’00’ Flag(I)X’04’ Flag(W)FLAGSTD (FIPS)specificationReserved <strong>for</strong> flaggingCompiler modeSpace valueData <strong>for</strong> 3-valuedoptionsXL1XL1XL1CL1XL1X’08’X’0C’X’10’X’FF’Flag(E)Flag(S)Flag(U)Noflag1... ....Minimum.1.. ....Intermediate..1. ....High...1 ....IBM extensions.... 1...Level-1 segmentation.... .1..Level-2 segmentation.... ..1.Debugging.... ...1Obsolete1111 1111Reserved <strong>for</strong> future useX’00’X’04’X’08’X’0C’X’FF’Unconditional Nocompile, Nocompile(I)Nocompile(W)Nocompile(E)Nocompile(S)Compile1... ....NAME(ALIAS) specified.1.. ....NUMPROC(MIG) specified..1. ....TRUNC(BIN) specified...1 1111Reserved <strong>for</strong> future use760 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 122. SYSADATA options record (continued)Field Size DescriptionTEST suboptions XL11... ....TEST(HOOK).1.. ....TEST(SEP)..1. ....TEST(EJPD)...1 1111Reserved <strong>for</strong> TEST suboptionsOUTDD name length HL2 Length of OUTDD nameRWT ID Length HL2 Length of Reserved Word Table identifierLVLINFO CL4 User-specified LVLINFO dataPGMNAMEsuboptionsEntry interfacesuboptionsCallInterfacesuboptionsARITH suboptionXL1XL1XL1XL11... ....Bit1=PGMNAME(COMPAT).1.. ....Bit1=PGMNAME(LONGUPPER)..1. ....Bit1=PGMNAME(LONGMIXED)...1 1111Reserved <strong>for</strong> future use1... ....Bit 1 = EntryInterface(System) (Windows only).1.. ....Bit 1 = EntryInterface(OptLink) (Windows only)..11 1111Reserved <strong>for</strong> future use1... ....Bit1=CallInterface(System) (Windows and AIXonly).1.. ....Bit1=CallInterface(OptLink) (Windows only)...1 ....Bit1=CallInterface(Cdecl) (Windows only).... 1...Bit1=CallInterface(System(Desc)) (Windowsand AIX only)..1. .111Reserved <strong>for</strong> future use1... ....Bit 1 = ARITH(COMPAT).1.. ....Bit 1 = ARITH(EXTEND)11 1111Reserved <strong>for</strong> future useDBCS Req FL4 DBCS XREF storage requirementAppendix G. <strong>COBOL</strong> SYSADATA file contents 761


Table 122. SYSADATA options record (continued)Field Size DescriptionDBCS ORDPGM HL2 Length of name of DBCS Ordering ProgramlengthDBCS ENCTBL HL2 Length of name of DBCS Encode TablelengthDBCS ORD TYPE CL2 DBCS Ordering typeReserved CL6 Reserved <strong>for</strong> future useConverted SO CL1 Converted SO hexadecimal valueConverted SI CL1 Converted SI hexadecimal valueLanguage id CL2 This field holds the two-character abbreviation (one ofEN, UE, JA, or JP) from the LANGUAGE option.Reserved CL8 Reserved <strong>for</strong> future useINEXIT name length HL2 Length of SYSIN user-exit namePRTEXIT name length HL2 Length of SYSPRINT user-exit nameLIBEXIT name length HL2 Length of ’Library’ user-exit nameADEXIT name length HL2 Length of ADATA user-exit nameCURROPT CL5 CURRENCY option valueReserved CL1 Reserved <strong>for</strong> future useYEARWINDOW HL2 YEARWINDOW option valueCODEPAGE HL2 CODEPAGE CCSID option valueReserved CL50 Reserved <strong>for</strong> future useLINECNT HL2 LINECOUNT valueReserved CL2 Reserved <strong>for</strong> future useBUFSIZE FL4 BUFSIZE option valueSize value FL4 SIZE option valueReserved FL4 Reserved <strong>for</strong> future usePhase residence bitsbyte 1XL11... ....Bit1=IGYCLIBR in user region.1.. ....Bit1=IGYCSCANinuser region..1. ....Bit1=IGYCDSCNinuser region...1 ....Bit1=IGYCGROUinuser region.... 1...Bit1=IGYCPSCNinuser region.... .1..Bit1=IGYCPANAinuser region.... ..1.Bit1=IGYCFGENinuser region.... ...1Bit1=IGYCPGENinuser region762 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 122. SYSADATA options record (continued)Field Size DescriptionPhase residence bitsbyte 2XL11... ....Bit1=IGYCOPTMinuser region.1.. ....Bit1=IGYCLSTR in user region..1. ....Bit1=IGYCXREF in user region...1 ....Bit1=IGYCDMAP in user region.... 1...Bit1=IGYCASM1inuser region.... .1..Bit1=IGYCASM2inuser region.... ..1.Bit1=IGYCDIAGinuser region.... ...1Reserved <strong>for</strong> future usePhase residence bits XL2 Reservedbytes 3 and 4Reserved CL8 Reserved <strong>for</strong> future useOUTDD name CL(n) OUTDD nameRWT CL(n) Reserved word table identifierDBCS ORDPGM CL(n) DBCS Ordering program nameDBCS ENCTBL CL(n) DBCS Encode table nameINEXIT name CL(n) SYSIN user-exit namePRTEXIT name CL(n) SYSPRINT user-exit nameLIBEXIT name CL(n) ’Library’ user-exit nameADEXIT name CL(n) ADATA user-exit nameExternal symbol record: X’0020’The following table shows the contents of the external symbol record.Appendix G. <strong>COBOL</strong> SYSADATA file contents 763


Table 123. SYSADATA external symbol recordField Size DescriptionSection typeXL1X'00' PROGRAM-ID name (main entry point name)X'01'X'02'X'04'X'05'X'06'X'0A'X'12'X'C0'X'C1'X'C6'X'FF'ENTRY name (secondary entry point name)External reference (referenced external entrypoint)Not applicable <strong>for</strong> <strong>COBOL</strong>Not applicable <strong>for</strong> <strong>COBOL</strong>Not applicable <strong>for</strong> <strong>COBOL</strong>Not applicable <strong>for</strong> <strong>COBOL</strong>Internal reference (referenced internalsubprogram)External class-name (OO <strong>COBOL</strong> classdefinition)METHOD-ID name (OO <strong>COBOL</strong> method definition)Method reference (OO <strong>COBOL</strong> methodreference)Not applicable <strong>for</strong> <strong>COBOL</strong>Types X’12’, X’C0’, X’C1’ and X’C6’ are <strong>for</strong> <strong>COBOL</strong> only.Flags XL1 Not applicable <strong>for</strong> <strong>COBOL</strong>Reserved HL2 Reserved <strong>for</strong> future useSymbol-ID FL4 Symbol-ID of program that contains the reference (only<strong>for</strong> types x’02’ and x’12’)Line number FL4 Line number of statement that contains the reference(only <strong>for</strong> types x’02’ and x’12’)Section length FL4 Not applicable <strong>for</strong> <strong>COBOL</strong>LD ID FL4 Not applicable <strong>for</strong> <strong>COBOL</strong>Reserved CL8 Reserved <strong>for</strong> future useExternal name length HL2 Number of characters in the external nameAlias name length HL2 Not applicable <strong>for</strong> <strong>COBOL</strong>External name CL(n) The external nameAlias section name CL(n) Not applicable <strong>for</strong> <strong>COBOL</strong>Parse tree record: X’0024’The following table shows the contents of the parse tree record.Table 124. SYSADATA parse tree recordField Size DescriptionNode number FL4 The node number generated by the compiler, starting at1764 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionNode type HL2 The type of the node:001 Program002 Class003 Method101 Identification Division102 Environment Division103 Data Division104 Procedure Division105 End Program/Method/Class201 Declaratives body202 Nondeclaratives body301 Section302 Procedure section401 Paragraph402 Procedure paragraph501 Sentence502 File definition503 Sort file definition504 Program-name505 Program attribute508 ENVIRONMENT DIVISION clause509 CLASS attribute510 METHOD attribute511 USE statement601 Statement602 Data description clause603 Data entry604 File description clause605 Data entry name606 Data entry level607 EXEC entryAppendix G. <strong>COBOL</strong> SYSADATA file contents 765


Table 124. SYSADATA parse tree record (continued)Field Size Description701 EVALUATE subject phrase702 EVALUATE WHEN phrase703 EVALUATE WHEN OTHER phrase704 SEARCH WHEN phrase705 INSPECT CONVERTING phrase706 INSPECT REPLACING phrase707 INSPECT TALLYING phrase708 PERFORM UNTIL phrase709 PERFORM VARYING phrase710 PERFORM AFTER phrase711 Statement block712 Scope terminator713 INITIALIZE REPLACING phrase714 EXEC CICS Command720 DATA DIVISION phrase801 Phrase802 ON phrase803 NOT phrase804 THEN phrase805 ELSE phrase806 Condition807 Expression808 Relative indexing809 EXEC CICS Option810 Reserved word811 INITIALIZE REPLACING category766 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size Description901 Section or paragraph name902 Identifier903 Alphabet-name904 Class-name905 Condition-name906 File-name907 Index-name908 Mnemonic-name910 Symbolic-character911 Literal912 Function identifier913 Data-name914 Special register915 Procedure reference916 Arithmetic operator917 All procedures918 INITIALIZE literal (no tokens)919 ALL literal or figcon920 Keyword class test name921 Reserved word at identifier level922 Unary operator923 Relational operator1001 Subscript1002 Reference modificationNode subtype HL2 The subtype of the node.For Section type:0001 CONFIGURATION Section0002 INPUT-OUTPUT Section0003 FILE Section0004 WORKING-STORAGE Section0005 LINKAGE Section0006 LOCAL-STORAGE Section0007 REP<strong>OS</strong>ITORY SectionAppendix G. <strong>COBOL</strong> SYSADATA file contents 767


|Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor Paragraph type:0001 PROGRAM-ID paragraph0002 AUTHOR paragraph0003 INSTALLATION paragraph0004 DATE-WRITTEN paragraph0005 SECURITY paragraph0006 SOURCE-COMPUTER paragraph0007 OBJECT-COMPUTER paragraph0008 SPECIAL-NAMES paragraph0009 FILE-CONTROL paragraph0010 I-O-CONTROL paragraph0011 DATE-COMPILED paragraph0012 CLASS-ID paragraph0013 METHOD-ID paragraph0014 REP<strong>OS</strong>ITORY paragraphFor Environment Division clause type:0001 WITH DEBUGGING MODE0002 MEMORY-SIZE0003 SEGMENT-LIMIT0004 CURRENCY-SIGN0005 DECIMAL POINT0006 PROGRAM COLLATING SEQUENCE0007 ALPHABET0008 SYMBOLIC-CHARACTER0009 CLASS0010 ENVIRONMENT NAME0011 SELECT0012 XML-SCHEMA768 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor Data description clause type:0001 BLANK WHEN ZERO0002 DATA-NAME OR FILLER0003 JUSTIFIED0004 OCCURS0005 PICTURE0006 REDEFINES0007 RENAMES0008 SIGN0009 SYNCHRONIZED0010 USAGE0011 VALUE0023 GLOBAL0024 EXTERNALAppendix G. <strong>COBOL</strong> SYSADATA file contents 769


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor File Description clause type:0001 FILE STATUS0002 ORGANIZATION0003 ACCESS MODE0004 RECORD KEY0005 ASSIGN0006 RELATIVE KEY0007 PASSWORD0008 PROCESSING MODE0009 RECORD DELIMITER0010 PADDING CHARACTER0011 BLOCK CONTAINS0012 RECORD CONTAINS0013 LABEL RECORDS0014 VALUE OF0015 DATA RECORDS0016 LINAGE0017 ALTERNATE KEY0018 LINES AT TOP0019 LINES AT BOTTOM0020 CODE-SET0021 RECORDING MODE0022 RESERVE0023 GLOBAL0024 EXTERNAL0025 LOCK770 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor Statement type:0002 NEXT SENTENCE0003 ACCEPT0004 ADD0005 ALTER0006 CALL0007 CANCEL0008 CL<strong>OS</strong>E0009 COMPUTE0010 CONTINUE0011 DELETE0012 DISPLAY0013 DIVIDE (INTO)0113 DIVIDE (BY)0014 ENTER0015 ENTRY0016 EVALUATE0017 EXIT0018 GO0019 GOBACK0020 IF0021 INITIALIZE0022 INSPECTAppendix G. <strong>COBOL</strong> SYSADATA file contents 771


Table 124. SYSADATA parse tree record (continued)Field Size Description0023 INVOKE0024 MERGE0025 MOVE0026 MULTIPLY0027 OPEN0028 PERFORM0029 READ0030 READY0031 RELEASE0032 RESET0033 RETURN0034 REWRITE0035 SEARCH0036 SERVICE0037 SET0038 SORT0039 START0040 STOP0041 STRING0042 SUBTRACT0043 UNSTRING0044 EXEC SQL0144 EXEC CICS0045 WRITE0046 XML772 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor Phrase type:0001 INTO0002 DELIMITED0003 INITIALIZE. . .REPLACING0004 INSPECT. . .ALL0005 INSPECT. . .LEADING0006 SET. . .TO0007 SET. . .UP0008 SET. . .DOWN0009 PERFORM. . .TIMES0010 DIVIDE. . .REMAINDER0011 INSPECT. . .FIRST0012 SEARCH. . .VARYING0013 MORE-LABELS0014 SEARCH ALL0015 SEARCH. . .AT END0016 SEARCH. . .TEST INDEX0017 GLOBAL0018 LABEL0019 DEBUGGING0020 SEQUENCE0021 Reserved <strong>for</strong> future use0022 Reserved <strong>for</strong> future use0023 Reserved <strong>for</strong> future use0024 TALLYING0025 Reserved <strong>for</strong> future use0026 ON SIZE ERROR0027 ON OVERFLOW0028 ON ERROR0029 AT END0030 INVALID KEYAppendix G. <strong>COBOL</strong> SYSADATA file contents 773


Table 124. SYSADATA parse tree record (continued)Field Size Description0031 END-OF-PAGE0032 USING0033 BEFORE0034 AFTER0035 EXCEPTION0036 CORRESPONDING0037 Reserved <strong>for</strong> future use0038 RETURNING0039 GIVING0040 THROUGH0041 KEY0042 DELIMITER0043 POINTER0044 COUNT0045 METHOD0046 PROGRAM0047 INPUT0048 OUTPUT0049 I-O0050 EXTEND0051 RELOAD0052 ASCENDING0053 DESCENDING0054 DUPLICATES0055 NATIVE (USAGE)0056 INDEXED0057 FROM0058 FOOTING0059 LINES AT BOTTOM0060 LINES AT TOP0061 XML ENCODING0062 XML GENERATE XML-DECLARATION0063 XML GENERATE ATTRIBUTES0064 XML GENERATE NAMESPACE|0065 XML PARSE PROCESSING0066 XML PARSE VALIDATING774 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor Function identifier type:0001 C<strong>OS</strong>0002 LOG0003 MAX0004 MIN0005 MOD0006 ORD0007 REM0008 SIN0009 SUM0010 TAN0011 AC<strong>OS</strong>0012 ASIN0013 ATAN0014 CHAR0015 MEAN0016 SQRT0017 LOG100018 RANGE0019 LENGTH0020 MEDIAN0021 NUMVAL0022 RANDOM0023 ANNUITY0024 INTEGER0025 ORD-MAX0026 ORD-MIN0027 REVERSE0028 MIDRANGE0029 NUMVAL-C0030 VARIANCE0031 FACTORIAL0032 LOWER-CASEAppendix G. <strong>COBOL</strong> SYSADATA file contents 775


Table 124. SYSADATA parse tree record (continued)Field Size Description0033 UPPER-CASE0034 CURRENT-DATE0035 INTEGER-PART0036 PRESENT-VALUE0037 WHEN-COMPILED0038 DAY-OF-INTEGER0039 INTEGER-OF-DAY0040 DATE-OF-INTEGER0041 INTEGER-OF-DATE0042 STANDARD-DEVIATION0043 YEAR-TO-YYYY0044 DAY-TO-YYYYDDD0045 DATE-TO-YYYYMMDD0046 UNDATE0047 DATEVAL0048 YEARWINDOW0049 DISPLAY-OF0050 NATIONAL-OFFor Special Register type:0001 ADDRESS OF0002 LENGTH OFFor Keyword Class Test Name type:0001 ALPHABETIC0002 ALPHABETIC-LOWER0003 ALPHABETIC-UPPER0004 DBCS0005 KANJI0006 NUMERIC0007 NEGATIVE0008 P<strong>OS</strong>ITIVE0009 ZEROFor Reserved Word type:0001 TRUE0002 FALSE0003 ANY0004 THRU776 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor Identifier, Data-name, Index-name, Condition-nameor Mnemonic-name type:0001 REFERENCED0002 CHANGED0003 REFERENCED & CHANGEDFor Initialize literal type:0001 ALPHABETIC0002 ALPHANUMERIC0003 NUMERIC0004 ALPHANUMERIC-EDITED0005 NUMERIC-EDITED0006 DBCS/EGCS0007 NATIONAL0008 NATIONAL-EDITEDFor Procedure-name type:0001 SECTION0002 PARAGRAPHFor Reserved word at identifier level type:0001 ROUNDED0002 TRUE0003 ON0004 OFF0005 SIZE0006 DATE0007 DAY0008 DAY-OF-WEEK0009 TIME0010 WHEN-COMPILED0011 PAGE0012 DATE YYYYMMDD0013 DAY YYYYDDDAppendix G. <strong>COBOL</strong> SYSADATA file contents 777


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionFor Arithmetic Operator type:0001 PLUS0002 MINUS0003 TIMES0004 DIVIDE0005 DIVIDE REMAINDER0006 EXPONENTIATE0007 NEGATEFor Relational Operator type:0008 LESS0009 LESS OR EQUAL0010 EQUAL0011 NOT EQUAL0012 GREATER0013 GREATER OR EQUAL0014 AND0015 OR0016 CLASS CONDITION0017 NOT CLASS CONDITIONParent node number FL4 The node number of the parent of the nodeLeft sibling nodenumberFL4The node number of the left sibling of the node, if any. Ifnone, the value is zero.Symbol ID FL4 The Symbol ID of the node, if it is a user-name of one ofthe following types:v Data entryv Identifierv File-namev Index-namev Procedure-namev Condition-namev Mnemonic-nameThis value corresponds to the Symbol ID in a Symbol(Type 42) record, except <strong>for</strong> procedure-names where itcorresponds to the Paragraph ID.For all other node types this value is zero.Section Symbol ID FL4 The Symbol ID of the section containing the node, if it isa qualified paragraph-name reference. This valuecorresponds to the Section ID in a Symbol (Type 42)record.For all other node types this value is zero.First token number FL4 The number of the first token associated with the node778 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 124. SYSADATA parse tree record (continued)Field Size DescriptionLast token number FL4 The number of the last token associated with the nodeReserved FL4 Reserved <strong>for</strong> future useFlags CL1 In<strong>for</strong>mation about the node:X’80’ReservedX’40’ Generated node, no tokensReserved CL3 Reserved <strong>for</strong> future useToken record: X’0030’The compiler does not generate token records <strong>for</strong> any lines that are treated ascomment lines, which include, but are not limited to, items in the following list.vvvComment lines, which are lines that have an asterisk (*) or a slash (/) in column7The following compiler-directing statements:– *CBL (*CONTROL)– BASIS– COPY– DELETE– EJECT– INSERT– REPLACE– SKIP1– SKIP2– SKIP3– TITLEDebugging lines, which are lines that have a D in column 7, if WITH DEBUGGINGMODE is not specifiedTable 125. SYSADATA token recordField Size DescriptionToken number FL4 The token number within the source file generated bythe compiler, starting at 1. Any copybooks have alreadybeen included in the source.Appendix G. <strong>COBOL</strong> SYSADATA file contents 779


Table 125. SYSADATA token record (continued)Field Size DescriptionToken code HL2 The type of token (user-name, literal, reserved word, andso <strong>for</strong>th).For reserved words, the compiler reserved-word tablevalues are used.For PICTURE strings, the special code 0000 is used.For each piece (other than the last) of a continued token,the special code 3333 is used.Otherwise, the following codes are used:0001 ACCEPT0002 ADD0003 ALTER0004 CALL0005 CANCEL0007 CL<strong>OS</strong>E0009 COMPUTE0011 DELETE0013 DISPLAY0014 DIVIDE0017 READY0018 END-PERFORM0019 ENTER0020 ENTRY0021 EXIT0022 EXEC0023 GO0024 IFEXECUTE0025 INITIALIZE0026 INVOKE0027 INSPECT0028 MERGE0029 MOVE780 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 125. SYSADATA token record (continued)Field Size Description0030 MULTIPLY0031 OPEN0032 PERFORM0033 READ0035 RELEASE0036 RETURN0037 REWRITE0038 SEARCH0040 SET0041 SORT0042 START0043 STOP0044 STRING0045 SUBTRACT0048 UNSTRING0049 USE0050 WRITE0051 CONTINUE0052 END-ADD0053 END-CALL0054 END-COMPUTE0055 END-DELETE0056 END-DIVIDE0057 END-EVALUATE0058 END-IF0059 END-MULTIPLY0060 END-READ0061 END-RETURN0062 END-REWRITE0063 END-SEARCH0064 END-START0065 END-STRING0066 END-SUBTRACT0067 END-UNSTRING0068 END-WRITE0069 GOBACKAppendix G. <strong>COBOL</strong> SYSADATA file contents 781


Table 125. SYSADATA token record (continued)Field Size Description0070 EVALUATE0071 RESET0072 SERVICE0073 END-INVOKE0074 END-EXEC0075 XML0076 END-XML0099 FOREIGN-VERB0101 DATA-NAME0105 DASHED-NUM0106 DECIMAL0107 DIV-SIGN0108 EQ0109 EXPONENTIATION0110 GT0111 INTEGER0112 LT0113 LPAREN0114 MINUS-SIGN0115 MULT-SIGN0116 NONUMLIT0117 PERIOD0118 PLUS-SIGN0121 RPAREN0122 SIGNED-INTEGER0123 QUID0124 COLON0125 IEOF0126 EGCS-LIT0127 COMMA-SPACE0128 SEMICOLON-SPACE0129 PROCEDURE-NAME0130 FLT-POINT-LIT0131 Language Environment782 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 125. SYSADATA token record (continued)Field Size Description0132 GE0133 IDREF0134 EXPREF0136 CICS0137 NEW0138 NATIONAL-LIT0200 ADDRESS0201 ADVANCING0202 AFTER0203 ALL0204 ALPHABETIC0205 ALPHANUMERIC0206 ANY0207 AND0208 ALPHANUMERIC-EDITED0209 BEFORE0210 BEGINNING0211 FUNCTION0212 CONTENT0213 CORRCORRESPONDING0214 DAY0215 DATE0216 DEBUG-CONTENTS0217 DEBUG-ITEM0218 DEBUG-LINE0219 DEBUG-NAME0220 DEBUG-SUB-10221 DEBUG-SUB-20222 DEBUG-SUB-30223 DELIMITED0224 DELIMITER0225 DOWNAppendix G. <strong>COBOL</strong> SYSADATA file contents 783


Table 125. SYSADATA token record (continued)Field Size Description0226 NUMERIC-EDITED0227 XML-EVENT0228 END-OF-PAGEEOP0229 EQUAL0230 ERROR0231 XML-NTEXT0232 EXCEPTION0233 EXTEND0234 FIRST0235 FROM0236 GIVING0237 GREATER0238 I-O0239 IN0240 INITIAL0241 INTO0242 INVALID0243 SQL0244 LESS0245 LINAGE-COUNTER0246 XML-TEXT0247 LOCK0248 GENERATE0249 NEGATIVE0250 NEXT0251 NO0252 NOT0253 NUMERIC0254 KANJI0255 OR0256 OTHER0257 OVERFLOW0258 PAGE0259 CONVERTING784 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 125. SYSADATA token record (continued)Field Size Description0260 POINTER0261 P<strong>OS</strong>ITIVE0262 DBCS0263 PROCEDURES0264 PROCEED0265 REFERENCES0266 DAY-OF-WEEK0267 REMAINDER0268 REMOVAL0269 REPLACING0270 REVERSED0271 REWIND0272 ROUNDED0273 RUN0274 SENTENCE0275 STANDARD0276 RETURN-CODESORT-CORE-SIZESORT-FILE-SIZESORT-MESSAGESORT-MODE-SIZESORT-RETURNTALLYXML-CODE0277 TALLYING0278 SUM0279 TEST0280 THAN0281 UNTIL0282 UP0283 UPON0284 VARYING0285 RELOAD0286 TRUEAppendix G. <strong>COBOL</strong> SYSADATA file contents 785


Table 125. SYSADATA token record (continued)Field Size Description0287 THEN0288 RETURNING0289 ELSE0290 SELF0291 SUPER0292 WHEN-COMPILED0293 ENDING0294 FALSE0295 REFERENCE0296 NATIONAL-EDITED0297 COM-REG0298 ALPHABETIC-LOWER0299 ALPHABETIC-UPPER0301 REDEFINES0302 OCCURS0303 SYNCSYNCHRONIZED0304 MORE-LABELS0305 JUSTJUSTIFIED0306 SHIFT-IN0307 BLANK0308 VALUE0309 COMPCOMPUTATIONAL0310 COMP-1COMPUTATIONAL-10311 COMP-3COMPUTATIONAL-30312 COMP-2COMPUTATIONAL-20313 COMP-4COMPUTATIONAL-40314 DISPLAY-10315 SHIFT-OUT786 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 125. SYSADATA token record (continued)Field Size Description0316 INDEX0317 USAGE0318 SIGN0319 LEADING0320 SEPARATE0321 INDEXED0322 LEFT0323 RIGHT0324 PICPICTURE0325 VALUES0326 GLOBAL0327 EXTERNAL0328 BINARY0329 PACKED-DECIMAL0330 EGCS0331 PROCEDURE-POINTER0332 COMP-5COMPUTATIONAL-50333 FUNCTION-POINTER0334 TYPE0335 JNIENVPTR0336 NATIONAL0337 GROUP-USAGE0401 HIGH-VALUEHIGH-VALUES0402 LOW-VALUELOW-VALUES0403 QUOTEQUOTES0404 SPACESPACES0405 ZEROAppendix G. <strong>COBOL</strong> SYSADATA file contents 787


Table 125. SYSADATA token record (continued)Field Size Description0406 ZEROESZER<strong>OS</strong>0407 NULLNULLS0501 BLOCK0502 BOTTOM0505 CHARACTER0506 CODE0507 CODE-SET0514 FILLER0516 FOOTING0520 LABEL0521 LENGTH0524 LINAGE0526 OMITTED0531 RENAMES0543 TOP0545 TRAILING0549 RECORDING0601 INHERITS0603 RECURSIVE0701 ACCESS0702 ALSO0703 ALTERNATE0704 AREAAREAS0705 ASSIGN0707 COLLATING0708 COMMA0709 CURRENCY0710 CLASS0711 DECIMAL-POINT0712 DUPLICATES0713 DYNAMIC0714 EVERY788 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 125. SYSADATA token record (continued)Field Size Description0716 MEMORY0717 MODE0718 MODULES0719 MULTIPLE0720 NATIVE0721 OFF0722 OPTIONAL0723 ORGANIZATION0724 P<strong>OS</strong>ITION0725 PROGRAM0726 RANDOM0727 RELATIVE0728 RERUN0729 RESERVE0730 SAME0731 SEGMENT-LIMIT0732 SELECT0733 SEQUENCE0734 SEQUENTIAL0736 SORT-MERGE0737 STANDARD-10738 TAPE0739 WORDS0740 PROCESSING0741 APPLY0742 WRITE-ONLY0743 COMMON0744 ALPHABET0745 PADDING0746 SYMBOLIC0747 STANDARD-20748 OVERRIDE0750 PASSWORDAppendix G. <strong>COBOL</strong> SYSADATA file contents 789


Table 125. SYSADATA token record (continued)Field Size Description0801 AREIS0802 ASCENDING0803 AT0804 BY0805 CHARACTERS0806 CONTAINS0808 COUNT0809 DEBUGGING0810 DEPENDING0811 DESCENDING0812 DIVISION0814 FOR0815 ORDER0816 INPUT0817 REPLACE0818 KEY0819 LINELINES0821 OF0822 ON0823 OUTPUT0825 RECORD0826 RECORDS0827 REEL0828 SECTION0829 SIZE0830 STATUS0831 THROUGHTHRU0832 TIME0833 TIMES0834 TO0836 UNIT790 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 125. SYSADATA token record (continued)Field Size Description0837 USING0838 WHEN0839 WITH0901 PROCEDURE0902 DECLARATIVES0903 END1001 DATA1002 FILE1003 FD1004 SD1005 WORKING-STORAGE1006 LOCAL-STORAGE1007 LINKAGE1101 ENVIRONMENT1102 CONFIGURATION1103 SOURCE-COMPUTER1104 OBJECT-COMPUTER1105 SPECIAL-NAMES1106 REP<strong>OS</strong>ITORY1107 INPUT-OUTPUT1108 FILE-CONTROL1109 I-O-CONTROL1201 IDIDENTIFICATION1202 PROGRAM-ID1203 AUTHOR1204 INSTALLATION1205 DATE-WRITTEN1206 DATE-COMPILED1207 SECURITY1208 CLASS-ID1209 METHOD-ID1210 METHOD1211 FACTORYAppendix G. <strong>COBOL</strong> SYSADATA file contents 791


Table 125. SYSADATA token record (continued)Field Size Description1212 OBJECT2020 TRACE3000 DATADEF3001 F-NAME3002 UPSI-SWITCH3003 CONDNAME3004 CONDVAR3005 BLOB3006 CLOB3007 DBCLOB3008 BLOB-LOCATOR3009 CLOB-LOCATOR3010 DBCLOB-LOCATOR3011 BLOB-FILE3012 CLOB-FILE3013 DBCLOB-FILE3014 DFHRESP5001 PARSE5002 AUTOMATIC5003 PREVIOUS9999 <strong>COBOL</strong>Token length HL2 The length of the tokenToken column FL4 The starting column number of the token in the sourcelistingToken line FL4 The line number of the token in the source listingFlags CL1 In<strong>for</strong>mation about the token:X’80’X’40’Token is continuedLast piece of continued tokenNote that <strong>for</strong> PICTURE strings, even if the source token iscontinued, there will be only one Token recordgenerated. It will have a token code of 0000, the tokencolumn and line of the first piece, the length of thecomplete string, no continuation flags set, and the tokentext of the complete string.Reserved CL7 Reserved <strong>for</strong> future useToken text CL(n) The actual token stringSource error record: X’0032’The following table shows the contents of the source error record.792 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 126. SYSADATA source error recordField Size DescriptionStatement number FL4 The statement number of the statement in errorError identifier CL16 The error message identifier (left-justified and paddedwith blanks)Error severity HL2 The severity of the errorError message length HL2 The length of the error message textLine position XL1 The line position indicator provided in FIPS messagesReserved CL7 Reserved <strong>for</strong> future useError message CL(n) The error message textSource record: X’0038’The following table shows the contents of the source record.Table 127. SYSADATA source recordField Size DescriptionLine number FL4 The listing line number of the source recordInput record number FL4 The input source record number in the current input filePrimary file number HL2 The input file’s assigned sequence number if this recordis from the primary input file. (Refer to the Input file nfield in the Job identification record).Library file number HL2 The library input file’s assigned sequence number if thisrecord is from a COPY|BASIS input file. (Refer to theMember File ID n field in the Library record.)Reserved CL8 Reserved <strong>for</strong> future useParent record number FL4 The parent source record number. This will be the recordnumber of the COPY|BASIS statement.Parent primary filenumberParent libraryassigned file numberHL2HL2The parent file’s assigned sequence number if the parentof this record is from the primary input file. (Refer to theInput file n field in the Job Identification Record.)The parent library file’s assigned sequence number if thisrecord’s parent is from a COPY|BASIS input file. (Refer tothe COPY/BASIS Member File ID n field in the Libraryrecord.)Reserved CL8 Reserved <strong>for</strong> future useLength of source HL2 The length of the actual source record followingrecordReserved CL10 Reserved <strong>for</strong> future useSource record CL(n)Appendix G. <strong>COBOL</strong> SYSADATA file contents 793


COPY REPLACING record: X’0039’One COPY REPLACING type record will be emitted each time a REPLACING action takesplace. That is, whenever operand-1 of the REPLACING phrase is matched with text inthe copybook, a COPY REPLACING TEXT record will be written.The following table shows the contents of the COPY REPLACING record.Table 128. SYSADATA COPY REPLACING recordField Size DescriptionStarting line numberof replaced stringStarting columnnumber of replacedstringEnding line numberof replaced stringEnding columnnumber of replacedstringStarting line numberof original stringStarting columnnumber of originalstringEnding line numberof original stringEnding columnnumber of originalstringFL4FL4FL4FL4FL4FL4FL4FL4The listing line number of the start of the text thatresulted from REPLACINGThe listing column number of the start of the text thatresulted from REPLACINGThe listing line number of the end of the text thatresulted from REPLACINGThe listing column number of the end of the text thatresulted from REPLACINGThe source file line number of the start of the text thatwas changed by REPLACINGThe source file column number of the start of the textthat was changed by REPLACINGThe source file line number of the end of the text thatwas changed by REPLACINGThe source file column number of the end of the text thatwas changed by REPLACINGSymbol record: X’0042’The following table shows the contents of the symbol record.Table 129. SYSADATA symbol recordField Size DescriptionSymbol ID FL4 Unique ID of symbolLine number FL4 The listing line number of the source record in which thesymbol is defined or declaredLevel XL1 True level-number of symbol (or relative level-number ofa data item within a structure). For <strong>COBOL</strong>, this can bein the range 01-49, 66 (<strong>for</strong> RENAMES items), 77, or 88 (<strong>for</strong>condition items).Qualification XL1indicatorX'00' Unique name; no qualification needed.X'01' This data item needs qualification. The name isnot unique within the program. This fieldapplies only when this data item is not thelevel-01 name.794 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 129. SYSADATA symbol record (continued)Field Size DescriptionSymbol typeXL1X'68' Class-name (Class-ID)X'58'X'40'X'20'X'10'X'08'X'81'Method-nameData-nameProcedure-nameMnemonic-nameProgram-nameReservedThe following are ORed into the above types, whenapplicable:X'04'ExternalX'02'GlobalSymbol attributeXL1X'01'NumericX'02'Elementary character of one of these classes:v Alphabeticv Alphanumericv DBCSv NationalX'03'GroupX'04'PointerX'05'Index data itemX'06'Index-nameX'07'ConditionX'0F'FileX'10'Sort fileX'17'Class-name (repository)X'18'Object reference|X'19'Currency-sign symbol|X'1A'XML schema nameAppendix G. <strong>COBOL</strong> SYSADATA file contents 795


Table 129. SYSADATA symbol record (continued)Field Size DescriptionClauses XL1 Clauses specified in symbol definition.For symbols that have a symbol attribute of Numeric(X'01'), Elementary character (X'02'), Group (X'03'),Pointer (X'04'), Index data item (X'05'), or Objectreference (X'18'):1... ....Value.1.. ....Indexed..1. ....Redefines...1 ....Renames.... 1...Occurs.... .1..Has Occurs keys.... ..1.Occurs Depending On.... ...1Occurs in parentFor both file types:1... ....Select.1.. ....Assign..1. ....Rerun...1 ....Same area.... 1...Same record area.... .1..Recording mode.... ..1.Reserved.... ...1Record796 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 129. SYSADATA symbol record (continued)Field Size DescriptionFor mnemonic-name symbols:01 CSP02 C0103 C0204 C0305 C0406 C0507 C0608 C0709 C0810 C0911 C1012 C1113 C1214 S0115 S0216 S0317 S0418 S0519 CONSOLE20 SYSIN|SYSIPT22 SYSOUT|SYSLST|SYSLIST24 SYSPUNCH|SYSPCH26 UPSI-027 UPSI-128 UPSI-229 UPSI-330 UPSI-431 UPSI-532 UPSI-633 UPSI-734 AFP-5AAppendix G. <strong>COBOL</strong> SYSADATA file contents 797


Table 129. SYSADATA symbol record (continued)Field Size DescriptionData flags 1 XL1 For both file types, and <strong>for</strong> symbols that have a symbolattribute of Numeric (X'01'), Elementary character(X'02'), Group (X'03'), Pointer (X'04'), Index data item(X'05'), or Object reference (X'18'):1... ....Redefined.1.. ....Renamed..1. ....Synchronized...1 ....Implicitly redefined.... 1...Date field.... .1..Implicit redefines.... ..1.FILLER.... ...1Level 77798 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 129. SYSADATA symbol record (continued)Field Size DescriptionData flags 2 XL1 For symbols that have a symbol attribute of Numeric(X'01'):1... ....Binary.1.. ....External floating point (of USAGE DISPLAY orUSAGE NATIONAL)..1. ....Internal floating point...1 ....Packed.... 1...External decimal (of USAGE DISPLAY or USAGENATIONAL).... .1..Scaled negative.... ..1.Numeric edited (of USAGE DISPLAY or USAGENATIONAL).... ...1Reserved <strong>for</strong> future useFor symbols that have a symbol attribute of Elementarycharacter (X'02') orGroup(X'03'):1... ....Alphabetic.1.. ....Alphanumeric..1. ....Alphanumeric edited...1 ....Group contains its own ODO object.... 1...DBCS item.... .1..Group variable length.... ..1.EGCS item.... ...1EGCS editedAppendix G. <strong>COBOL</strong> SYSADATA file contents 799


Table 129. SYSADATA symbol record (continued)Field Size DescriptionFor both file types:1... ....Object of ODO in record.1.. ....Subject of ODO in record..1. ....Sequential access...1 ....Random access.... 1...Dynamic access.... .1..Locate mode.... ..1.Record area.... ...1Reserved <strong>for</strong> future useField will be zero <strong>for</strong> all other data types.Data flags 3 XL1 For both file types:1... ....All records are the same length.1.. ....Fixed length..1. ....Variable length...1 ....Undefined.... 1...Spanned.... .1..Blocked.... ..1.Apply write only.... ...1Same sort merge areaField will be zero <strong>for</strong> all other data types.800 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 129. SYSADATA symbol record (continued)Field Size DescriptionFile organization XL1 For both file types:1... ....QSAM.1.. ....ASCII..1. ....Standard label...1 ....User label.... 1...VSAM sequential.... .1..VSAM indexed.... ..1.VSAM relative.... ...1Line sequentialUSAGE clauseSign clauseIndicatorsFL1FL1FL1Field will be zero <strong>for</strong> all other data types.X'00'X'01'X'02'X'03'X'04'X'05'X'06'X'07'X'08'X'09'X'0B'X'0A'X'00'X'01'X'02'X'03'X'04'X'01'X'02'USAGE IS DISPLAYUSAGE IS COMP-1USAGE IS COMP-2USAGE IS PACKED-DECIMAL or USAGE IS COMP-3USAGE IS BINARY, USAGE IS COMP, orUSAGE ISCOMP-4USAGE IS DISPLAY-1USAGE IS POINTERUSAGE IS INDEXUSAGE IS PROCEDURE-POINTERUSAGE IS OBJECT-REFERENCENATIONALFUNCTION-POINTERNo SIGN clauseSIGN IS LEADINGSIGN IS LEADING SEPARATE CHARACTERSIGN IS TRAILINGSIGN IS TRAILING SEPARATE CHARACTERHas JUSTIFIED clause. Right-justified attribute isin effect.Has BLANK WHEN ZERO clause.Appendix G. <strong>COBOL</strong> SYSADATA file contents 801


Table 129. SYSADATA symbol record (continued)Field Size DescriptionSize FL4 The size of this data item. The actual number of bytesthis item occupies in storage. If a DBCS item, the numberis in bytes, not characters. For variable-length items, thisfield will reflect the maximum size of storage reserved<strong>for</strong> this item by the compiler. Also known as the ″Lengthattribute.″Precision FL1 The precision of a fixed or float data itemScale FL1 The scale factor of a fixed data item. This is the numberof digits to the right of the decimal point.802 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 129. SYSADATA symbol record (continued)Field Size DescriptionBase locator type FL1 For host:01 Base Locator File02 Base Locator Working-Storage03 Base Locator Linkage Section05 Base Locator special regs07 Indexed by variable09 COMREG special reg10 UPSI switch13 Base Locator <strong>for</strong> Varloc items14 Base Locator <strong>for</strong> Extern data15 Base Locator alphanumeric FUNC16 Base Locator alphanumeric EVAL17 Base Locator <strong>for</strong> Object data19 Base Locator <strong>for</strong> Local-Storage20 Factory data21 XML-TEXT and XML-NTEXTFor Windows and AIX:01 Base Locator File02 Base Locator Linkage Section03 Base Locator <strong>for</strong> Varloc items04 Base Locator <strong>for</strong> Extern data05 Base Locator <strong>for</strong> Object data06 XML-TEXT and XML-NTEXT10 Base Locator Working-Storage11 Base Locator special regs12 Base Locator alphanumeric FUNC13 Base Locator alphanumeric EVAL14 Indexed by variable16 COMREG special reg17 UPSI switch18 Factory data22 Base Locator <strong>for</strong> Local-StorageAppendix G. <strong>COBOL</strong> SYSADATA file contents 803


Table 129. SYSADATA symbol record (continued)Field Size DescriptionDate <strong>for</strong>mat FL1 Date <strong>for</strong>mat:01 YY02 YYXX03 YYXXXX04 YYXXX05 YYYY06 YYYYXX07 YYYYXXXX08 YYYYXXX09 YYX10 YYYYX22 XXYY23 XXXXYY24 XXXYY26 XXYYYY27 XXXXYYYY28 XXXYYYY29 XYY30 XYYYYData flags 4 XL1 For symbols that have a symbol attribute of Numeric(X'01'):1... ....Numeric nationalFor symbols that have a symbol attribute of Elementarycharacter (X'02'):1... ....National.1.. ....National editedFor symbols that have a symbol attribute of Group(X'03'):1... ....Group-Usage NationalReserved FL3 Reserved <strong>for</strong> future use804 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 129. SYSADATA symbol record (continued)Field Size DescriptionAddressingin<strong>for</strong>mationFL4 For host, the Base Locator number and displacement:Bits 0-4UnusedStructuredisplacementBits 5-19Base Locator (BL) numberBits 20-31Displacement off Base LocatorFor Windows and AIX, the W-code SymId.AL4 Offset of symbol within structure. This offset is set to 0<strong>for</strong> variably located items.Parent displacement AL4 Byte offset from immediate parent of the item beingdefined.Parent ID FL4 The symbol ID of the immediate parent of the item beingdefined.Redefined ID FL4 The symbol ID of the data item that this item redefines,if applicable.Start-renamed ID FL4 If this item is a level-66 item, the symbol ID of thestarting <strong>COBOL</strong> data item that this item renames. If not alevel-66 item, this field is set to 0.End-renamed ID FL4 If this item is a level-66 item, the symbol ID of theending <strong>COBOL</strong> data item that this item renames. If not alevel-66 item, this field is set to 0.Program-namesymbol IDOCCURS minimumFL4FL4ID of the program-name of the program or theclass-name of the class where this symbol is defined.Minimum value <strong>for</strong> OCCURSParagraph IDOCCURS maximumFL4Proc-name ID <strong>for</strong> a paragraph-nameMaximum value <strong>for</strong> OCCURSSection IDProc-name ID <strong>for</strong> a section-nameDimensions FL4 Number of dimensionsCase bit vector XL4 The case of the characters in the symbol name isrepresented with one bit per character. Each bit has thefollowing meaning:0 Uppercase1 LowercaseBit 0 represents the case of the first character, bit 1represents the case of the second character, and so <strong>for</strong>th.Reserved CL8 Reserved <strong>for</strong> future useValue pairs count HL2 Count of value pairsSymbol name length HL2 Number of characters in the symbol nameAppendix G. <strong>COBOL</strong> SYSADATA file contents 805


Table 129. SYSADATA symbol record (continued)Field Size DescriptionPicture data length<strong>for</strong> data-nameorAssignment-namelength <strong>for</strong> file-nameHL2Number of characters in the picture data; zero if symbolhas no associated PICTURE clause. (Length of the PICTUREfield.) Length represents the field as it is found in thesource input. This length does not represent theexpanded field <strong>for</strong> PICTURE items that contain areplication factor. The maximum <strong>COBOL</strong> length <strong>for</strong> aPICTURE string is 50 bytes. Zero in this field indicates noPICTURE specified.Initial Value length<strong>for</strong> data-nameExternal class-namelength <strong>for</strong> CLASS-IDODO symbol nameID <strong>for</strong> data-nameHL2FL4Number of characters in the external file-name if this is afile-name. This is the DD name part of theassignment-name. Zero if file-name and ASSIGN USINGspecified.Number of characters in the symbol value; zero ifsymbol has no initial valueNumber of characters in the external class-name <strong>for</strong>CLASS-IDIf data-name, ID of the ODO symbol name; zero if ODOnot specifiedID of ASSIGNdata-name iffile-nameIf file-name, Symbol-ID <strong>for</strong> ASSIGN USING data-name; zeroif ASSIGN TO specifiedKeys count HL2 The number of keys definedIndex count HL2 Count of Index symbol IDs; zero if none specifiedSymbol name CL(n)Picture data string <strong>for</strong>data-nameorAssignment-name <strong>for</strong>file-nameCL(n)The PICTURE character string exactly as the user types itin. The character string includes all symbols, parentheses,and replication factor.The external file-name if this is a file-name. This is the DDname part of the assignment-name.Index ID list (n)FL4 ID of each index symbol nameKeys (n)XL8 This field contains data describing keys specified <strong>for</strong> anarray. The following three fields are repeated as manytimes as specified in the ’Keys count’ field....Key Sequence FL1 Ascending or descending indicator.X'00'DESCENDINGX'01' ASCENDING...Filler CL3 Reserved...Key ID FL4 The symbol ID of the data item that is the key field inthe arrayInitial Value data <strong>for</strong>data-nameExternal class-name<strong>for</strong> CLASS-IDCL(n)This field contains the data specified in the INITIALVALUE clause <strong>for</strong> this symbol. The following foursubfields are repeated according to the count in the’Value pairs count’ field. The total length of the data inthis field is contained in the ’Initial value length’ field.The external class-name <strong>for</strong> CLASS-ID....1st value length HL2 Length of first value806 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 129. SYSADATA symbol record (continued)Field Size Description...1st value data CL(n) 1st value.This field contains the literal (or figurative constant) as itis specified in the VALUE clause in the source file. Itincludes any beginning and ending delimiters, embeddedquotation marks, and SHIFT IN and SHIFT OUTcharacters. If the literal spans multiple lines, the lines areconcatenated into one long string. If a figurative constantis specified, this field contains the actual reserved word,not the value associated with that word....2nd value length HL2 Length of second value, zero if not a THRU value pair...2nd value data CL(n) 2nd value.This field contains the literal (or figurative constant) as itis specified in the VALUE clause in the source file. Itincludes any beginning and ending delimiters, embeddedquotation marks, and SHIFT IN and SHIFT OUTcharacters. If the literal spans multiple lines, the lines areconcatenated into one long string. If a figurative constantis specified, this field contains the actual reserved word,not the value associated with that word.Symbol cross-reference record: X’0044’The following table shows the contents of the symbol cross-reference record.Table 130. SYSADATA symbol cross-reference recordField Size DescriptionSymbol length HL2 The length of the symbolStatement definition FL4 The statement number where the symbol is defined ordeclaredFor VERB XREF only:Verb count - total number of references to this verb.Number ofreferences 1 HL2 The number of references in this record to the symbolfollowingCross-reference type XL1X’01’ ProgramX’02’X’03’X’04’X’05’ProcedureVerbSymbol or data-nameMethodX’06’ ClassReserved CL7 Reserved <strong>for</strong> future useSymbol name CL(n) The symbol. Variable length.Appendix G. <strong>COBOL</strong> SYSADATA file contents 807


Table 130. SYSADATA symbol cross-reference record (continued)Field Size Description...Reference flag CL1 For symbol or data-name references:C’ ’ Blank means reference onlyC’M’Modification reference flagFor Procedure type symbol references:C’A’C’D’C’E’C’G’C’P’C’T’ALTER (procedure-name)GO TO (procedure-name) DEPENDING ONEnd of range of (PERFORM) through(procedure-name)GO TO (procedure-name)PERFORM (procedure-name)(ALTER) TO PROCEED TO (procedure-name)C’U’ Use <strong>for</strong> debugging (procedure-name)...Statement number XL4 The statement number on which the symbol or verb isreferenced1. The reference flag field and the statement number field occur as many times as thenumber of references field dictates. For example, if there is a value of 10 in the numberof references field, there will be 10 occurrences of the reference flag and statementnumber pair <strong>for</strong> data-name, procedure, or program symbols, or 10 occurrences of thestatement number <strong>for</strong> verbs.Where the number of references would exceed the record size <strong>for</strong> the SYSADATA file,the record is continued on the next record. The continuation flag is set in the commonheader section of the record.Nested program record: X’0046’The following table shows the contents of the nested program record.Table 131. SYSADATA nested program recordField Size DescriptionStatement definition FL4 The statement number where the symbol is defined ordeclaredNesting level XL1 Program nesting levelProgram attributes XL11... ....Initial.1.. ....Common..1. ....PROCEDURE DIVISION using...1 1111Reserved <strong>for</strong> future useReserved XL1 Reserved <strong>for</strong> future useProgram-name length XL1 Length of the following fieldProgram-name CL(n) The program-name808 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Library record: X’0060’The following table shows the contents of the SYSADATA library record.Table 132. SYSADATA library recordField Size DescriptionNumber of members 1 HL2 Count of the number of COPY/INCLUDE code membersdescribed in this recordLibrary name length HL2 The length of the library nameLibrary volume HL2 The length of the library volume IDlengthConcatenation XL2 Concatenation number of the librarynumberLibrary ddname HL2 The length of the library ddnamelengthReserved CL4 Reserved <strong>for</strong> future useLibrary name CL(n) The name of the library from which the COPY/INCLUDEmember was retrievedLibrary volume CL(n) The volume identification of the volume where thelibrary residesLibrary ddname CL(n) The ddname (or equivalent) used <strong>for</strong> this library...COPY/BASIS member HL2 The library file ID of the name followingfile ID 2...COPY/BASIS name HL2 The length of the name followinglength...COPY/BASIS name CL(n) The name of the COPY/BASIS member that has been used1. If 10 COPY members are retrieved from a library, the ″Number of members″ field willcontain 10 and there will be 10 occurrences of the ″COPY/BASIS member file ID″ field,the ″COPY/BASIS name length″ field, and the ″COPY/BASIS name″ field.2. If COPY/BASIS members are retrieved from different libraries, a library record is writtento the SYSADATA file <strong>for</strong> each unique library.Statistics record: X’0090’The following table shows the contents of the statistics record.Table 133. SYSADATA statistics recordField Size DescriptionSource records FL4 The number of source records processedDATA DIVISION FL4 The number of DATA DIVISION statements processedstatementsPROCEDURE DIVISION FL4 The number of PROCEDURE DIVISION statements processedstatementsCompilation number HL2 Batch compilation numberError severity XL1 The highest error message severityAppendix G. <strong>COBOL</strong> SYSADATA file contents 809


Table 133. SYSADATA statistics record (continued)Field Size DescriptionFlagsXL11... ....End of Job indicator.1.. ....Class definition indicator..11 1111Reserved <strong>for</strong> future useEOJ severity XL1 The maximum return code <strong>for</strong> the compile jobProgram-name length XL1 The length of the program-nameProgram-name CL(n) Program-nameEVENTS record: X’0120’Events records are included in the ADATA file to provide compatibility withprevious levels of the compiler.Events records are of the following types:v Time stampv Processorv File endv Programv File IDv ErrorTable 134. SYSADATA EVENTS TIMESTAMP record layoutField Size DescriptionHeader CL12 Standard ADATA record headerRecord length HL2 Length of following EVENTS record data (excluding thishalfword)EVENTS record typeTIMESTAMP recordCL12C’TIMESTAMP’Blank separator CL1Revision level XL1Blank separator CL1Date XL8 YYYYMMDDHour XL2 HHMinutes XL2 MISeconds XL2 SSTable 135. SYSADATA EVENTS PROCESSOR record layoutField Size DescriptionHeader CL12 Standard ADATA record headerRecord length HL2 Length of following EVENTS record data (excluding thishalfword)810 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 135. SYSADATA EVENTS PROCESSOR record layout (continued)Field Size DescriptionEVENTS record type CL9 C’PROCESSOR’PROCESSOR recordBlank separator CL1Revision level XL1Blank separator CL1Output file ID XL1Blank separator CL1Line-class indicator XL1Table 136. SYSADATA EVENTS FILE END record layoutField Size DescriptionHeader CL12 Standard ADATA record headerRecord length HL2 Length of following EVENTS record data (excluding thishalfword)EVENTS record type CL7 C’FILEEND’FILE END recordBlank separator CL1Revision level XL1Blank separator CL1Input file IDXL1Blank separator CL1Expansion indicator XL1Table 137. SYSADATA EVENTS PROGRAM record layoutField Size DescriptionHeader CL12 Standard ADATA record headerRecord length HL2 Length of following EVENTS record data (excluding thishalfword)EVENTS record type CL7 C’PROGRAM’PROGRAM recordBlank separator CL1Revision level XL1Blank separator CL1Output file ID XL1Blank separator CL1Program input recordnumberXL1Table 138. SYSADATA EVENTS FILE ID record layoutField Size DescriptionHeader CL12 Standard ADATA record headerAppendix G. <strong>COBOL</strong> SYSADATA file contents 811


Table 138. SYSADATA EVENTS FILE ID record layout (continued)Field Size DescriptionRecord length HL2 Length of following EVENTS record data (excluding thishalfword)EVENTS record type CL7 C’FILEID’FILE ID recordBlank separator CL1Revision level XL1Blank separator CL1Input source file ID XL1 File ID of source fileBlank separator CL1Reference indicator XL1Blank separator CL1Source file name H2lengthBlank separator CL1Source file name CL(n)Table 139. SYSADATA EVENTS ERROR record layoutField Size DescriptionHeader CL12 Standard ADATA record headerRecord length HL2 Length of following EVENTS record data (excluding thishalfword)EVENTS record type CL5 C’ERROR’ERROR recordBlank separator CL1Revision level XL1Blank separator CL1Input source file ID XL1 File ID of source fileBlank separator CL1Annot class XL1 Annot-class message placementBlank separator CL1Error input record XL10numberBlank separator CL1Error start line XL10numberBlank separator CL1Error token start XL1 Column number of error token startnumberBlank separator CL1Error end line XL10numberBlank separator CL1812 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Table 139. SYSADATA EVENTS ERROR record layout (continued)Field Size DescriptionError token end XL1 Column number of error token endnumberBlank separator CL1Error message ID XL9numberBlank separator CL1Error message XL1severity codeBlank separator CL1Error message XL2severity level numberBlank separator CL1Error message length HL3Blank separator CL1Error message text CL(n)Appendix G. <strong>COBOL</strong> SYSADATA file contents 813


814 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Appendix H. Using sample programsThe sample programs, which are included on your product tape, demonstratemany language elements and concepts of <strong>COBOL</strong>.This in<strong>for</strong>mation contains the following items:v Overview of the programs, including program charts <strong>for</strong> two of the samplesv Format and sample of the input datav Sample of reports producedv In<strong>for</strong>mation about how to run the programsv List of the language elements and concepts that are illustratedPseudocode and other comments about the programs are included in the programprolog, which you can obtain in a program listing.There are three sample programs:v IGYTCARA is an example of using QSAM files and VSAM indexed files, andshows how to use many <strong>COBOL</strong> intrinsic functions.v IGYTCARB is an example of using IBM Interactive System Product Facility(ISPF).v IGYTSALE is an example of using several of the features of the LanguageEnvironment callable services.IGYTCARA: batch applicationRELATED CONCEPTS“IGYTCARA: batch application”“IGYTCARB: interactive program” on page 819“IGYTSALE: nested program application” on page 822A company that has several local offices wants to establish employee carpools.Application IGYTCARA validates the transaction-file entries (QSAM sequential fileprocessing) and updates a master file (VSAM indexed file processing).This batch application does two tasks:v Produces reports of employees who can share rides from the same homelocation to the same work locationv Updates the carpool data:– Adds data <strong>for</strong> new employees– Changes in<strong>for</strong>mation <strong>for</strong> participating employees– Deletes employee records– Lists update requests that are not validThe following diagram shows the parts of the application and how they areorganized:© Copyright IBM Corp. 1991, 2009 815


RELATED TASKS“Preparing to run IGYTCARA” on page 818RELATED REFERENCES“Input data <strong>for</strong> IGYTCARA”“Report produced by IGYTCARA” on page 817“Language elements and concepts that are illustrated” on page 829Input data <strong>for</strong> IGYTCARAAs input to the program, the company collected in<strong>for</strong>mation from interestedemployees, coded the in<strong>for</strong>mation, and produced an input file. Here is an exampleof the <strong>for</strong>mat of the input file (spaces between fields are left out, as they would bein your input file) with an explanation of each item.1. Transaction code2. Shift3. Home code816 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


4. Work code5. Commuter name6. Home address7. Home phone8. Work phone9. Home location code10. Work location code11. Driving status codeThis sample below shows a section of the input file:A10111ROBERTS AB1021 CRYSTAL COURTSAN FRANCISCOCA9990141555501904155551387H1W1DA20212KAHN DE789 EMILY LANE SAN FRANCISCOCA9992141555518904155552589H2W2DP48899 99ASDFG0005557890123ASDFGHJ TR10111ROBERTS AB1221 CRYSTAL COURTSAN FRANCISCOCA9990141555501904155551387H1W1DA20212KAHN DE789 EMILY LANE SAN FRANCISCOCA9992141555518904155552589H2W2DD20212KAHN DED20212KAHN DEA20212KAHN DE789 EMILY LANE SAN FRANCISCOCA9992141555518904155552589H2W2DA10111BONNICK FD1025 FIFTH AVENUE SAN FRANCISCOCA9990541555595904155557895H8W3A10111PETERSON SW435 THIRD AVENUE SAN FRANCISCOCA9990541555546904155553717H3W4...Report produced by IGYTCARAThe following sample shows the first page of the output report produced byIGYTCARA. Your actual output might vary slightly in appearance, depending onyour system.1REPORT #: IGYTCAR1 COMMUTER FILE UPDATE LIST PAGE #: 1-PROGRAM #: IGYTCAR1 RUN TIME: 01:40 RUN DATE: 11/24/2003-========================================================================================================================| RE-| SHIFT | | | | |STA-|TRANS|CORD|HOME CODE| COMMUTER | HOME | HOME PHONE | HOME LOCATION JUNCTION |TUS | TRANS. ERRORCODE |TYPE|WORK CODE| NAME | ADDRESS | WORK PHONE | WORK LOCATION JUNCTION |CODE|========================================================================================================================A NEW 1 01 11 ROBERTS AB 1021 CRYSTAL COURT (415) 555-0190 RODNEY/CRYSTAL DSAN FRANCISCO CA 99901 (415) 555-1387 BAYFAIR PLAZA------------------------------------------------------------------------------------------------------------------------A NEW 2 02 12 KAHN DE 789 EMILY LANE (415) 555-1890 COYOTE DSAN FRANCISCO CA 99921 (415) 555-2589 14TH STREET/166TH AVENUE------------------------------------------------------------------------------------------------------------------------P 4 88 99 (000) 555-7890 HOME CODE ' ' NOT FOUND. T99 ASDFG (123) ASD-FGHJ WORK CODE ' ' NOT FOUND. TRANSACT. CODESHIFT CODEHOME LOC. CODEWORK LOC. CODELAST NAMEINITIALSADDRESSCITYSTATE CODEZIPCODEHOME PHONEWORK PHONEHOME JUNCTIONWORK JUNCTIONDRIVING STATUS------------------------------------------------------------------------------------------------------------------------R OLD 1 01 11 ROBERTS AB 1021 CRYSTAL COURT (415) 555-0190 RODNEY/CRYSTAL DSAN FRANCISCO CA 99901 (415) 555-1387 BAYFAIR PLAZANEW 1 01 11 ROBERTS AB 1221 CRYSTAL COURT (415) 555-0190 RODNEY/CRYSTAL DSAN FRANCISCO CA 99901 (415) 555-1387 BAYFAIR PLAZA------------------------------------------------------------------------------------------------------------------------A 2 02 12 KAHN DE 789 EMILY LANE (415) 555-1890 COYOTE DSAN FRANCISCO CA 99921 (415) 555-2589 14TH STREET/166TH AVENUE DUPLICATE REC.------------------------------------------------------------------------------------------------------------------------D OLD 2 02 12 KAHN DE 789 EMILY LANE (415) 555-1890 COYOTE DSAN FRANCISCO CA 99921 (415) 555-2589 14TH STREET/166TH AVENUE------------------------------------------------------------------------------------------------------------------------D 2 02 12 KAHN DE REC. NOT FOUND------------------------------------------------------------------------------------------------------------------------A NEW 2 02 12 KAHN DE 789 EMILY LANE (415) 555-1890 COYOTE DSAN FRANCISCO CA 99921 (415) 555-2589 14TH STREET/166TH AVENUE------------------------------------------------------------------------------------------------------------------------A NEW 1 01 11 BONNICK FD 1025 FIFTH AVENUE (415) 555-9590 RODNEYSAN FRANCISCO CA 99905 (415) 555-7895 17TH FREEWAY SAN LEANDRO------------------------------------------------------------------------------------------------------------------------A NEW 1 01 11 PETERSON SW 435 THIRD AVENUE (415) 555-4690 RODNEY/THIRD AVENUEAppendix H. Using sample programs 817


Preparing to run IGYTCARAAll files required by the IGYTCARA program (IGYTCARA, IGYTCODE, andIGYTRANX) are supplied on the product installation tape. These files are locatedin the IGY.V4R2M0.SIGYSAMP data set.Data set and procedure names might be changed at installation time. You shouldcheck with your system programmer to verify these names.Do not change these options on the CBL statement in the source file <strong>for</strong>IGYTCARA:v NOADVv NODYNAMv NONAMEv NONUMBERv QUOTEv SEQUENCEWith these options in effect, the program will not cause any diagnostic messages tobe issued. You can use the sequence number string in the source file to search <strong>for</strong>the language elements used.RELATED CONCEPTS“IGYTCARA: batch application” on page 815RELATED TASKS“Running IGYTCARA”RELATED REFERENCES“Input data <strong>for</strong> IGYTCARA” on page 816“Report produced by IGYTCARA” on page 817“Language elements and concepts that are illustrated” on page 829Running IGYTCARAThe following procedure compiles, link-edits, and runs the IGYTCARA program. Ifyou want only to compile or only to compile and link-edit the program, you needto change the IGYWCLG cataloged procedure.To run IGYTCARA under z/<strong>OS</strong>, use JCL to define a VSAM cluster and compile theprogram. Insert the in<strong>for</strong>mation specific to your system and installation in thefields that are shown in lowercase letters (accounting in<strong>for</strong>mation, volume serialnumber, unit name, cluster prefix). These examples use the nameIGYTCAR.MASTFILE; you can use another name if you want to.1. Use this JCL to create the required VSAM cluster:818 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>//CREATE JOB (acct-info),'IGYTCAR CREATE VSAM',MSGLEVEL=(1,1),// TIME=(0,29)//CREATE EXEC PGM=IDCAMS//VOL1 DD VOL=SER=your-volume-serial,UNIT=your-unit,DISP=SHR//SYSPRINT DD SYSOUT=A//SYSIN DD *DELETE your-prefix.IGYTCAR.MASTFILE -FILE(VOL1) -PURGEDEFINE CLUSTER -(NAME(your-prefix.IGYTCAR.MASTFILE) -


*VOLUME(your-volume-serial) -FILE(VOL1) -INDEXED -RECSZ(80 80) -KEYS(16 0) -CYLINDERS(2))To remove any existing cluster, a DELETE is issued be<strong>for</strong>e the VSAM cluster iscreated.2. Use the following JCL to compile, link-edit, and run the IGYTCARA program://IGYTCARA JOB (acct-info),'IGYTCAR',MSGLEVEL=(1,1),TIME=(0,29)//TEST EXEC IGYWCLG//<strong>COBOL</strong>.SYSLIB DD DSN=IGY.V4R2M0.SIGYSAMP,DISP=SHR//<strong>COBOL</strong>.SYSIN DD DSN=IGY.V4R2M0.SIGYSAMP(IGYTCARA),DISP=SHR//GO.SYSOUT DD SYSOUT=A//GO.COMMUTR DD DSN=your-prefix.IGYTCAR.MASTFILE,DISP=SHR//GO.LOCCODE DD DSN=IGY.V4R2M0.SIGYSAMP(IGYTCODE),DISP=SHR//GO.UPDTRANS DD DSN=IGY.V4R2M0.SIGYSAMP(IGYTRANX),DISP=SHR//GO.UPDPRINT DD SYSOUT=A,DCB=BLKSIZE=133//RELATED TASKSChapter 10, “Processing VSAM files,” on page 179RELATED REFERENCES“Compile, link-edit, and run procedure (IGYWCLG)” on page 253IGYTCARB: interactive programIGYTCARB contains an interactive program <strong>for</strong> entering carpool data by using IBMInteractive System Productivity Facility (ISPF) to invoke Dialog Manager and<strong>Enterprise</strong> <strong>COBOL</strong>. IGYTCARB creates a file that can be used as input <strong>for</strong> acarpool listing or matching program such as IGYTCARA.The input data <strong>for</strong> IGYTCARB is the same as that <strong>for</strong> IGYTCARA. IGYTCARB letsyou append to the in<strong>for</strong>mation in your input file by using an ISPF panel. Anexample of the panel used by IGYTCARB is shown below:--------------------------- CARPOOL DATA ENTRY -------------------------------New Data EntryPrevious EntryType =======> - A, R, or D AShift ======> - 1, 2, or 3 1Home Code ==> -- 2 Chars 01Work Code ==> -- 2 Chars 11Name =======> --------- 9 Chars POPOWICHInitials ===> -- 2 Chars ADAddress ====> ------------------ 18 Chars 134 SIXTH AVENUECity =======> ------------- 13 Chars SAN FRANCISC<strong>OS</strong>tate ======> -- 2 Chars CAZip Code ===> ----- 5 Chars 99903Home Phone => ---------- 10 Chars 4155553390Work Phone => ---------- 10 Chars 4155557855Home Jnc code > -- 2 Chars H3Work Jnc Code > -- 2 Chars W7Commuter Stat > -D, R or blankRELATED TASKS“Preparing to run IGYTCARB” on page 820Appendix H. Using sample programs 819


Preparing to run IGYTCARBRun the IGYTCARB program under Interactive System Productivity Facility (ISPF).All files required by IGYTCARB (IGYTCARB, IGYTRANB, and IGYTPNL) aresupplied on the product installation tape in the IGY.V4R2M0.SIGYSAMP data set.Data-set names and procedure-names might be changed at installation time. Checkwith your system programmer to verify the names.Do not change the following options in the CBL statement in the source file <strong>for</strong>IGYTCARB:v NONUMBERv QUOTEv SEQUENCEWith these options in effect, the program will not cause any diagnostic messages tobe issued. You can use the sequence number string in the source file to search <strong>for</strong>language elements.RELATED CONCEPTS“IGYTCARB: interactive program” on page 819RELATED TASKS“Running IGYTCARB”RELATED REFERENCES“Language elements and concepts that are illustrated” on page 829Running IGYTCARBThe following procedure compiles, link-edits, and runs the IGYTCARB program. Ifyou want only to compile or only to compile and link-edit the program, you needto change the procedure.To run IGYTCARB under z/<strong>OS</strong>, do the following steps:1. Using the ISPF editor, change the ISPF/PDF Primary Option Panel (ISR@PRIM)or some other panel to include the IGYTCARB invocation. Panel ISR@PRIM isin your site’s PDF panel data set (normally ISRPLIB).The following example shows an ISR@PRIM panel modified, in two identifiedlocations, to include the IGYTCARB invocation. If you add or change an optionin the upper portion of the panel definition, you must also add or change thecorresponding line on the lower portion of the panel.%---------------------- ISPF/PDF PRIMARY OPTION PANEL ------------------------%OPTION ===>_ZCMD +% +USERID - &ZUSER% 0 +ISPF PARMS - Specify terminal and user parameters +TIME - &ZTIME% 1 +BROWSE - Display source data or output listings +TERMINAL - &ZTERM% 2 +EDIT - Create or change source data +PF KEYS - &ZKEYS% 3 +UTILITIES - Per<strong>for</strong>m utility functions% 4 +FOREGROUND - Invoke language processors in <strong>for</strong>eground% 5 +BATCH - Submit to batch <strong>for</strong> language processing% 6 +COMMAND - Enter TSO or Workstation commands% 7 +DIALOG TEST - Per<strong>for</strong>m dialog testing% 8 +LM UTILITIES- Per<strong>for</strong>m library management utility functions% C +IGYTCARB - Run IGYTCARB UPDATE TRANSACTION PROGRAM (1)% T +TUTORIAL - Display in<strong>for</strong>mation about ISPF/PDF% X +EXIT - Terminate using console, log, and list defaults820 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


%%+Enter%END+command to terminate ISPF.%)INIT.HELP = ISR00003&ZPRIM = YES /* ALWAYS A PRIMARY OPTION MENU */&ZHTOP = ISR00003 /* TUTORIAL TABLE OF CONTENTS */&ZHINDEX = ISR91000 /* TUTORIAL INDEX - 1ST PAGE */VPUT (ZHTOP,ZHINDEX) PROFILE)PROC&Z1 = TRUNC(&ZCMD,1)IF (&Z1 &notsym.= '.')&ZSEL = TRANS( TRUNC (&ZCMD,'.')0,'PANEL(ISPOPTA)'1,'PGM(ISRBRO) PARM(ISRBRO01)'2,'PGM(ISREDIT) PARM(P,ISREDM01)'3,'PANEL(ISRUTIL)'4,'PANEL(ISRFPA)'5,'PGM(ISRJB1) PARM(ISRJPA) NOCHECK'6,'PGM(ISRPCC)'7,'PGM(ISRYXDR) NOCHECK'8,'PANEL(ISRLPRIM)'C,'PGM(IGYTCARB)' (2)T,'PGM(ISPTUTOR) PARM(ISR00000)'' ',' 'X,'EXIT'*,'?' )&ZTRAIL = .TRAILIF (&Z1 = '.') .msg = ISPD141)ENDAs indicated by (1) in this example, you add IGYTCARB to the upper portionof the panel by entering:% C +IGYTCARB - Run IGYTCARB UPDATE TRANSACTION PROGRAMYou add the corresponding line on the lower portion of the panel, indicated by(2), by entering:C,'PGM(IGYTCARB)'2. Place ISR@PRIM (or your other modified panel) and IGYTPNL in a library andmake this library the first library in the ISPPLIB concatenation.3. Comment sequence line IB2200 and uncomment sequence line IB2210 inIGYTCARB. (The OPEN EXTEND verb is supported under z/<strong>OS</strong>.)4. Compile and link-edit IGYTCARB and place the resulting load module in yourLOADLIB.5. Allocate ISPLLIB by using the following command:ALLOCATE FILE(ISPLLIB) DATASET(DSN1, SYS1.COBLIB, DSN2) SHR REUSEHere DSN1 is the library name of the LOADLIB from step 4. DSN2 is yourinstalled ISPLLIB.6. Allocate the input and output data sets by using the following command:ALLOCATE FILE(UPDTRANS) DA('IGY.V4R2M0.SIGYSAMP(IGYTRANB)') SHR REUSE7. Allocate ISPPLIB by using the following command:ALLOCATE FILE(ISPPLIB) DATASET(DSN3, DSN4) SHR REUSEHere DSN3 is the library containing the modified panels. DSN4 is the ISPF panellibrary.8. Invoke IGYTCARB by using your modified panel.RELATED REFERENCESISPF Dialog Developer’s <strong>Guide</strong> and ReferenceAppendix H. Using sample programs 821


IGYTSALE: nested program applicationApplication IGYTSALE tracks product sales and sales commissions <strong>for</strong> asporting-goods distributor.This nested program application does the following tasks:1. Keeps a record of the product line, customers, and number of salespeople. Thisdata is stored in a file called IGYTABLE.2. Maintains a file that records valid transactions and transaction errors. Alltransactions that are not valid are flagged, and the results are printed in areport. Transactions to be processed are in a file called IGYTRANA.3. Processes transactions and report sales by location.4. Records an individual’s sales per<strong>for</strong>mance and commission, and prints theresults in a report.5. Reports the sale and shipment dates in local time and UTC (Universal TimeCoordinate), and calculates the response time.The following diagram shows the parts of the application as a hierarchy:The following diagram shows how the parts are nested:822 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Preparing to run IGYTSALE” on page 828RELATED REFERENCES“Input data <strong>for</strong> IGYTSALE”“Reports produced by IGYTSALE” on page 825“Language elements and concepts that are illustrated” on page 829Input data <strong>for</strong> IGYTSALEAs input to our program, the distributor collected in<strong>for</strong>mation about its customers,salespeople, and products, coded the in<strong>for</strong>mation, and produced an input file.This input file, called IGYTABLE, is loaded into three separate tables <strong>for</strong> useduring transaction processing. The <strong>for</strong>mat of the file is as follows, with anexplanation of the items below:1. Record type2. Customer code3. Customer name4. Product codeAppendix H. Using sample programs 823


5. Product description6. Product unit price7. Salesperson number8. Salesperson name9. Date of hire10. Commission rateThe value of field 1 (C, P, or S) determines the <strong>for</strong>mat of the input record. Thefollowing sample shows a section of IGYTABLE:S1111Edyth Phillips 062484042327S1122Chuck Morgan 052780084425S1133Art Tung 022882061728S1144Billy Jim Bob 010272121150S1155Chris Preston 122083053377S1166Al Willie Roz 111276100000P01Footballs 0000620P02Football Equipment 0032080P03Football Uni<strong>for</strong>m 0004910P04Basketballs 0002220P05Basketball Rim/Board0008830P06Basketball Uni<strong>for</strong>m 0004220C01L. A. SportsC02Gear UpC03Play OutdoorsC04Sports 4 YouC05Sports R USC06Stay ActiveC07Sport ShopC08Stay SportyC09Hot SportsC10The SportsmanC11Playing BallC12Sports Play...In addition, the distributor collected in<strong>for</strong>mation about sales transactions. Eachtransaction represents an individual salesperson’s sales to a particular customer.The customer can purchase from one to five items during each transaction. Thetransaction in<strong>for</strong>mation is coded and put into an input file, called IGYTRANA. The<strong>for</strong>mat of this file is as follows, with an explanation of the items below:1. Sales order number2. Invoiced items (number of different items ordered)3. Date of sale (year month day hour minutes seconds)4. Sales area5. Salesperson number6. Customer code7. Date of shipment (year month day hour minutes seconds)8. Product code9. Quantity sold824 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Fields 8 and 9 occur one to eight times depending on the number of different itemsordered (field 2). The following sample shows a section of IGYTRANA:A00001119900227010101CNTRL VALLEY11442019900228259999A00004119900310100530CNTRL VALLEY11441019900403150099A00005119900418222409CNTRL VALLEY11441219900419059900A00006119900523151010CNTRL VALLEY11442019900623250004419990324591515SAN DIEGO 11615 60200132200110522045100B11114419901111003301SAN DIEGO 11661519901114260200132200110522041100A00007119901115003205CNTRL VALLEY11332019901117120023C00125419900118101527SF BAY AREA 11331519900120160200112200250522145111B11116419901201132013SF BAY AREA 11331519901203060200102200110522045102B11117319901201070833SAN Diego 1165661990120333020o132200120522041100B11118419901221191544SAN DIEGO 11661419901223160200142200130522040300B11119419901210211544SAN DIEGO 11221219901214060200152200160522050500B11120419901212000816SAN DIEGO 11220419901213150200052200160522040100B11121419901201131544SAN DIEGO 11330219901203120200112200140522250100B11122419901112073312SAN DIEGO 11221019901113100200162200260522250100B11123919901110123314SAN DIEGO 11660919901114260200270500110522250100140010B11124219901313510000SAN DIEGO 116611 1 0200042200120a22141100B11125419901215012510SAN DIEGO 11661519901216110200162200130522141111B11126119901111000034SAN DIEGO 11331619901113260022B11127119901110154100SAN DIEGO 11221219901113122000B11128419901110175001SAN DIEGO 11661519901113260200132200160521041104...Reports produced by IGYTSALEThe figures referenced below are samples of IGYTSALE output.The program records the following data in reports:v Transaction errorsv Sales by product and areav Individual sales per<strong>for</strong>mance and commissionsv Response time between the sale date and the date the sold products are shippedYour output might vary slightly in appearance, depending on your system.“Example: IGYTSALE transaction errors”“Example: IGYTSALE sales analysis by product by area” on page 826“Example: IGYTSALE sales and commissions” on page 827“Example: IGYTSALE response time from sale to ship” on page 827Example: IGYTSALE transaction errorsThe following sample of IGYTSALE output shows transaction errors in the lastcolumn.Day of Report: Tuesday <strong>COBOL</strong> SPORTS 11/24/2003 03:12 Page: 1Invalid Edited TransactionsSales Inv. Sales Sales Sales Cust. Product And Quantity Sold ShipOrder Items Time Stamp Area Pers Code Date Stamp----- ----- -------------- ----------- ----- ----- ------------------------- ------------4 19990324591515 SAN DIEGO 116 15 60200132200110522045100 Error Descriptions-Sales order number is missing-Date of sale time stamp is invalid-Salesperson number not numeric-Product code not in product-table-Date of ship time stamp is invalidB11117 3 19901201070833 SAN Diego 1165 66 33020o132200120522041100 19901203 Error Descriptions-Sales area not in area-table-Salesperson not in sales-per-table-Customer code not in customer-table-Product code not in product-table-Quantity sold not numericB11123 9 19901110123314 SAN DIEGO 1166 09 260200270500110522250100140010 19901114 Error Descriptions-Invoiced items is invalid-Product and quantity not checked-Date of ship time stamp is invalidB11124 2 19901313510000 SAN DIEGO 1166 11 1 0200042200120a22141100 Error Descriptions-Date of sale time stamp is invalidAppendix H. Using sample programs 825


-Product code is invalid-Date of ship time stamp is invalid133 81119110000 L<strong>OS</strong> ANGELES 1166 10 040112110210160321251104 Error Descriptions-Sales order number is invalid-Invoiced items is invalid-Date of sale time stamp is invalid-Product and quantity not checked-Date of ship time stamp is invalidC11133 4 1990111944 1166 10 040112110210160321251104 Error Descriptions-Date of sale time stamp is invalid-Sales area is missing-Date of ship time stamp is invalidC11138 4 19901117091530 L<strong>OS</strong> ANGELES 1155 113200102010260321250004 19901119 Error Descriptions-Customer code is invalidD00009 9 19901201222222 CNTRL COAST 115 19 141 1131221 19901202 Error Descriptions-Invoiced items is invalidExample: IGYTSALE sales analysis by product by areaThe following sample of IGYTSALE output shows sales by product and area.Day of Report: Tuesday <strong>COBOL</strong> SPORTS 11/24/2003 03:12 Page: 1Sales Analysis By Product By AreaAreas of Sale| | CNTRL COAST | CNTRL VALLEY | L<strong>OS</strong> ANGELES | NORTH COAST | SAN DIEGO | SF BAY AREA | || Product Codes | | | | | | | Product Totals |==================================================================================================================================|Product Number 04 | | | | | | | ||Basketballs | | | | | | | || Units Sold | | | 433 | | 2604 | 5102 | 8139 || Unit Price | | | 22.20 | | 22.20 | 22.20 | || Amount of Sale | | | $9,612.60 | | $57,808.80 | $113,264.40 | $180,685.80 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 05 | | | | | | | ||Basketball Rim/Board| | | | | | | || Units Sold | | 9900 | 2120 | 11 | 2700 | | 14731 || Unit Price | | 88.30 | 88.30 | 88.30 | 88.30 | | || Amount of Sale | | $874,170.00 | $187,196.00 | $971.30 | $238,410.00 | | $1,300,747.30 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 06 | | | | | | | ||Basketball Uni<strong>for</strong>m | | | | | | | || Units Sold | | | | 990 | 200 | 200 | 1390 || Unit Price | | | | 42.20 | 42.20 | 42.20 | || Amount of Sale | | | | $41,778.00 | $8,440.00 | $8,440.00 | $58,658.00 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 10 | | | | | | | ||Baseball Cage | | | | | | | || Units Sold | 45 | | 3450 | 16 | 200 | 3320 | 7031 || Unit Price | 890.00 | | 890.00 | 890.00 | 890.00 | 890.00 | || Amount of Sale | $40,050.00 | |$3,070,500.00 | $14,240.00 | $178,000.00 |$2,954,800.00 | $6,257,590.00 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 11 | | | | | | | ||Baseball Uni<strong>for</strong>m | | | | | | | || Units Sold | 10003 | | 3578 | | 2922 | 2746 | 19249 || Unit Price | 45.70 | | 45.70 | | 45.70 | 45.70 | || Amount of Sale | $457,137.10 | | $163,514.60 | | $133,535.40 | $125,492.20 | $879,679.30 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 12 | | | | | | | ||Softballs | | | | | | | || Units Sold | 10 | 137 | 2564 | 13 | 2200 | 22 | 4946 || Unit Price | 1.40 | 1.40 | 1.40 | 1.40 | 1.40 | 1.40 | || Amount of Sale | $14.00 | $191.80 | $3,589.60 | $18.20 | $3,080.00 | $30.80 | $6,924.40 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 13 | | | | | | | ||Softball Bats | | | | | | | || Units Sold | 3227 | | 3300 | 1998 | 5444 | 99 | 14068 || Unit Price | 12.60 | | 12.60 | 12.60 | 12.60 | 12.60 | || Amount of Sale | $40,660.20 | | $41,580.00 | $25,174.80 | $68,594.40 | $1,247.40 | $177,256.80 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 14 | | | | | | | ||Softball Gloves | | | | | | | || Units Sold | 1155 | | 136 | 3119 | 3833 | 5152 | 13395 || Unit Price | 12.00 | | 12.00 | 12.00 | 12.00 | 12.00 | || Amount of Sale | $13,860.00 | | $1,632.00 | $37,428.00 | $45,996.00 | $61,824.00 | $160,740.00 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 15 | | | | | | | ||Softball Cage | | | | | | | || Units Sold | 997 | 99 | 2000 | | 2400 | | 5496 || Unit Price | 890.00 | 890.00 | 890.00 | | 890.00 | | || Amount of Sale | $887,330.00 | $88,110.00 |$1,780,000.00 | |$2,136,000.00 | | $4,891,440.00 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 16 | | | | | | | ||Softball Uni<strong>for</strong>m | | | | | | | || Units Sold | 44 | | 465 | 16 | 6165 | 200 | 6890 || Unit Price | 45.70 | | 45.70 | 45.70 | 45.70 | 45.70 | || Amount of Sale | $2,010.80 | | $21,250.50 | $731.20 | $281,740.50 | $9,140.00 | $314,873.00 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 25 | | | | | | | ||RacketBalls | | | | | | | || Units Sold | 1001 | 10003 | 1108 | 8989 | 200 | 522 | 21823 || Unit Price | 0.60 | 0.60 | 0.60 | 0.60 | 0.60 | 0.60 | || Amount of Sale | $600.60 | $6,001.80 | $664.80 | $5,393.40 | $120.00 | $313.20 | $13,093.80 |----------------------------------------------------------------------------------------------------------------------------------|Product Number 26 | | | | | | | ||Racketball Rackets | | | | | | | || Units Sold | 21 | | 862 | 194 | 944 | 31 | 2052 || Unit Price | 12.70 | | 12.70 | 12.70 | 12.70 | 12.70 | || Amount of Sale | $266.70 | | $10,947.40 | $2,463.80 | $11,988.80 | $393.70 | $26,060.40 |----------------------------------------------------------------------------------------------------------------------------------==================================================================================================================================| Total Units Sold | 16503 | 20139 | 20016 | 15346 | 29812 | 17394 * 119210 *| Total Sales |$1,441,929.40 | $968,473.60 |$5,290,487.50 | $128,198.70 |$3,163,713.90 |$3,274,945.70 * $14,267,748.80 *826 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Example: IGYTSALE sales and commissionsThe following sample of IGYTSALE output shows sales per<strong>for</strong>mance andcommissions by salesperson.Day of Report: Tuesday <strong>COBOL</strong> SPORTS 11/24/2003 03:12 Page: 1Sales and Commission ReportSalesperson: Billy Jim BobCustomers: Number of Products Total <strong>for</strong> Discount Discount CommissionOrders Ordered Order (if any) Amount Earned-------------------- --------- -------- -------------- -------- ----------- -----------Sports Stop 3 10117 $6,161.40 2.25% $138.63 $746.45The Sportsman 1 99 $88,110.00 5.06% $4,458.36 $10,674.52Sports Play 1 9900 $874,170.00 7.59% $66,349.50 $105,905.69--------- -------- -------------- ----------- -----------Totals: 5 20116 $968,441.40 $70,946.49 $117,326.66Salesperson: Willie Al RozCustomers: Number of Products Total <strong>for</strong> Discount Discount CommissionOrders Ordered Order (if any) Amount Earned-------------------- --------- -------- -------------- -------- ----------- -----------Winners Club 4 13998 $1,572,775.90 7.59% $119,373.69 $157,277.59Winning Sports 1 3222 $48,777.20 3.38% $1,648.66 $4,877.72The Sportsman 1 1747 $27,415.50 3.38% $926.64 $2,741.55Play Outdoors 1 2510 $18,579.60 3.38% $627.99 $1,857.96--------- -------- -------------- ----------- -----------Totals: 7 21477 $1,667,548.20 $122,576.98 $166,754.82Salesperson: Art TungCustomers: Number of Products Total <strong>for</strong> Discount Discount CommissionOrders Ordered Order (if any) Amount Earned-------------------- --------- -------- -------------- -------- ----------- -----------Sports Stop 1 23 $32.20 2.25% $.72 $1.98Winners Club 2 16057 $2,274,885.00 7.59% $172,663.77 $140,424.10Gear Up 1 3022 $107,144.00 7.59% $8,132.22 $6,613.78Sports Club 1 22 $279.40 2.25% $6.28 $17.24Sports Fans Shop 1 1044 $20,447.30 3.38% $691.11 $1,262.17L. A. Sports 1 1163 $979,198.10 7.59% $74,321.13 $60,443.94--------- -------- -------------- ----------- -----------Totals: 7 21331 $3,381,986.00 $255,815.23 $208,763.21Salesperson: Chuck MorganCustomers: Number of Products Total <strong>for</strong> Discount Discount CommissionOrders Ordered Order (if any) Amount Earned-------------------- --------- -------- -------------- -------- ----------- -----------Sports Play 3 7422 $3,817,245.40 7.59% $289,728.92 $322,270.94Sports 4 You 1 3022 $398,335.40 7.59% $30,233.65 $33,629.46The Sportsman 1 3022 $285,229.40 7.59% $21,648.91 $24,080.49Sports 4 Winners 1 1100 $68,509.40 5.06% $3,466.57 $5,783.90Sports Club 1 12027 $1,324,256.10 7.59% $100,511.03 $111,800.32--------- -------- -------------- ----------- -----------Totals: 7 26593 $5,893,575.70 $445,589.08 $497,565.11Salesperson: Chris PrestonCustomers: Number of Products Total <strong>for</strong> Discount Discount CommissionOrders Ordered Order (if any) Amount Earned-------------------- --------- -------- -------------- -------- ----------- -----------Playing Ball 1 5535 $1,939,219.10 7.59% $147,186.72 $103,509.69Play Sports 1 5675 $225,130.80 7.59% $17,087.42 $12,016.80Winners Club 1 631 $14,069.70 2.25% $316.56 $750.99The Jock Shop 1 2332 $28,716.60 3.38% $970.62 $1,532.80--------- -------- -------------- ----------- -----------Totals: 4 14173 $2,207,136.20 $165,561.32 $117,810.28Salesperson: Edyth PhillipsCustomers: Number of Products Total <strong>for</strong> Discount Discount CommissionOrders Ordered Order (if any) Amount Earned-------------------- --------- -------- -------------- -------- ----------- -----------Sports Play 2 3575 $92,409.90 5.06% $4,675.94 $3,911.43Winning Sports 1 11945 $56,651.40 5.06% $2,866.56 $2,397.88--------- -------- -------------- ----------- -----------Totals: 3 15520 $149,061.30 $7,542.50 $6,309.31Grand Totals: 33 119210 $14,267,748.80 $1,068,031.60 $1,114,529.39Example: IGYTSALE response time from sale to shipThe following sample of IGYTSALE output shows response time between the saledate in the United States and the date the sold products are shipped to Europe.Day of Report: Monday <strong>COBOL</strong> SPORTS 11/24/2003 03:12 Page: 1Response Time from USA Sale to European ShipProd Units Sale Date/Time(PST) Ship Date Ship Response TimeCode Sold YYYYMMDD HHMMSS YYYYMMDD Day Days---- ----- -------- ------ -------- ---- -------------25 9999 19900226 010101 19900228 WED .9515 99 19900310 100530 19900403 TUE 23.5705 9900 19900418 222409 19900419 THU .0625 4 19900523 151010 19900623 SAT 30.36Appendix H. Using sample programs 827


04 1100 19901110 003301 19901114 WED 2.9712 23 19901114 003205 19901117 SAT 1.9714 5111 19900118 101527 19900120 SAT 1.5704 5102 19901201 132013 19901203 MON 1.4404 300 19901221 191544 19901223 SUN 1.1905 500 19901210 211544 19901214 FRI 3.1104 100 19901211 000816 19901213 THU .9925 100 19901201 131544 19901203 MON 1.4425 100 19901112 073312 19901113 TUE .6814 1111 19901214 012510 19901216 SUN .9426 22 19901110 000034 19901113 TUE 1.9912 2000 19901110 154100 19901113 TUE 2.3404 1104 19901110 175001 19901113 TUE 2.2512 114 19901229 115522 19901230 SUN .5015 2000 19901110 190113 19901114 WED 3.2010 1440 19901112 001500 19901115 THU 1.9825 1104 19901118 120101 19901119 MON .4925 4 19901118 110030 19901119 MON .5412 144 19901114 010510 19901119 MON 3.9514 112 19901119 010101 19901122 THU 1.9526 321 19901117 173945 19901119 MON 1.2613 1221 19901101 135133 19901102 FRI .4210 22 19901029 210000 19901030 TUE .1214 35 19901130 160500 19901201 SAT .3211 9005 19901211 050505 19901212 WED .7806 990 19900511 214409 19900515 TUE 3.0913 1998 19900712 150100 19900716 MON 3.3726 31 19901010 185559 19901011 THU .2114 30 19901210 195500 19901212 WED 1.17Preparing to run IGYTSALEAll files required by the IGYTSALE program (IGYTSALE, IGYTCRC, IGYTPRC,IGYTSRC, IGYTABLE, and IGYTRANA) are on the product installation tape in theIGY.V4R2M0.SIGYSAMP data set.You can change data-set names and procedure-names at installation time. Checkwith your system programmer to verify these names.Do not change these options in the CBL statement in the source file <strong>for</strong> IGYTSALE:v LIBv NONUMBERv SEQUENCEv NONUMBERv QUOTEWith these options in effect, the program might not cause any diagnostic messagesto be issued. You can use the sequence number string in the source file to search<strong>for</strong> the language elements used.When you run IGYTSALE, the following messages are printed to the SYSOUT dataset:Program IGYTSALE BeginsThere were 00041 records processed in this programProgram IGYTSALE Normal EndRELATED CONCEPTS“IGYTSALE: nested program application” on page 822828 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


RELATED TASKS“Running IGYTSALE”RELATED REFERENCES“Input data <strong>for</strong> IGYTSALE” on page 823“Reports produced by IGYTSALE” on page 825“Language elements and concepts that are illustrated”Running IGYTSALEUse the following JCL to compile, link-edit, and run the IGYTSALE program. Ifyou want only to compile or only to compile and link-edit the program, change theIGYWCLG cataloged procedure.Insert the in<strong>for</strong>mation <strong>for</strong> your system or installation in the fields that are shownin lowercase letters (accounting in<strong>for</strong>mation).//IGYTSALE JOB (acct-info),'IGYTSALE',MSGLEVEL=(1,1),TIME=(0,29)//TEST EXEC IGYWCLG//<strong>COBOL</strong>.SYSLIB DD DSN=IGY.V4R2M0.SIGYSAMP,DISP=SHR//<strong>COBOL</strong>.SYSIN DD DSN=IGY.V4R2M0.SIGYSAMP(IGYTSALE),DISP=SHR//GO.SYSOUT DD SYSOUT=A//GO.IGYTABLE DD DSN=IGY.V4R2M0.SIGYSAMP(IGYTABLE),DISP=SHR//GO.IGYTRANS DD DSN=IGY.V4R2M0.SIGYSAMP(IGYTRANA),DISP=SHR//GO.IGYPRINT DD SYSOUT=A,DCB=BLKSIZE=133//GO.IGYPRT2 DD SYSOUT=A,DCB=BLKSIZE=133//Language elements and concepts that are illustratedThe sample programs illustrate several <strong>COBOL</strong> language elements and concepts.To find the applicable language element <strong>for</strong> a sample program, locate theabbreviation <strong>for</strong> that program in the sequence string:Sample programIGYTCARAIGYTCARBIGYTSALEAbbreviationIAIBISThe following table lists the language elements and programming concepts that thesample programs illustrate. The language element or concept is described, and thesequence string is shown. The sequence string is the special character string thatappears in the sequence field of the source file. You can use this string as a searchargument <strong>for</strong> locating the elements in the listing.Language element or conceptACCEPT ...FROM DAY-OF-WEEKACCEPT ...FROM DATEACCEPT ...FROM TIMEADD...TOAFTER ADVANCINGAFTER PAGEALLSequence stringIS0900IS0901IS0902IS4550IS2700IS2600IS4200Appendix H. Using sample programs 829


Language element or conceptASSIGNAUTHORCALLCallable services (Language Environment):1. CEEDATM: <strong>for</strong>mat date or time output2. CEEDCOD: feedback code check3. CEEGMTO: UTC offset from local time4. CEELOCT: local date and time5. CEESECS: convert timestamp to secondsCL<strong>OS</strong>E filesComma, semicolon, and space interchangeableCOMMON statement <strong>for</strong> nested programsComplex OCCURS DEPENDING ONCOMPUTECOMPUTE ROUNDEDCONFIGURATION SECTIONCONFIGURATION SECTION (optional)CONTINUE statementCOPY statementDATA DIVISION (optional)Data validationDo-until (PERFORM ...TEST AFTER)Do-while (PERFORM ...TEST BEFORE)END-ADDEND-COMPUTEEND-EVALUATEEND-IFEND-MULTIPLYEND-PERFORMEND PROGRAMEND-READEND-SEARCHENVIRONMENT DIVISION (optional)Error handling, termination of programEVALUATE statementEVALUATE ...ALSOEXIT PROGRAM not only statement in paragraphExponentiationEXTERNAL clauseFILE-CONTROL entry <strong>for</strong> sequential fileFILE-CONTROL entry <strong>for</strong> VSAM indexed fileSequence stringIS1101IA0040IS08001. IS0875, IS25752. IS09053. IS09044. IS08505. IS2350, IS2550IS1900IS3500, IS3600IS4600IS0700, IS3700IS4501IS4500IA0970IS0200IA5310, IA5380IS0500IS5100IA5130-6190IA4900-5010, IA7690-7770IS1660IS2900IS4510IA6590, IS2450IS1680IS3100IS1700IA9990IS1800IS3400IS0200IA4620, IA5080, IA7800-7980IA6270-6590IS2400IS2000IS4500IS1200IA1190-1300IA1070-1180830 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Language element or conceptFILE SECTION (optional)FILE STATUS code checkFILLER (optional)Flags, level-88, definitionFlags, level-88, testingFLOATING POINTGLOBAL statementINITIAL statement <strong>for</strong> nested programsINITIALIZEInitializing a table in the DATA DIVISIONInline PERFORM statementI-O-CONTROL paragraphs (optional)INPUT-OUTPUT SECTION (optional)Intrinsic functions:1. CURRENT-DATE2. MAX3. MEAN4. MEDIAN5. MIN6. STANDARD-DEVIATION7. UPPER-CASE8. VARIANCE9. WHEN-COMPILEDIS (optional in all clauses)LABEL RECORDS (optional)LINKAGE SECTIONMixing of indexes and subscriptsMnemonic namesMOVEMOVE CORRESPONDING statementMULTIPLY ...GIVINGNested IF statement, using END-IFNested programNEXT SENTENCENOT AT ENDNULLOBJECT-COMPUTER (optional)OCCURS DEPENDING ONODO uses maximum length <strong>for</strong> receiving itemOPEN EXTENDOPEN INPUTOPEN OUTPUTSequence stringIS0200IA4600-4630, IA4760-4790IS0400IA1730-1800, IA2440-2480, IA2710IA4430, IA5200-5250IS4400IS0300IS2300IS2500IA2920-4260IA4410-4520IS0200IS02001. IA90052. IA92353. IA92154. IA92205. IA92406. IA92307. IA90158. IA92259. IA9000IS0700IS1150IS4900IS3500IA1000IS0903IA4810, IA4830IS3000IA5460-5830IS1000IS4300IS1600IS4800IS0200IS0710IS1550IB2210IS1400IS1500Appendix H. Using sample programs 831


Language element or conceptORGANIZATION (optional)Page ejectParenthesis in abbreviated conditionsPERFORM ...WITH TEST AFTER (Do-until)PERFORM ...WITH TEST BEFORE (Do-while)PERFORM ...UNTILPERFORM ...VARYING statementPOINTER functionPrint file FD entryPrint reportPROCEDURE DIVISION ...USINGPROGRAM-ID (30 characters allowed)READ...INTO...ATENDREDEFINES statementReference modificationRelational operator = (greater than or equal)Relative subscriptingREPLACESEARCH statementSELECTSequence number can contain any characterSequential file processingSequential table search, using PERFORMSequential table search, using SEARCHSET INDEXSET...TOTRUE statementSOURCE-COMPUTER (optional)SPECIAL-NAMES paragraph (optional)STRING statementSupport <strong>for</strong> lowercase lettersTALLYTITLE statement <strong>for</strong> nested programsUpdate commuter recordUpdate transaction work value spacesUSAGE BINARYUSAGE PACKED-DECIMALValidate elementsVALUE with OCCURSVALUE SPACE (S)VALUE ZERO (S) (ES)Sequence stringIS1100IA7180-7210IS4850IA4900-5010, IA7690-7770IS1660IS5000IA7690-7770IS4700IA1570-1620IA7100-7360IB1320-IB1650IS0120IS1550IA1940, IA2060, IA2890, IA3320IS2425IS4400IS2425IS4000IS4100IS3300IS1100IA, IB, ISIA4480-4510, IA4840-4870IA7690-7770IA5270-5320, IA5340-5390IS3200IA4390, IA4500, IA4860, IA4980IS0200IS0200IA6950, IA7050IS0100IS1650IS0100IA6200-6610IB0790-IB1000IS1300IS1301IB0810, IB0860, IB1000IS0600IS0601IS0600832 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Language element or conceptVariable-length table control variableVariable-length table definitionVariable-length table loadingVSAM indexed file key definitionVSAM return-code displayWORKING-STORAGE SECTIONSequence stringIA5100IA2090-2210IA4840-4990IA1170IA7800-7900IS0250Appendix H. Using sample programs 833


834 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


NoticesThis in<strong>for</strong>mation was developed <strong>for</strong> products and services offered in the U.S.A.IBM may not offer the products, services, or features discussed in this document inother countries. Consult your local IBM representative <strong>for</strong> in<strong>for</strong>mation on theproducts and services currently available in your area. Any reference to an IBMproduct, program, or service is not intended to state or imply that only that IBMproduct, program, or service may be used. Any functionally equivalent product,program, or service that does not infringe any IBM intellectual property right maybe used instead. However, it is the user’s responsibility to evaluate and verify theoperation of any non-IBM product, program, or service.IBM may have patents or pending patent applications covering subject matterdescribed in this document. The furnishing of this document does not grant youany license to these patents. You can send license inquiries, in writing, to:IBM Director of LicensingIBM CorporationNorth Castle DriveArmonk, NY 10504-1785U.S.A.For license inquiries regarding double-byte (DBCS) in<strong>for</strong>mation, contact the IBMIntellectual Property Department in your country or send inquiries, in writing, to:Intellectual Property LicensingLegal and Intellectual Property LawIBM Japan, Ltd.3-2-12, Roppongi, Minato-ku, Tokyo 106-8711The following paragraph does not apply to the United Kingdom or any othercountry where such provisions are inconsistent with local law:INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THISPUBLICATION ″AS IS″ WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESSFOR A PARTICULAR PURP<strong>OS</strong>E. Some states do not allow disclaimer of express orimplied warranties in certain transactions, there<strong>for</strong>e, this statement may not applyto you.This in<strong>for</strong>mation could include technical inaccuracies or typographical errors.Changes are periodically made to the in<strong>for</strong>mation herein; these changes will beincorporated in new editions of the publication. IBM may make improvementsand/or changes in the product(s) and/or the program(s) described in thispublication at any time without notice.Any references in this in<strong>for</strong>mation to non-IBM Web sites are provided <strong>for</strong>convenience only and do not in any manner serve as an endorsement of those Websites. The materials at those Web sites are not part of the materials <strong>for</strong> this IBMproduct and use of those Web sites is at your own risk.IBM may use or distribute any of the in<strong>for</strong>mation you supply in any way itbelieves appropriate without incurring any obligation to you.© Copyright IBM Corp. 1991, 2009 835


Licensees of this program who wish to have in<strong>for</strong>mation about it <strong>for</strong> the purposeof enabling: (i) the exchange of in<strong>for</strong>mation between independently createdprograms and other programs (including this one) and (ii) the mutual use of thein<strong>for</strong>mation which has been exchanged, should contact:IBM CorporationJ46A/G4555 Bailey AvenueSan Jose, CA 95141-1003U.S.A.Such in<strong>for</strong>mation may be available, subject to appropriate terms and conditions,including in some cases, payment of a fee.The licensed program described in this document and all licensed materialavailable <strong>for</strong> it are provided by IBM under terms of the IBM Customer Agreement,IBM International Program License Agreement or any equivalent agreementbetween us.Any per<strong>for</strong>mance data contained herein was determined in a controlledenvironment. There<strong>for</strong>e, the results obtained in other operating environments mayvary significantly. Some measurements may have been made on development-levelsystems and there is no guarantee that these measurements will be the same ongenerally available systems. Furthermore, some measurements may have beenestimated through extrapolation. Actual results may vary. Users of this documentshould verify the applicable data <strong>for</strong> their specific environment.In<strong>for</strong>mation concerning non-IBM products was obtained from the suppliers ofthose products, their published announcements or other publicly available sources.IBM has not tested those products and cannot confirm the accuracy ofper<strong>for</strong>mance, compatibility or any other claims related to non-IBM products.Questions on the capabilities of non-IBM products should be addressed to thesuppliers of those products.All statements regarding IBM’s future direction or intent are subject to change orwithdrawal without notice, and represent goals and objectives only.This in<strong>for</strong>mation contains examples of data and reports used in daily businessoperations. To illustrate them as completely as possible, the examples include thenames of individuals, companies, brands, and products. All of these names arefictitious and any similarity to the names and addresses used by an actual businessenterprise is entirely coincidental.COPYRIGHT LICENSE:This in<strong>for</strong>mation contains sample application programs in source language, whichillustrate programming techniques on various operating plat<strong>for</strong>ms. You may copy,modify, and distribute these sample programs in any <strong>for</strong>m without payment toIBM, <strong>for</strong> the purposes of developing, using, marketing or distributing applicationprograms con<strong>for</strong>ming to the application programming interface <strong>for</strong> the operatingplat<strong>for</strong>m <strong>for</strong> which the sample programs are written. These examples have notbeen thoroughly tested under all conditions. IBM, there<strong>for</strong>e, cannot guarantee orimply reliability, serviceability, or function of these programs. The sampleprograms are provided ″AS IS″, without warranty of any kind. IBM shall not beliable <strong>for</strong> any damages arising out of your use of the sample programs.836 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Each copy or any portion of these sample programs or any derivative work, mustinclude a copyright notice as follows:© (your company name) (year). Portions of this code are derived from IBM Corp.Sample Programs. © Copyright IBM Corp. _enter the year or years_. All rightsreserved.If you are viewing this in<strong>for</strong>mation softcopy, the photographs and colorillustrations may not appear.TrademarksThe following terms are trademarks of International Business MachinesCorporation in the United States, or other countries, or both:IBMThe IBM logoibm.comAIXBookManagerCICSDB2IMSIMS/ESALanguage Environment<strong>OS</strong>/390RACFRationalSystem zVTAMWebSpherez/Architecturez/<strong>OS</strong>zSeriesIntel is a registered trademark of Intel Corporation or its subsidiaries in the UnitedStates and other countries.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.Microsoft and Windows are trademarks of Microsoft Corporation in the UnitedStates, other countries, or both.UNIX is a registered trademark of The Open Group in the United States and othercountries.Other company, product, or service names may be the trademarks or service marksof others.Notices 837


838 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


GlossaryThe terms in this glossary are defined inaccordance with their meaning in <strong>COBOL</strong>. Theseterms might or might not have the same meaningin other languages.This glossary includes terms and definitions fromthe following publications:v ANSI INCITS 23-1985, <strong>Programming</strong> languages -<strong>COBOL</strong>, as amended by ANSI INCITS 23a-1989,<strong>Programming</strong> Languages - <strong>COBOL</strong> - IntrinsicFunction Module <strong>for</strong> <strong>COBOL</strong>, and ANSI INCITS23b-1993, <strong>Programming</strong> Languages - CorrectionAmendment <strong>for</strong> <strong>COBOL</strong>v ANSI X3.172-2002, American National StandardDictionary <strong>for</strong> In<strong>for</strong>mation SystemsAmerican National Standard definitions arepreceded by an asterisk (*).This glossary includes definitions developed bySun Microsystems, Inc. <strong>for</strong> their Java and J2EEglossaries. When Sun is the source of a definition,that is indicated.A* abbreviated combined relation conditionThe combined condition that results fromthe explicit omission of a common subjector a common subject and commonrelational operator in a consecutivesequence of relation conditions.abend Abnormal termination of a program.above the 16-MB lineStorage above the so-called 16-MB line (orboundary) but below the 2-GB bar. Thisstorage is addressable only in 31-bitmode. Be<strong>for</strong>e IBM introduced theMVS/XA architecture in the 1980s, thevirtual storage <strong>for</strong> a program was limitedto 16 MB. Programs that have beencompiled with a 24-bit mode can addressonly 16 MB of space, as though they werekept under an imaginary storage line.Since VS <strong>COBOL</strong> II, a program that hasbeen compiled with a 31-bit mode can beabove the 16-MB line.* access modeThe manner in which records are to beoperated upon within a file.|* actual decimal pointThe physical representation, using thedecimal point characters period (.) orcomma (,), of the decimal point positionin a data item.actual document encodingFor an XML document, one of thefollowing encoding categories that theXML parser determines by examining thefirst few bytes of the document:v ASCIIv EBCDICv UTF-8v UTF-16, either big-endian orlittle-endianv Other unsupported encodingv No recognizable encoding* alphabet-nameA user-defined word, in theSPECIAL-NAMES paragraph of theENVIRONMENT DIVISION, that assigns aname to a specific character set orcollating sequence or both.* alphabetic characterA letter or a space character.alphabetic data itemA data item that is described with aPICTURE character string that containsonly the symbol A. An alphabetic dataitem has USAGE DISPLAY.* alphanumeric characterAny character in the single-byte characterset of the computer.alphanumeric data itemA general reference to a data item that isdescribed implicitly or explicitly as USAGEDISPLAY, and that has categoryalphanumeric, alphanumeric-edited, ornumeric-edited.alphanumeric-edited data itemA data item that is described by a PICTUREcharacter string that contains at least oneinstance of the symbol A or X and at leastone of the simple insertion symbols B, 0,or /. An alphanumeric-edited data itemhas USAGE DISPLAY.© Copyright IBM Corp. 1991, 2009 839


* alphanumeric functionA function whose value is composed of astring of one or more characters from thealphanumeric character set of thecomputer.alphanumeric group itemA group item that is defined without aGROUP-USAGE NATIONAL clause. Foroperations such as INSPECT, STRING, andUNSTRING, an alphanumeric group item isprocessed as though all its content weredescribed as USAGE DISPLAY regardless ofthe actual content of the group. Foroperations that require processing of theelementary items within a group, such asMOVE CORRESPONDING, ADD CORRESPONDING,or INITIALIZE, an alphanumeric groupitem is processed using group semantics.alphanumeric literalA literal that has an opening delimiterfrom the following set: ', ", X', X", Z', orZ". The string of characters can includeany character in the character set of thecomputer.* alternate record keyA key, other than the prime record key,whose contents identify a record withinan indexed file.ANSI (American National Standards Institute)An organization that consists ofproducers, consumers, andgeneral-interest groups and establishes theprocedures by which accreditedorganizations create and maintainvoluntary industry standards in theUnited States.argument(1) An identifier, a literal, an arithmeticexpression, or a function-identifier thatspecifies a value to be used in theevaluation of a function. (2) An operandof the USING phrase of a CALL or INVOKEstatement, used <strong>for</strong> passing values to acalled program or an invoked method.* arithmetic expressionAn identifier of a numeric elementaryitem, a numeric literal, such identifiersand literals separated by arithmeticoperators, two arithmetic expressionsseparated by an arithmetic operator, or anarithmetic expression enclosed inparentheses.* arithmetic operationThe process caused by the execution of anarithmetic statement, or the evaluation ofan arithmetic expression, that results in amathematically correct solution to thearguments presented.* arithmetic operatorA single character, or a fixedtwo-character combination that belongs tothe following set:CharacterMeaning+ Addition- Subtraction* Multiplication/ Division** Exponentiation* arithmetic statementA statement that causes an arithmeticoperation to be executed. The arithmeticstatements are ADD, COMPUTE, DIVIDE,MULTIPLY, and SUBTRACT.array An aggregate that consists of data objects,each of which can be uniquely referencedby subscripting. An array is roughlyanalogous to a <strong>COBOL</strong> table.* ascending keyA key upon the values of which data isordered, starting with the lowest value ofthe key up to the highest value of the key,in accordance with the rules <strong>for</strong>comparing data items.ASCIIAmerican National Standard Code <strong>for</strong>In<strong>for</strong>mation Interchange. The standardcode uses a coded character set that isbased on 7-bit coded characters (8 bitsincluding parity check). The standard isused <strong>for</strong> in<strong>for</strong>mation interchange betweendata processing systems, datacommunication systems, and associatedequipment. The ASCII set consists ofcontrol characters and graphic characters.IBM has defined an extension to ASCII(characters 128-255).assignment-nameA name that identifies the organization ofa <strong>COBOL</strong> file and the name by which it isknown to the system.* assumed decimal pointA decimal point position that does not840 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


involve the existence of an actualcharacter in a data item. The assumeddecimal point has logical meaning but nophysical representation.AT END conditionA condition that is caused during theexecution of a READ, RETURN, orSEARCHstatement under certain conditions:v A READ statement runs on a sequentiallyaccessed file when no next logicalrecord exists in the file, or when thenumber of significant digits in therelative record number is larger thanthe size of the relative key data item, orwhen an optional input file is notavailable.v A RETURN statement runs when no nextlogical record exists <strong>for</strong> the associatedsort or merge file.v A SEARCH statement runs when thesearch operation terminates withoutsatisfying the condition specified in anyof the associated WHEN phrases.Bbig-endianThe default <strong>for</strong>mat that the mainframeand the AIX workstation use to storebinary data and UTF-16 characters. In this<strong>for</strong>mat, the least significant byte of abinary data item is at the highest addressand the least significant byte of a UTF-16character is at the highest address.Compare with little-endian.binary itemA numeric data item that is represented inbinary notation (on the base 2 numberingsystem). The decimal equivalent consistsof the decimal digits 0 through 9, plus anoperational sign. The leftmost bit of theitem is the operational sign.binary searchA dichotomizing search in which, at eachstep of the search, the set of data elementsis divided by two; some appropriateaction is taken in the case of an oddnumber.* blockA physical unit of data that is normallycomposed of one or more logical records.For mass storage files, a block can containa portion of a logical record. The size of ablock has no direct relationship to the sizeof the file within which the block iscontained or to the size of the logicalrecords that are either contained withinthe block or that overlap the block.Synonymous with physical record.breakpointA place in a computer program, usuallyspecified by an instruction, where externalintervention or a monitor program caninterrupt the program as it runs.bufferA portion of storage that is used to holdinput or output data temporarily.built-in functionSee intrinsic function.business methodA method of an enterprise bean thatimplements the business logic or rules ofan application. (Sun)byte A string that consists of a certain numberof bits, usually eight, treated as a unit,and representing a character or a controlfunction.byte order mark (BOM)A Unicode character that can be used atthe start of UTF-16 or UTF-32 text toindicate the byte order of subsequent text;the byte order can be either big-endian orlittle-endian.bytecodeMachine-independent code that isgenerated by the Java compiler andexecuted by the Java interpreter. (Sun)Ccallable servicesIn Language Environment, a set ofservices that a <strong>COBOL</strong> program caninvoke by using the conventionalLanguage Environment-defined callinterface. All programs that share theLanguage Environment conventions canuse these services.called programA program that is the object of a CALLstatement. At run time the called programand calling program are combined toproduce a run unit.* calling programA program that executes a CALL to anotherprogram.Glossary 841


case structureA program-processing logic in which aseries of conditions is tested in order tochoose between a number of resultingactions.cataloged procedureA set of job control statements that areplaced in a partitioned data set called theprocedure library (SYS1.PROCLIB). Youcan use cataloged procedures to save timeand reduce errors in coding JCL.CCSIDSee coded character set identifier.century windowA 100-year interval within which anytwo-digit year is unique. Several types ofcentury window are available to <strong>COBOL</strong>programmers:v For windowed date fields, you use theYEARWINDOW compiler option.v For the windowing intrinsic functionsDATE-TO-YYYYMMDD, DAY-TO-YYYYDDD, andYEAR-TO-YYYY, you specify the centurywindow with argument-2.v For Language Environment callableservices, you specify the centurywindow in CEESCEN.* characterThe basic indivisible unit of the language.character encoding unitA unit of data that corresponds to onecode point in a coded character set. Oneor more character encoding units are usedto represent a character in a codedcharacter set. Also known as encoding unit.For USAGE NATIONAL, a character encodingunit corresponds to one 2-byte code pointof UTF-16.For USAGE DISPLAY, a character encodingunit corresponds to a byte.For USAGE DISPLAY-1, a characterencoding unit corresponds to a 2-bytecode point in the DBCS character set.character positionThe amount of physical storage orpresentation space required to hold orpresent one character. The term applies toany class of character. For specific classesof characters, the following terms apply:v Alphanumeric character position, <strong>for</strong>characters represented in USAGE DISPLAYv DBCS character position, <strong>for</strong> DBCScharacters represented in USAGEDISPLAY-1v National character position, <strong>for</strong> charactersrepresented in USAGE NATIONAL;synonymous with character encoding unit<strong>for</strong> UTF-16character setA collection of elements that are used torepresent textual in<strong>for</strong>mation, but <strong>for</strong>which no coded representation isassumed. See also coded character set.character stringA sequence of contiguous characters that<strong>for</strong>m a <strong>COBOL</strong> word, a literal, a PICTUREcharacter string, or a comment-entry. Acharacter string must be delimited byseparators.checkpointA point at which in<strong>for</strong>mation about thestatus of a job and the system can berecorded so that the job step can berestarted later.* classThe entity that defines common behaviorand implementation <strong>for</strong> zero, one, ormore objects. The objects that share thesame implementation are considered to beobjects of the same class. Classes can bedefined hierarchically, allowing one classto inherit from another.* class conditionThe proposition (<strong>for</strong> which a truth valuecan be determined) that the content of anitem is wholly alphabetic, is whollynumeric, is wholly DBCS, is wholly Kanji,or consists exclusively of the charactersthat are listed in the definition of aclass-name.* class definitionThe <strong>COBOL</strong> source unit that defines aclass.class hierarchyA tree-like structure that showsrelationships among object classes. Itplaces one class at the top and one ormore layers of classes below it.Synonymous with inheritance hierarchy.842 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


|* class identification entryAn entry in the CLASS-ID paragraph of theIDENTIFICATION DIVISION; this entrycontains clauses that specify theclass-name and assign selected attributesto the class definition.class-name (object-oriented)The name of an object-oriented <strong>COBOL</strong>class definition.* class-name (of data)A user-defined word that is defined in theSPECIAL-NAMES paragraph of theENVIRONMENT DIVISION; this word assignsa name to the proposition (<strong>for</strong> which atruth value can be defined) that thecontent of a data item consists exclusivelyof the characters that are listed in thedefinition of the class-name.class objectThe runtime object that represents a class.* clauseAn ordered set of consecutive <strong>COBOL</strong>character strings whose purpose is tospecify an attribute of an entry.client In object-oriented programming, aprogram or method that requests servicesfrom one or more methods in a class.<strong>COBOL</strong> character setThe set of characters used in writing<strong>COBOL</strong> syntax. The complete <strong>COBOL</strong>character set consists of the characterslisted below:CharacterMeaning0,1,...,9 DigitA,B,...,ZUppercase lettera,b,...,zLowercase letterSpace+ Plus sign- Minus sign (hyphen)* Asterisk/ Slant (<strong>for</strong>ward slash)= Equal sign$ Currency sign, Comma; Semicolon. Period (decimal point, full stop)″ Quotation mark’ Apostrophe( Left parenthesis) Right parenthesis> Greater than< Less than|CharacterMeaning: Colon_Underscore* <strong>COBOL</strong> wordSee word.code pageAn assignment of graphic characters andcontrol function meanings to all codepoints. For example, one code page couldassign characters and meanings to 256code points <strong>for</strong> 8-bit code, and anothercode page could assign characters andmeanings to 128 code points <strong>for</strong> 7-bitcode. For example, one of the IBM codepages <strong>for</strong> English on the workstation isIBM-1252 and on the host is IBM-1047. Acoded character set.code pointA unique bit pattern that is defined in acoded character set (code page). Graphicsymbols and control characters areassigned to code points.coded character setA set of unambiguous rules that establisha character set and the relationshipbetween the characters of the set and theircoded representation. Examples of codedcharacter sets are the character sets asrepresented by ASCII or EBCDIC codepages or by the UTF-16 encoding scheme<strong>for</strong> Unicode.coded character set identifier (CCSID)An IBM-defined number in the range 1 to65,535 that identifies a specific code page.* collating sequenceThe sequence in which the characters thatare acceptable to a computer are ordered<strong>for</strong> purposes of sorting, merging,comparing, and <strong>for</strong> processing indexedfiles sequentially.* columnA byte position within a print line orwithin a reference <strong>for</strong>mat line. Thecolumns are numbered from 1, by 1,starting at the leftmost position of the lineand extending to the rightmost position ofthe line. A column holds one single-bytecharacter.* combined conditionA condition that is the result ofconnecting two or more conditions withGlossary 843


the AND or the OR logical operator. See alsocondition and negated combined condition.* comment-entryAn entry in the IDENTIFICATION DIVISIONthat can be any combination of charactersfrom the character set of the computer.* comment lineA source program line represented by anasterisk (*) in the indicator area of the lineand any characters from the character setof the computer in area A and area B ofthat line. The comment line serves only<strong>for</strong> documentation. A special <strong>for</strong>m ofcomment line represented by a slant (/)in the indicator area of the line and anycharacters from the character set of thecomputer in area A and area B of that linecauses page ejection be<strong>for</strong>e printing thecomment.* common programA program that, despite being directlycontained within another program, can becalled from any program directly orindirectly contained in that otherprogram.compatible date fieldThe meaning of the term compatible, whenapplied to date fields, depends on the<strong>COBOL</strong> division in which the usageoccurs:v DATA DIVISION: Two date fields arecompatible if they have identical USAGEand meet at least one of the followingconditions:– They have the same date <strong>for</strong>mat.– Both are windowed date fields,where one consists only of awindowed year, DATE FORMAT YY.– Both are expanded date fields, whereone consists only of an expandedyear, DATE FORMAT YYYY.– One has DATE FORMAT YYXXXX, andthe other has YYXX.– One has DATE FORMAT YYYYXXXX, andthe other has YYYYXX.A windowed date field can besubordinate to a data item that is anexpanded date group. The two datefields are compatible if the subordinatedate field has USAGE DISPLAY, starts twobytes after the start of the groupexpanded date field, and the two fieldsmeet at least one of the followingconditions:– The subordinate date field has aDATE FORMAT pattern with the samenumber of Xs as the DATE FORMATpattern of the group date field.– The subordinate date field has DATEFORMAT YY.– The group date field has DATEFORMAT YYYYXXXX and thesubordinate date field has DATEFORMAT YYXX.v PROCEDURE DIVISION: Two date fieldsare compatible if they have the samedate <strong>for</strong>mat except <strong>for</strong> the year part,which can be windowed or expanded.For example, a windowed date fieldwith DATE FORMAT YYXXX is compatiblewith:– Another windowed date field withDATE FORMAT YYXXX– An expanded date field with DATEFORMAT YYYYXXX* compile(1) To translate a program expressed in ahigh-level language into a programexpressed in an intermediate language,assembly language, or a computerlanguage. (2) To prepare amachine-language program from acomputer program written in anotherprogramming language by making use ofthe overall logic structure of the program,or generating more than one computerinstruction <strong>for</strong> each symbolic statement,or both, as well as per<strong>for</strong>ming thefunction of an assembler.* compile timeThe time at which <strong>COBOL</strong> source code istranslated, by a <strong>COBOL</strong> compiler, to a<strong>COBOL</strong> object program.compilerA program that translates source codewritten in a higher-level language intomachine-language object code.compiler-directing statementA statement that causes the compiler totake a specific action during compilation.The standard compiler-directingstatements are COPY, REPLACE, and USE.844 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


* complex conditionA condition in which one or more logicaloperators act upon one or moreconditions. See also condition, negatedsimple condition, and negated combinedcondition.complex ODOCertain <strong>for</strong>ms of the OCCURS DEPENDING ONclause:v Variably located item or group: A dataitem described by an OCCURS clausewith the DEPENDING ON option isfollowed by a nonsubordinate dataitem or group. The group can be analphanumeric group or a nationalgroup.v Variably located table: A data itemdescribed by an OCCURS clause with theDEPENDING ON option is followed by anonsubordinate data item described byan OCCURS clause.v Table with variable-length elements: Adata item described by an OCCURSclause contains a subordinate data itemdescribed by an OCCURS clause with theDEPENDING ON option.v Index name <strong>for</strong> a table withvariable-length elements.v Element of a table with variable-lengthelements.component(1) A functional grouping of related files.(2) In object-oriented programming, areusable object or program that per<strong>for</strong>msa specific function and is designed towork with other components andapplications. JavaBeans is SunMicrosystems, Inc.’s architecture <strong>for</strong>creating components.* computer-nameA system-name that identifies thecomputer where the program is to becompiled or run.condition (exception)An exception that has been enabled, orrecognized, by Language Environmentand thus is eligible to activate user andlanguage condition handlers. Anyalteration to the normal programmed flowof an application. Conditions can bedetected by the hardware or the operatingsystem and result in an interrupt. Theycan also be detected by language-specificgenerated code or language library code.condition (expression)A status of data at run time <strong>for</strong> which atruth value can be determined. Whereused in this in<strong>for</strong>mation in or in referenceto “condition” (condition-1, condition-2,...)of a general <strong>for</strong>mat, the term refers to aconditional expression that consists ofeither a simple condition optionallyparenthesized or a combined condition(consisting of the syntactically correctcombination of simple conditions, logicaloperators, and parentheses) <strong>for</strong> which atruth value can be determined. See alsosimple condition, complex condition, negatedsimple condition, combined condition, andnegated combined condition.* conditional expressionA simple condition or a complexcondition specified in an EVALUATE, IF,PERFORM, orSEARCH statement. See alsosimple condition and complex condition.* conditional phraseA phrase that specifies the action to betaken upon determination of the truthvalue of a condition that results from theexecution of a conditional statement.* conditional statementA statement that specifies that the truthvalue of a condition is to be determinedand that the subsequent action of theobject program depends on this truthvalue.* conditional variableA data item one or more values of whichhas a condition-name assigned to it.* condition-nameA user-defined word that assigns a nameto a subset of values that a conditionalvariable can assume; or a user-definedword assigned to a status of animplementor-defined switch or device.* condition-name conditionThe proposition (<strong>for</strong> which a truth valuecan be determined) that the value of aconditional variable is a member of theset of values attributed to acondition-name associated with theconditional variable.* CONFIGURATION SECTIONA section of the ENVIRONMENT DIVISIONGlossary 845


that describes overall specifications ofsource and object programs and classdefinitions.CONSOLEA <strong>COBOL</strong> environment-name associatedwith the operator console.contained programA <strong>COBOL</strong> program that is nested withinanother <strong>COBOL</strong> program.* contiguous itemsItems that are described by consecutiveentries in the DATA DIVISION, and thatbear a definite hierarchic relationship toeach other.copybookA file or library member that contains asequence of code that is included in thesource program at compile time using theCOPY statement. The file can be created bythe user, supplied by <strong>COBOL</strong>, or suppliedby another product. Synonymous withcopy file.* counterA data item used <strong>for</strong> storing numbers ornumber representations in a manner thatpermits these numbers to be increased ordecreased by the value of anothernumber, or to be changed or reset to zeroor to an arbitrary positive or negativevalue.cross-reference listingThe portion of the compiler listing thatcontains in<strong>for</strong>mation on where files,fields, and indicators are defined,referenced, and modified in a program.currency-sign valueA character string that identifies themonetary units stored in a numeric-editeditem. Typical examples are $, USD, andEUR. A currency-sign value can bedefined by either the CURRENCY compileroption or the CURRENCY SIGN clause in theSPECIAL-NAMES paragraph of theENVIRONMENT DIVISION. IftheCURRENCYSIGN clause is not specified and theNOCURRENCY compiler option is in effect,the dollar sign ($) is used as the defaultcurrency-sign value. See also currencysymbol.currency symbolA character used in a PICTURE clause toindicate the position of a currency signvalue in a numeric-edited item. Acurrency symbol can be defined by eitherthe CURRENCY compiler option or theCURRENCY SIGN clause in theSPECIAL-NAMES paragraph of theENVIRONMENT DIVISION. IftheCURRENCYSIGN clause is not specified and theNOCURRENCY compiler option is in effect,the dollar sign ($) is used as the defaultcurrency sign value and currency symbol.Multiple currency symbols and currencysign values can be defined. See alsocurrency sign value.* current recordIn file processing, the record that isavailable in the record area associatedwith a file.* current volume pointerA conceptual entity that points to thecurrent volume of a sequential file.D* data clauseA clause, appearing in a data descriptionentry in the DATA DIVISION of a <strong>COBOL</strong>program, that provides in<strong>for</strong>mationdescribing a particular attribute of a dataitem.* data description entryAn entry in the DATA DIVISION of a<strong>COBOL</strong> program that is composed of alevel-number followed by a data-name, ifrequired, and then followed by a set ofdata clauses, as required.DATA DIVISIONThe division of a <strong>COBOL</strong> program ormethod that describes the data to beprocessed by the program or method: thefiles to be used and the records containedwithin them; internal working-storagerecords that will be needed; data to bemade available in more than one programin the <strong>COBOL</strong> run unit.* data itemA unit of data (excluding literals) definedby a <strong>COBOL</strong> program or by the rules <strong>for</strong>function evaluation.* data-nameA user-defined word that names a dataitem described in a data description entry.When used in the general <strong>for</strong>mats,data-name represents a word that must846 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


not be reference-modified, subscripted, orqualified unless specifically permitted bythe rules <strong>for</strong> the <strong>for</strong>mat.date fieldAny of the following:v A data item whose data descriptionentry includes a DATE FORMAT clause.v A value returned by one of thefollowing intrinsic functions:DATE-OF-INTEGERDATE-TO-YYYYMMDDDATEVALDAY-OF-INTEGERDAY-TO-YYYYDDDYEAR-TO-YYYYYEARWINDOWv The conceptual data items DATE,DATE YYYYMMDD, DAY, and DAYYYYYDDD of the ACCEPT statement.v The result of certain arithmeticoperations. For details, see Arithmeticwith date fields (<strong>Enterprise</strong> <strong>COBOL</strong>Language Reference).The term date field refers to both expandeddate field and windowed date field. See alsonondate.date <strong>for</strong>matThe date pattern of a date field, specifiedin either of the following ways:v Explicitly, by the DATE FORMAT clause orDATEVAL intrinsic function argument-2v Implicitly, by statements and intrinsicfunctions that return date fields. Fordetails, see Date field (<strong>Enterprise</strong><strong>COBOL</strong> Language Reference).DBCSSee double-byte character set (DBCS).DBCS characterAny character defined in IBM’sdouble-byte character set.DBCS character positionSee character position.DBCS data itemA data item that is described by a PICTUREcharacter string that contains at least onesymbol G, or, when the NSYMBOL(DBCS)compiler option is in effect, at least onesymbol N. A DBCS data item has USAGEDISPLAY-1.* debugging lineAny line with aDintheindicator area ofthe line.* debugging sectionA section that contains a USE FORDEBUGGING statement.* declarative sentenceA compiler-directing sentence thatconsists of a single USE statementterminated by the separator period.* declarativesA set of one or more special-purposesections, written at the beginning of thePROCEDURE DIVISION, the first of which ispreceded by the key word DECLARATIVEand the last of which is followed by thekey words END DECLARATIVES. Adeclarative is composed of a sectionheader, followed by a USEcompiler-directing sentence, followed by aset of zero, one, or more associatedparagraphs.* de-editThe logical removal of all editingcharacters from a numeric-edited dataitem in order to determine the uneditednumeric value of the item.* delimited scope statementAny statement that includes its explicitscope terminator.* delimiterA character or a sequence of contiguouscharacters that identify the end of a stringof characters and separate that string ofcharacters from the following string ofcharacters. A delimiter is not part of thestring of characters that it delimits.dependent regionIn IMS, the MVS virtual storage regionthat contains message-driven programs,batch programs, or online utilities.* descending keyA key upon the values of which data isordered starting with the highest value ofkey down to the lowest value of key, inaccordance with the rules <strong>for</strong> comparingdata items.digitAny of the numerals from 0 through 9. In<strong>COBOL</strong>, the term is not used to refer toany other symbol.Glossary 847


* digit positionThe amount of physical storage requiredto store a single digit. This amount canvary depending on the usage specified inthe data description entry that defines thedata item.* direct accessThe facility to obtain data from storagedevices or to enter data into a storagedevice in such a way that the processdepends only on the location of that dataand not on a reference to data previouslyaccessed.display floating-point data itemA data item that is described implicitly orexplicitly as USAGE DISPLAY and that has aPICTURE character string that describes anexternal floating-point data item.* divisionA collection of zero, one, or more sectionsor paragraphs, called the division body,that are <strong>for</strong>med and combined inaccordance with a specific set of rules.Each division consists of the divisionheader and the related division body.There are four divisions in a <strong>COBOL</strong>program: Identification, Environment,Data, and Procedure.* division headerA combination of words followed by aseparator period that indicates thebeginning of a division. The divisionheaders are:IDENTIFICATION DIVISION.ENVIRONMENT DIVISION.DATA DIVISION.PROCEDURE DIVISION.DLL See dynamic link library (DLL).DLL applicationAn application that references importedprograms, functions, or variables.DLL linkageA CALL in a program that has beencompiled with the DLL and NODYNAMoptions; the CALL resolves to an exportedname in a separate module, or to anINVOKE of a method that is defined in aseparate module.do constructIn structured programming, a DOstatement is used to group a number of||statements in a procedure. In <strong>COBOL</strong>, aninline PERFORM statement functions in thesame way.do-untilIn structured programming, a do-untilloop will be executed at least once, anduntil a given condition is true. In <strong>COBOL</strong>,a TEST AFTER phrase used with thePERFORM statement functions in the sameway.do-whileIn structured programming, a do-whileloop will be executed if, and while, agiven condition is true. In <strong>COBOL</strong>, a TESTBEFORE phrase used with the PERFORMstatement functions in the same way.document type declarationAn XML element that contains or pointsto markup declarations that provide agrammar <strong>for</strong> a class of documents. Thisgrammar is known as a document typedefinition, or DTD.document type definition (DTD)The grammar <strong>for</strong> a class of XMLdocuments. See document type declaration.double-byte character set (DBCS)A set of characters in which eachcharacter is represented by 2 bytes.Languages such as Japanese, Chinese, andKorean, which contain more symbols thancan be represented by 256 code points,require double-byte character sets.Because each character requires 2 bytes,entering, displaying, and printing DBCScharacters requires hardware andsupporting software that areDBCS-capable.* dynamic accessAn access mode in which specific logicalrecords can be obtained from or placedinto a mass storage file in a nonsequentialmanner and obtained from a file in asequential manner during the scope of thesame OPEN statement.dynamic CALLA CALL literal statement in a program thathas been compiled with the DYNAM optionand the NODLL option, or a CALL identifierstatement in a program that has beencompiled with the NODLL option.dynamic link library (DLL)A file that contains executable code and848 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


data that are bound to a program at loadtime or run time, rather than duringlinking. Several applications can share thecode and data in a DLL simultaneously.Although a DLL is not part of theexecutable file <strong>for</strong> a program, it can berequired <strong>for</strong> an executable file to runproperly.dynamic storage area (DSA)Dynamically acquired storage composedof a register save area and an areaavailable <strong>for</strong> dynamic storage allocation(such as program variables). A DSA isallocated upon invocation of a program orfunction and persists <strong>for</strong> the duration ofthe invocation instance. DSAs aregenerally allocated within stack segmentsmanaged by Language Environment.* EBCDIC (Extended Binary-Coded DecimalInterchange Code)A coded character set based on 8-bitcoded characters.EBCDIC characterAny one of the symbols included in theEBCDIC (Extended Binary-Coded-DecimalInterchange Code) set.edited data itemA data item that has been modified bysuppressing zeros or inserting editingcharacters or both.* editing characterA single character or a fixed two-charactercombination belonging to the followingset:CharacterMeaningSpace0 Zero+ Plus- MinusCRCreditDBDebitZZero suppress* Check protect$ Currency sign, Comma (decimal point). Period (decimal point)/ Slant (<strong>for</strong>ward slash)EJB See <strong>Enterprise</strong> JavaBeans.EJB containerA container that implements the EJBcomponent contract of the J2EEarchitecture. This contract specifies aruntime environment <strong>for</strong> enterprise beansthat includes security, concurrency, lifecycle management, transaction,deployment, and other services. An EJBcontainer is provided by an EJB or J2EEserver. (Sun)EJB serverSoftware that provides services to an EJBcontainer. An EJB server can host one ormore EJB containers. (Sun)element (text element)One logical unit of a string of text, suchas the description of a single data item orverb, preceded by a unique codeidentifying the element type.* elementary itemA data item that is described as not beingfurther logically subdivided.encapsulationIn object-oriented programming, thetechnique that is used to hide the inherentdetails of an object. The object providesan interface that queries and manipulatesthe data without exposing its underlyingstructure. Synonymous with in<strong>for</strong>mationhiding.enclaveWhen running under LanguageEnvironment, an enclave is analogous to arun unit. An enclave can create otherenclaves by a LINK and the use of thesystem() function of C.encoding unitSee character encoding unit.end class markerA combination of words, followed by aseparator period, that indicates the end ofa <strong>COBOL</strong> class definition. The end classmarker is:END CLASS class-name.end method markerA combination of words, followed by aseparator period, that indicates the end ofa <strong>COBOL</strong> method definition. The endmethod marker is:END METHOD method-name.* end of PROCEDURE DIVISIONThe physical position of a <strong>COBOL</strong> sourceprogram after which no furtherprocedures appear.Glossary 849


* end program markerA combination of words, followed by aseparator period, that indicates the end ofa <strong>COBOL</strong> source program. The endprogram marker is:END PROGRAM program-name.enterprise beanA component that implements a businesstask and resides in an EJB container. (Sun)<strong>Enterprise</strong> JavaBeansA component architecture defined by SunMicrosystems, Inc. <strong>for</strong> the developmentand deployment of object-oriented,distributed, enterprise-level applications.* entryAny descriptive set of consecutive clausesterminated by a separator period andwritten in the IDENTIFICATION DIVISION,ENVIRONMENT DIVISION, orDATA DIVISIONof a <strong>COBOL</strong> program.* environment clauseA clause that appears as part of anENVIRONMENT DIVISION entry.ENVIRONMENT DIVISIONOne of the four main component parts ofa <strong>COBOL</strong> program, class definition, ormethod definition. The ENVIRONMENTDIVISION describes the computers wherethe source program is compiled and thosewhere the object program is run. Itprovides a linkage between the logicalconcept of files and their records, and thephysical aspects of the devices on whichfiles are stored.environment-nameA name, specified by IBM, that identifiessystem logical units, printer and cardpunch control characters, report codes,program switches or all of these. When anenvironment-name is associated with amnemonic-name in the ENVIRONMENTDIVISION, the mnemonic-name can besubstituted in any <strong>for</strong>mat in which suchsubstitution is valid.environment variableAny of a number of variables that definesome aspect of the computingenvironment, and are accessible toprograms that operate in thatenvironment. Environment variables canaffect the behavior of programs that aresensitive to the environment in whichthey operate.execution timeSee run time.execution-time environmentSee runtime environment.expanded date fieldA date field containing an expanded(four-digit) year. See also date field andexpanded year.expanded yearA date field that consists only of afour-digit year. Its value includes thecentury: <strong>for</strong> example, 1998. Compare withwindowed year.* explicit scope terminatorA reserved word that terminates the scopeof a particular PROCEDURE DIVISIONstatement.exponentA number that indicates the power towhich another number (the base) is to beraised. Positive exponents denotemultiplication; negative exponents denotedivision; and fractional exponents denotea root of a quantity. In <strong>COBOL</strong>, anexponential expression is indicated withthe symbol ** followed by the exponent.* expressionAn arithmetic or conditional expression.* extend modeThe state of a file after execution of anOPEN statement, with the EXTEND phrasespecified <strong>for</strong> that file, and be<strong>for</strong>e theexecution of a CL<strong>OS</strong>E statement, withoutthe REEL or UNIT phrase <strong>for</strong> that file.Extensible Markup LanguageSee XML.extensions<strong>COBOL</strong> syntax and semantics supportedby IBM compilers in addition to thosedescribed in Standard <strong>COBOL</strong> 85.external code pageFor XML documents, the value specifiedby the CODEPAGE compiler option.* external dataThe data that is described in a program asexternal data items and external fileconnectors.850 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


* external data itemA data item that is described as part of anexternal record in one or more programsof a run unit and that can be referencedfrom any program in which it isdescribed.* external data recordA logical record that is described in oneor more programs of a run unit andwhose constituent data items can bereferenced from any program in whichthey are described.external decimal data itemSee zoned decimal data item and nationaldecimal data item.* external file connectorA file connector that is accessible to oneor more object programs in the run unit.external floating-point data itemSee display floating-point data item andnational floating-point data item.external programThe outermost program. A program thatis not nested.* external switchA hardware or software device, definedand named by the implementor, which isused to indicate that one of two alternatestates exists.Ffactory dataData that is allocated once <strong>for</strong> a class andshared by all instances of the class.Factory data is declared in theWORKING-STORAGE SECTION of the DATADIVISION in the FACTORY paragraph of theclass definition, and is equivalent to Javaprivate static data.factory methodA method that is supported by a classindependently of an object instance.Factory methods are declared in theFACTORY paragraph of the class definition,and are equivalent to Java public staticmethods. They are typically used tocustomize the creation of objects.* figurative constantA compiler-generated value referencedthrough the use of certain reservedwords.* file A collection of logical records.* file attribute conflict conditionAn unsuccessful attempt has been madeto execute an input-output operation on afile and the file attributes, as specified <strong>for</strong>that file in the program, do not match thefixed attributes <strong>for</strong> that file.* file clauseA clause that appears as part of any ofthe following DATA DIVISION entries: filedescription entry (FD entry) andsort-merge file description entry (SDentry).* file connectorA storage area that contains in<strong>for</strong>mationabout a file and is used as the linkagebetween a file-name and a physical fileand between a file-name and itsassociated record area.* file control entryA SELECT clause and all its subordinateclauses that declare the relevant physicalattributes of a file.FILE-CONTROL paragraphA paragraph in the ENVIRONMENT DIVISIONin which the data files <strong>for</strong> a given sourceunit are declared.* file description entryAn entry in the FILE SECTION of the DATADIVISION that is composed of the levelindicator FD, followed by a file-name, andthen followed by a set of file clauses asrequired.* file-nameA user-defined word that names a fileconnector described in a file descriptionentry or a sort-merge file descriptionentry within the FILE SECTION of the DATADIVISION.* file organizationThe permanent logical file structureestablished at the time that a file iscreated.file position indicatorA conceptual entity that contains thevalue of the current key within the key ofreference <strong>for</strong> an indexed file, or the recordnumber of the current record <strong>for</strong> asequential file, or the relative recordnumber of the current record <strong>for</strong> arelative file, or indicates that no nextGlossary 851


logical record exists, or that an optionalinput file is not available, or that the ATEND condition already exists, or that novalid next record has been established.* FILE SECTIONThe section of the DATA DIVISION thatcontains file description entries andsort-merge file description entries togetherwith their associated record descriptions.file systemThe collection of files that con<strong>for</strong>m to aspecific set of data-record andfile-description protocols, and a set ofprograms that manage these files.* fixed file attributesIn<strong>for</strong>mation about a file that is establishedwhen a file is created and that cannotsubsequently be changed during theexistence of the file. These attributesinclude the organization of the file(sequential, relative, or indexed), theprime record key, the alternate recordkeys, the code set, the minimum andmaximum record size, the record type(fixed or variable), the collating sequenceof the keys <strong>for</strong> indexed files, the blockingfactor, the padding character, and therecord delimiter.* fixed-length recordA record associated with a file whose filedescription or sort-merge descriptionentry requires that all records contain thesame number of bytes.fixed-point itemA numeric data item defined with aPICTURE clause that specifies the locationof an optional sign, the number of digitsit contains, and the location of an optionaldecimal point. The <strong>for</strong>mat can be eitherbinary, packed decimal, or externaldecimal.floating pointA <strong>for</strong>mat <strong>for</strong> representing numbers inwhich a real number is represented by apair of distinct numerals. In afloating-point representation, the realnumber is the product of the fixed-pointpart (the first numeral) and a valueobtained by raising the implicitfloating-point base to a power denoted bythe exponent (the second numeral). Forexample, a floating-point representation ofthe number 0.0001234 is 0.1234 -3, where0.1234 is the mantissa and -3 is theexponent.floating-point data itemA numeric data item that contains afraction and an exponent. Its value isobtained by multiplying the fraction bythe base of the numeric data item raisedto the power that the exponent specifies.* <strong>for</strong>matA specific arrangement of a set of data.* functionA temporary data item whose value isdetermined at the time the function isreferenced during the execution of astatement.* function-identifierA syntactically correct combination ofcharacter strings and separators thatreferences a function. The data itemrepresented by a function is uniquelyidentified by a function-name with itsarguments, if any. A function-identifiercan include a reference-modifier. Afunction-identifier that references analphanumeric function can be specifiedanywhere in the general <strong>for</strong>mats that anidentifier can be specified, subject tocertain restrictions. A function-identifierthat references an integer or numericfunction can be referenced anywhere inthe general <strong>for</strong>mats that an arithmeticexpression can be specified.function-nameA word that names the mechanism whoseinvocation, along with requiredarguments, determines the value of afunction.function-pointer data itemA data item in which a pointer to anentry point can be stored. A data itemdefined with the USAGE ISFUNCTION-POINTER clause contains theaddress of a function entry point.Typically used to communicate with Cand Java programs.Ggarbage collectionThe automatic freeing by the Java runtimesystem of the memory <strong>for</strong> objects that areno longer referenced.852 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


* global nameA name that is declared in only oneprogram but that can be referenced fromthe program and from any programcontained within the program.Condition-names, data-names, file-names,record-names, report-names, and somespecial registers can be global names.global referenceA reference to an object that is outside thescope of a method.group item(1) A data item that is composed ofsubordinate data items. See alphanumericgroup item and national group item. (2)When not qualified explicitly or bycontext as a national group or analphanumeric group, the term refers togroups in general.grouping separatorA character used to separate units ofdigits in numbers <strong>for</strong> ease of reading. Thedefault is the character comma.Hheader label(1) A file label or data-set label thatprecedes the data records on a unit ofrecording media. (2) Synonym <strong>for</strong>beginning-of-file label.hide To redefine a factory or static method(inherited from a parent class) in asubclass.hierarchical file systemA collection of files and directories thatare organized in a hierarchical structureand can be accessed by using z/<strong>OS</strong>UNIX.* high-order endThe leftmost character of a string ofcharacters.hiperspaceIn a z/<strong>OS</strong> environment, a range of up to2 GB of contiguous virtual storageaddresses that a program can use as abuffer.IIBM <strong>COBOL</strong> extension<strong>COBOL</strong> syntax and semantics supportedby IBM compilers in addition to thosedescribed in Standard <strong>COBOL</strong> 85.IDENTIFICATION DIVISIONOne of the four main component parts ofa <strong>COBOL</strong> program, class definition, ormethod definition. The IDENTIFICATIONDIVISION identifies the program, class, ormethod. The IDENTIFICATION DIVISIONcan include the following documentation:author name, installation, or date.* identifierA syntactically correct combination ofcharacter strings and separators thatnames a data item. When referencing adata item that is not a function, anidentifier consists of a data-name,together with its qualifiers, subscripts,and reference-modifier, as required <strong>for</strong>uniqueness of reference. When referencinga data item that is a function, afunction-identifier is used.IGZCBSOThe <strong>Enterprise</strong> <strong>COBOL</strong> bootstrap routine.It must be link-edited with any modulethat contains a <strong>Enterprise</strong> <strong>COBOL</strong>program.* imperative statementA statement that either begins with animperative verb and specifies anunconditional action to be taken or is aconditional statement that is delimited byits explicit scope terminator (delimitedscope statement). An imperative statementcan consist of a sequence of imperativestatements.* implicit scope terminatorA separator period that terminates thescope of any preceding unterminatedstatement, or a phrase of a statement thatby its occurrence indicates the end of thescope of any statement contained withinthe preceding phrase.* indexA computer storage area or register, thecontent of which represents theidentification of a particular element in atable.* index data itemA data item in which the valuesassociated with an index-name can bestored in a <strong>for</strong>m specified by theimplementor.Glossary 853


indexed data-nameAn identifier that is composed of adata-name, followed by one or moreindex-names enclosed in parentheses.* indexed fileA file with indexed organization.* indexed organizationThe permanent logical file structure inwhich each record is identified by thevalue of one or more keys within thatrecord.indexingSynonymous with subscripting usingindex-names.* index-nameA user-defined word that names an indexassociated with a specific table.inheritanceA mechanism <strong>for</strong> using theimplementation of a class as the basis <strong>for</strong>another class. By definition, the inheritingclass con<strong>for</strong>ms to the inherited classes.<strong>Enterprise</strong> <strong>COBOL</strong> does not supportmultiple inheritance; a subclass has exactlyone immediate superclass.inheritance hierarchySee class hierarchy.* initial programA program that is placed into an initialstate every time the program is called in arun unit.* initial stateThe state of a program when it is firstcalled in a run unit.inlineIn a program, instructions that areexecuted sequentially, without branchingto routines, subroutines, or otherprograms.* input fileA file that is opened in the input mode.* input modeThe state of a file after execution of anOPEN statement, with the INPUT phrasespecified, <strong>for</strong> that file and be<strong>for</strong>e theexecution of a CL<strong>OS</strong>E statement, withoutthe REEL or UNIT phrase <strong>for</strong> that file.* input-output fileA file that is opened in the I-O mode.* INPUT-OUTPUT SECTIONThe section of the ENVIRONMENT DIVISIONthat names the files and the externalmedia required by an object program ormethod and that provides in<strong>for</strong>mationrequired <strong>for</strong> transmission and handling ofdata at run time.* input-output statementA statement that causes files to beprocessed by per<strong>for</strong>ming operations onindividual records or on the file as a unit.The input-output statements are ACCEPT(with the identifier phrase), CL<strong>OS</strong>E, DELETE,DISPLAY, OPEN, READ, REWRITE, SET (withthe TO ON or TO OFF phrase), START, andWRITE.* input procedureA set of statements, to which control isgiven during the execution of a SORTstatement, <strong>for</strong> the purpose of controllingthe release of specified records to besorted.instance dataData that defines the state of an object.The instance data introduced by a class isdefined in the WORKING-STORAGE SECTIONof the DATA DIVISION in the OBJECTparagraph of the class definition. Thestate of an object also includes the state ofthe instance variables introduced byclasses that are inherited by the currentclass. A separate copy of the instance datais created <strong>for</strong> each object instance.* integer(1) A numeric literal that does not includeany digit positions to the right of thedecimal point. (2) A numeric data itemdefined in the DATA DIVISION that doesnot include any digit positions to theright of the decimal point. (3) A numericfunction whose definition provides thatall digits to the right of the decimal pointare zero in the returned value <strong>for</strong> anypossible evaluation of the function.integer functionA function whose category is numeric andwhose definition does not include anydigit positions to the right of the decimalpoint.Interactive System Productivity Facility (ISPF)An IBM software product that provides amenu-driven interface <strong>for</strong> the TSO or VM854 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


user. ISPF includes library utilities, apowerful editor, and dialog management.interlanguage communication (ILC)The ability of routines written in differentprogramming languages to communicate.ILC support lets you readily buildapplications from component routineswritten in a variety of languages.intermediate resultAn intermediate field that contains theresults of a succession of arithmeticoperations.* internal dataThe data that is described in a programand excludes all external data items andexternal file connectors. Items describedin the LINKAGE SECTION of a program aretreated as internal data.* internal data itemA data item that is described in oneprogram in a run unit. An internal dataitem can have a global name.internal decimal data itemA data item that is described as USAGEPACKED-DECIMAL or USAGE COMP-3, and thathas a PICTURE character string that definesthe item as numeric (a valid combinationof symbols 9, S, P, orV). Synonymouswith packed-decimal data item.* internal file connectorA file connector that is accessible to onlyone object program in the run unit.internal floating-point data itemA data item that is described as USAGECOMP-1 or USAGE COMP-2. COMP-1 defines asingle-precision floating-point data item.COMP-2 defines a double-precisionfloating-point data item. There is noPICTURE clause associated with an internalfloating-point data item.* intrarecord data structureThe entire collection of groups andelementary data items from a logicalrecord that a contiguous subset of thedata description entries defines. Thesedata description entries include all entrieswhose level-number is greater than thelevel-number of the first data descriptionentry describing the intra-record datastructure.intrinsic functionA predefined function, such as acommonly used arithmetic function,called by a built-in function reference.* invalid key conditionA condition, at run time, caused when aspecific value of the key associated withan indexed or relative file is determinedto be not valid.* I-O-CONTROLThe name of an ENVIRONMENT DIVISIONparagraph in which object programrequirements <strong>for</strong> rerun points, sharing ofsame areas by several data files, andmultiple file storage on a singleinput-output device are specified.* I-O-CONTROL entryAn entry in the I-O-CONTROL paragraph ofthe ENVIRONMENT DIVISION; this entrycontains clauses that provide in<strong>for</strong>mationrequired <strong>for</strong> the transmission andhandling of data on named files duringthe execution of a program.* I-O modeThe state of a file after execution of anOPEN statement, with the I-O phrasespecified, <strong>for</strong> that file and be<strong>for</strong>e theexecution of a CL<strong>OS</strong>E statement withoutthe REEL or UNIT phase <strong>for</strong> that file.* I-O statusA conceptual entity that contains thetwo-character value indicating theresulting status of an input-outputoperation. This value is made available tothe program through the use of the FILESTATUS clause in the file control entry <strong>for</strong>the file.is-aA relationship that characterizes classesand subclasses in an inheritance hierarchy.Subclasses that have an is-a relationshipto a class inherit from that class.ISPF See Interactive System Productivity Facility(ISPF).iteration structureA program processing logic in which aseries of statements is repeated while acondition is true or until a condition istrue.JGlossary 855


J2EE See Java 2 Plat<strong>for</strong>m, <strong>Enterprise</strong> Edition(J2EE).Java 2 Plat<strong>for</strong>m, <strong>Enterprise</strong> Edition (J2EE)An environment <strong>for</strong> developing anddeploying enterprise applications, definedby Sun Microsystems, Inc. The J2EEplat<strong>for</strong>m consists of a set of services,application programming interfaces(APIs), and protocols that provide thefunctionality <strong>for</strong> developing multitiered,Web-based applications. (Sun)Java batch-processing program (JBP)An IMS batch-processing program thathas access to online databases and outputmessage queues. JBPs run online, but likeprograms in a batch environment, theyare started with JCL or in a TSO session.Java batch-processing regionAn IMS dependent region in which onlyJava batch-processing programs arescheduled.Java Database Connectivity (JDBC)A specification from Sun Microsystemsthat defines an API that enables Javaprograms to access databases.Java message-processing program (JMP)A Java application program that is drivenby transactions and has access to onlineIMS databases and message queues.Java message-processing regionAn IMS dependent region in which onlyJava message-processing programs arescheduled.Java Native Interface (JNI)A programming interface that lets Javacode that runs inside a Java virtualmachine (JVM) interoperate withapplications and libraries written in otherprogramming languages.Java virtual machine (JVM)A software implementation of a centralprocessing unit that runs compiled Javaprograms.JavaBeansA portable, plat<strong>for</strong>m-independent,reusable component model. (Sun)JBP See Java batch-processing program (JBP).JDBC See Java Database Connectivity (JDBC).JMP See Java message-processing program (JMP).job control language (JCL)A control language used to identify a jobto an operating system and to describethe job’s requirements.JVM See Java virtual machine (JVM).KKWhen referring to storage capacity, two tothe tenth power; 1024 in decimal notation.* key A data item that identifies the location ofa record, or a set of data items that serveto identify the ordering of data.* key of referenceThe key, either prime or alternate,currently being used to access recordswithin an indexed file.* keywordA reserved word or function-name whosepresence is required when the <strong>for</strong>mat inwhich the word appears is used in asource program.kilobyte (KB)One kilobyte equals 1024 bytes.L* language-nameA system-name that specifies a particularprogramming language.Language Environment-con<strong>for</strong>mingA characteristic of compiler products(such as <strong>Enterprise</strong> <strong>COBOL</strong>, <strong>COBOL</strong> <strong>for</strong><strong>OS</strong>/390 & VM, <strong>COBOL</strong> <strong>for</strong> MVS & VM,C/C++ <strong>for</strong> MVS & VM, PL/I <strong>for</strong> MVS &VM) that produce object code con<strong>for</strong>mingto the Language Environmentconventions.last-used stateA state that a program is in if its internalvalues remain the same as when theprogram was exited (the values are notreset to their initial values).* letterA character belonging to one of thefollowing two sets:1. Uppercase letters: A, B, C, D, E, F, G,H, I, J, K, L, M, N, O, P, Q, R, S, T, U,V, W, X, Y, Z2. Lowercase letters: a, b, c, d, e, f, g, h, i,j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y,z856 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


* level indicatorTwo alphabetic characters that identify aspecific type of file or a position in ahierarchy. The level indicators in the DATADIVISION are: CD, FD, and SD.* level-numberA user-defined word (expressed as atwo-digit number) that indicates thehierarchical position of a data item or thespecial properties of a data descriptionentry. Level-numbers in the range from 1through 49 indicate the position of a dataitem in the hierarchical structure of alogical record. Level-numbers in the range1 through 9 can be written either as asingle digit or as a zero followed by asignificant digit. Level-numbers 66, 77,and 88 identify special properties of adata description entry.* library-nameA user-defined word that names a<strong>COBOL</strong> library that the compiler is to use<strong>for</strong> compiling a given source program.* library textA sequence of text words, comment lines,the separator space, or the separatorpseudo-text delimiter in a <strong>COBOL</strong> library.Lilian dateThe number of days since the beginningof the Gregorian calendar. Day one isFriday, October 15, 1582. The Lilian date<strong>for</strong>mat is named in honor of Luigi Lilio,the creator of the Gregorian calendar.* linage-counterA special register whose value points tothe current position within the page body.link (1) The combination of the link connection(the transmission medium) and two linkstations, one at each end of the linkconnection. A link can be shared amongmultiple links in a multipoint ortoken-ring configuration. (2) Tointerconnect items of data or portions ofone or more computer programs; <strong>for</strong>example, linking object programs by alinkage editor to produce an executablefile.LINKAGE SECTIONThe section in the DATA DIVISION of thecalled program or invoked method thatdescribes data items available from thecalling program or invoking method. Bothlinkerthe calling program or invoking methodand the called program or invokedmethod can refer to these data items.A term that refers to either the z/<strong>OS</strong>linkage editor or the z/<strong>OS</strong> binder.literalA character string whose value isspecified either by the ordered set ofcharacters comprising the string or by theuse of a figurative constant.little-endianThe default <strong>for</strong>mat that Intel processorsuse to store binary data and UTF-16characters. In this <strong>for</strong>mat, the mostsignificant byte of a binary data item is atthe highest address and the mostsignificant byte of a UTF-16 character is atthe highest address. Compare withbig-endian.local referenceA reference to an object that is within thescope of your method.locale A set of attributes <strong>for</strong> a programexecution environment that indicatesculturally sensitive considerations, such ascharacter code page, collating sequence,date and time <strong>for</strong>mat, monetary valuerepresentation, numeric valuerepresentation, or language.* LOCAL-STORAGE SECTIONThe section of the DATA DIVISION thatdefines storage that is allocated and freedon a per-invocation basis, depending onthe value assigned in the VALUE clauses.* logical operatorOne of the reserved words AND, OR, orNOT. In the <strong>for</strong>mation of a condition,either AND, or OR, or both can be usedas logical connectives. NOT can be used<strong>for</strong> logical negation.* logical recordThe most inclusive data item. Thelevel-number <strong>for</strong> a record is 01. A recordcan be either an elementary item or agroup of items. Synonymous with record.* low-order endThe rightmost character of a string ofcharacters.MGlossary 857


main programIn a hierarchy of programs andsubroutines, the first program thatreceives control when the programs arerun within a process.makefileA text file that contains a list of the files<strong>for</strong> your application. The make utilityuses this file to update the target fileswith the latest changes.* mass storageA storage medium in which data can beorganized and maintained in both asequential manner and a nonsequentialmanner.* mass storage deviceA device that has a large storage capacity,such as a magnetic disk.* mass storage fileA collection of records that is stored in amass storage medium.* megabyte (MB)One megabyte equals 1,048,576 bytes.* merge fileA collection of records to be merged by aMERGE statement. The merge file is createdand can be used only by the mergefunction.message-processing program (MPP)An IMS application program that isdriven by transactions and has access toonline IMS databases and messagequeues.message queueThe data set on which messages arequeued be<strong>for</strong>e being processed by anapplication program or sent to a terminal.methodProcedural code that defines an operationsupported by an object and that isexecuted by an INVOKE statement on thatobject.* method definitionThe <strong>COBOL</strong> source code that defines amethod.* method identification entryAn entry in the METHOD-ID paragraph ofthe IDENTIFICATION DIVISION; this entrycontains a clause that specifies themethod-name.method invocationA communication from one object toanother that requests the receiving objectto execute a method.method-nameThe name of an object-oriented operation.When used to invoke the method, thename can be an alphanumeric or nationalliteral or a category alphanumeric orcategory national data item. When usedin the METHOD-ID paragraph to define themethod, the name must be analphanumeric or national literal.* mnemonic-nameA user-defined word that is associated inthe ENVIRONMENT DIVISION with aspecified implementor-name.module definition fileA file that describes the code segmentswithin a load module.MPP See message-processing program (MPP).multitaskingA mode of operation that provides <strong>for</strong> theconcurrent, or interleaved, execution oftwo or more tasks.multithreadingConcurrent operation of more than onepath of execution within a computer.Synonymous with multiprocessing.Nname A word (composed of not more than 30characters) that defines a <strong>COBOL</strong>operand.namespaceSee XML namespace.national character(1) A UTF-16 character in a USAGENATIONAL data item or national literal. (2)Any character represented in UTF-16.national character positionSee character position.national data itemA data item of category national,national-edited, or numeric-edited ofUSAGE NATIONAL.national decimal data itemAn external decimal data item that isdescribed implicitly or explicitly as USAGE858 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


NATIONAL and that contains a validcombination of PICTURE symbols 9, S, P,and V.national-edited data itemA data item that is described by a PICTUREcharacter string that contains at least oneinstance of the symbol N and at least oneof the simple insertion symbols B, 0, or/.A national-edited data item has USAGENATIONAL.national floating-point data itemAn external floating-point data item thatis described implicitly or explicitly asUSAGE NATIONAL and that has a PICTUREcharacter string that describes afloating-point data item.national group itemA group item that is explicitly orimplicitly described with a GROUP-USAGENATIONAL clause. A national group item isprocessed as though it were defined as anelementary data item of category national<strong>for</strong> operations such as INSPECT, STRING,and UNSTRING. This processing ensurescorrect padding and truncation ofnational characters, as contrasted withdefining USAGE NATIONAL data itemswithin an alphanumeric group item. Foroperations that require processing of theelementary items within a group, such asMOVE CORRESPONDING, ADD CORRESPONDING,and INITIALIZE, a national group isprocessed using group semantics.* native character setThe implementor-defined character setassociated with the computer specified inthe OBJECT-COMPUTER paragraph.* native collating sequenceThe implementor-defined collatingsequence associated with the computerspecified in the OBJECT-COMPUTERparagraph.native methodA Java method with an implementationthat is written in another programminglanguage, such as <strong>COBOL</strong>.* negated combined conditionThe NOT logical operator immediatelyfollowed by a parenthesized combinedcondition. See also condition and combinedcondition.* negated simple conditionThe NOT logical operator immediatelyfollowed by a simple condition. See alsocondition and simple condition.nested programA program that is directly containedwithin another program.* next executable sentenceThe next sentence to which control will betransferred after execution of the currentstatement is complete.* next executable statementThe next statement to which control willbe transferred after execution of thecurrent statement is complete.* next recordThe record that logically follows thecurrent record of a file.* noncontiguous itemsElementary data items in theWORKING-STORAGE SECTION and LINKAGESECTION that bear no hierarchicrelationship to other data items.nondateAny of the following items:v A data item whose date descriptionentry does not include the DATE FORMATclausev A literalv A date field that has been convertedusing the UNDATE functionv A reference-modified date fieldv The result of certain arithmeticoperations that can include date fieldoperands; <strong>for</strong> example, the differencebetween two compatible date fieldsnull A figurative constant that is used toassign, to pointer data items, the value ofan address that is not valid. NULLS can beused wherever NULL can be used.* numeric characterA character that belongs to the followingset of digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.numeric data item(1) A data item whose description restrictsits content to a value represented bycharacters chosen from the digits 0through 9. If signed, the item can alsocontain a +, -, or other representation ofan operational sign. (2) A data item ofGlossary 859


category numeric, internal floating-point,or external floating-point. A numeric dataitem can have USAGE DISPLAY, NATIONAL,PACKED-DECIMAL, BINARY, COMP, COMP-1,COMP-2, COMP-3, COMP-4, orCOMP-5.numeric-edited data itemA data item that contains numeric data ina <strong>for</strong>m suitable <strong>for</strong> use in printed output.The data item can consist of externaldecimal digits from 0 through 9, thedecimal separator, commas, the currencysign, sign control characters, and otherediting characters. A numeric-edited itemcan be represented in either USAGEDISPLAY or USAGE NATIONAL.* numeric functionA function whose class and category arenumeric but that <strong>for</strong> some possibleevaluation does not satisfy therequirements of integer functions.* numeric literalA literal composed of one or morenumeric characters that can contain adecimal point or an algebraic sign, orboth. The decimal point must not be therightmost character. The algebraic sign, ifpresent, must be the leftmost character.OobjectAn entity that has state (its data values)and operations (its methods). An object isa way to encapsulate state and behavior.Each object in the class is said to be aninstance of the class.object codeOutput from a compiler or assembler thatis itself executable machine code or issuitable <strong>for</strong> processing to produceexecutable machine code.* OBJECT-COMPUTERThe name of an ENVIRONMENT DIVISIONparagraph in which the computerenvironment, where the object program isrun, is described.* object computer entryAn entry in the OBJECT-COMPUTERparagraph of the ENVIRONMENT DIVISION;this entry contains clauses that describethe computer environment in which theobject program is to be executed.object deckA portion of an object program suitable asinput to a linkage editor. Synonymouswith object module and text deck.object instanceSee object.object moduleSynonym <strong>for</strong> object deck or text deck.* object of entryA set of operands and reserved words,within a DATA DIVISION entry of a <strong>COBOL</strong>program, that immediately follows thesubject of the entry.object-oriented programmingA programming approach based on theconcepts of encapsulation and inheritance.Unlike procedural programmingtechniques, object-oriented programmingconcentrates on the data objects thatcomprise the problem and how they aremanipulated, not on how something isaccomplished.object programA set or group of executablemachine-language instructions and othermaterial designed to interact with data toprovide problem solutions. In this context,an object program is generally themachine language result of the operationof a <strong>COBOL</strong> compiler on a sourceprogram or class definition. Where thereis no danger of ambiguity, the wordprogram can be used in place of objectprogram.object referenceA value that identifies an instance of aclass. If the class is not specified, theobject reference is universal and canapply to instances of any class.* object timeThe time at which an object program isexecuted. Synonymous with run time.* obsolete elementA <strong>COBOL</strong> language element in Standard<strong>COBOL</strong> 85 that was deleted fromStandard <strong>COBOL</strong> 2002.ODO objectIn the example below, X is the object ofthe OCCURS DEPENDING ON clause (ODOobject).860 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


WORKING-STORAGE SECTION01 TABLE-1.05 X PICS9.05 Y OCCURS 3 TIMESDEPENDING ON X PIC X.The value of the ODO object determineshow many of the ODO subject appear inthe table.ODO subjectIn the example above, Y is the subject ofthe OCCURS DEPENDING ON clause (ODOsubject). The number of Y ODO subjectsthat appear in the table depends on thevalue of X.* open modeThe state of a file after execution of anOPEN statement <strong>for</strong> that file and be<strong>for</strong>e theexecution of a CL<strong>OS</strong>E statement withoutthe REEL or UNIT phrase <strong>for</strong> that file. Theparticular open mode is specified in theOPEN statement as either INPUT, OUTPUT,I-O, orEXTEND.* operand(1) The general definition of operand is“the component that is operated upon.”(2) For the purposes of this document,any lowercase word (or words) thatappears in a statement or entry <strong>for</strong>matcan be considered to be an operand and,as such, is an implied reference to thedata indicated by the operand.operationA service that can be requested of anobject.* operational signAn algebraic sign that is associated with anumeric data item or a numeric literal, toindicate whether its value is positive ornegative.optional fileA file that is declared as being notnecessarily available each time the objectprogram is run.* optional wordA reserved word that is included in aspecific <strong>for</strong>mat only to improve thereadability of the language. Its presence isoptional to the user when the <strong>for</strong>mat inwhich the word appears is used in asource unit.* output fileA file that is opened in either outputmode or extend mode.* output modeThe state of a file after execution of anOPEN statement, with the OUTPUT or EXTENDphrase specified, <strong>for</strong> that file and be<strong>for</strong>ethe execution of a CL<strong>OS</strong>E statementwithout the REEL or UNIT phrase <strong>for</strong> thatfile.* output procedureA set of statements to which control isgiven during execution of a SORTstatement after the sort function iscompleted, or during execution of a MERGEstatement after the merge function reachesa point at which it can select the nextrecord in merged order when requested.overflow conditionA condition that occurs when a portion ofthe result of an operation exceeds thecapacity of the intended unit of storage.overloadTo define a method with the same nameas another method that is available in thesame class, but with a different signature.See also signature.overrideTo redefine an instance method (inheritedfrom a parent class) in a subclass.PpackageA group of related Java classes, which canbe imported individually or as a whole.packed-decimal data itemSee internal decimal data item.padding characterAn alphanumeric or national characterthat is used to fill the unused characterpositions in a physical record.page A vertical division of output data thatrepresents a physical separation of thedata. The separation is based on internallogical requirements or externalcharacteristics of the output medium orboth.* page bodyThat part of the logical page in whichlines can be written or spaced or both.Glossary 861


* paragraphIn the PROCEDURE DIVISION, aparagraph-name followed by a separatorperiod and by zero, one, or moresentences. In the IDENTIFICATIONDIVISION and ENVIRONMENT DIVISION, aparagraph header followed by zero, one,or more entries.* paragraph headerA reserved word, followed by theseparator period, that indicates thebeginning of a paragraph in theIDENTIFICATION DIVISION andENVIRONMENT DIVISION. The permissibleparagraph headers in the IDENTIFICATIONDIVISION are:PROGRAM-ID. (Program IDENTIFICATIONDIVISION)CLASS-ID. (Class IDENTIFICATION DIVISION)METHOD-ID. (Method IDENTIFICATIONDIVISION)AUTHOR.INSTALLATION.DATE-WRITTEN.DATE-COMPILED.SECURITY.The permissible paragraph headers in theENVIRONMENT DIVISION are:SOURCE-COMPUTER.OBJECT-COMPUTER.SPECIAL-NAMES.REP<strong>OS</strong>ITORY. (Program or ClassCONFIGURATION SECTION)FILE-CONTROL.I-O-CONTROL.* paragraph-nameA user-defined word that identifies andbegins a paragraph in the PROCEDUREDIVISION.parameter(1) Data passed between a callingprogram and a called program. (2) A dataelement in the USING phrase of a methodinvocation. Arguments provide additionalin<strong>for</strong>mation that the invoked method canuse to per<strong>for</strong>m the requested operation.Persistent Reusable JVMA JVM that can be serially reused <strong>for</strong>transaction processing by resetting theJVM between transactions. The resetphase restores the JVM to a knowninitialization state.* phraseAn ordered set of one or moreconsecutive <strong>COBOL</strong> character strings that<strong>for</strong>m a portion of a <strong>COBOL</strong> proceduralstatement or of a <strong>COBOL</strong> clause.* physical recordSee block.pointer data itemA data item in which address values canbe stored. Data items are explicitlydefined as pointers with the USAGE ISPOINTER clause. ADDRESS OF specialregisters are implicitly defined as pointerdata items. Pointer data items can becompared <strong>for</strong> equality or moved to otherpointer data items.port (1) To modify a computer program toenable it to run on a different plat<strong>for</strong>m.(2) In the Internet suite of protocols, aspecific logical connector between theTransmission Control Protocol (TCP) orthe User Datagram Protocol (UDP) and ahigher-level protocol or application. Aport is identified by a port number.portabilityThe ability to transfer an applicationprogram from one application plat<strong>for</strong>m toanother with relatively few changes to thesource program.preinitializationThe initialization of the <strong>COBOL</strong> runtimeenvironment in preparation <strong>for</strong> multiplecalls from programs, especiallynon-<strong>COBOL</strong> programs. The environmentis not terminated until an explicittermination.* prime record keyA key whose contents uniquely identify arecord within an indexed file.* priority-numberA user-defined word that classifiessections in the PROCEDURE DIVISION <strong>for</strong>purposes of segmentation. Segmentnumbers can contain only the characters 0through 9. A segment number can beexpressed as either one or two digits.privateAs applied to factory data or instancedata, accessible only by methods of theclass that defines the data.* procedureA paragraph or group of logicallysuccessive paragraphs, or a section or862 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


group of logically successive sections,within the PROCEDURE DIVISION.* procedure branching statementA statement that causes the explicittransfer of control to a statement otherthan the next executable statement in thesequence in which the statements arewritten in the source code. The procedurebranching statements are: ALTER, CALL,EXIT, EXIT PROGRAM, GO TO, MERGE (with theOUTPUT PROCEDURE phrase), PERFORM andSORT (with the INPUT PROCEDURE or OUTPUTPROCEDURE phrase), XML PARSE.PROCEDURE DIVISIONThe <strong>COBOL</strong> division that containsinstructions <strong>for</strong> solving a problem.procedure integrationOne of the functions of the <strong>COBOL</strong>optimizer is to simplify calls to per<strong>for</strong>medprocedures or contained programs.PERFORM procedure integration is theprocess whereby a PERFORM statement isreplaced by its per<strong>for</strong>med procedures.Contained program procedure integrationis the process where a call to a containedprogram is replaced by the program code.* procedure-nameA user-defined word that is used to namea paragraph or section in the PROCEDUREDIVISION. It consists of a paragraph-name(which can be qualified) or asection-name.procedure-pointer data itemA data item in which a pointer to anentry point can be stored. A data itemdefined with the USAGE ISPROCEDURE-POINTER clause contains theaddress of a procedure entry point.Typically used to communicate with<strong>COBOL</strong> and Language Environmentprograms.processThe course of events that occurs duringthe execution of all or part of a program.Multiple processes can run concurrently,and programs that run within a processcan share resources.program(1) A sequence of instructions suitable <strong>for</strong>processing by a computer. Processing mayinclude the use of a compiler to preparethe program <strong>for</strong> execution, as well as aruntime environment to execute it. (2) Alogical assembly of one or moreinterrelated modules. Multiple copies ofthe same program can be run in differentprocesses.* program identification entryIn the PROGRAM-ID paragraph of theIDENTIFICATION DIVISION, an entry thatcontains clauses that specify theprogram-name and assign selectedprogram attributes to the program.program-nameIn the IDENTIFICATION DIVISION and theend program marker, a user-defined wordor alphanumeric literal that identifies a<strong>COBOL</strong> source program.projectThe complete set of data and actions thatare required to build a target, such as adynamic link library (DLL) or otherexecutable (EXE).* pseudo-textA sequence of text words, comment lines,or the separator space in a sourceprogram or <strong>COBOL</strong> library bounded by,but not including, pseudo-text delimiters.* pseudo-text delimiterTwo contiguous equal sign characters (==)used to delimit pseudo-text.* punctuation characterA character that belongs to the followingset:CharacterMeaning, Comma; Semicolon: Colon. Period (full stop)″ Quotation mark( Left parenthesis) Right parenthesisSpace= Equal signQQSAM (queued sequential access method)An extended version of the basicsequential access method (BSAM). Whenthis method is used, a queue is <strong>for</strong>med ofinput data blocks that are awaitingprocessing or of output data blocks thatGlossary 863


have been processed and are awaitingtransfer to auxiliary storage or to anoutput device.* qualified data-nameAn identifier that is composed of adata-name followed by one or more setsof either of the connectives OF and INfollowed by a data-name qualifier.* qualifier(1) A data-name or a name associatedwith a level indicator that is used in areference either together with anotherdata-name (which is the name of an itemthat is subordinate to the qualifier) ortogether with a condition-name. (2) Asection-name that is used in a referencetogether with a paragraph-name specifiedin that section. (3) A library-name that isused in a reference together with atext-name associated with that library.R* random accessAn access mode in which theprogram-specified value of a key dataitem identifies the logical record that isobtained from, deleted from, or placedinto a relative or indexed file.* recordSee logical record.* record areaA storage area allocated <strong>for</strong> the purposeof processing the record described in arecord description entry in the FILESECTION of the DATA DIVISION. IntheFILESECTION, the current number of characterpositions in the record area is determinedby the explicit or implicit RECORD clause.* record descriptionSee record description entry.* record description entryThe total set of data description entriesassociated with a particular record.Synonymous with record description.record keyA key whose contents identify a recordwithin an indexed file.* record-nameA user-defined word that names a recorddescribed in a record description entry inthe DATA DIVISION of a <strong>COBOL</strong> program.* record numberThe ordinal number of a record in the filewhose organization is sequential.recording modeThe <strong>for</strong>mat of the logical records in a file.Recording mode can be F (fixed length), V(variable length), S (spanned), or U(undefined).recursionA program calling itself or being directlyor indirectly called by one of its calledprograms.recursively capableA program is recursively capable (can becalled recursively) if the RECURSIVEattribute is on the PROGRAM-ID statement.reel A discrete portion of a storage medium,the dimensions of which are determinedby each implementor that contains part ofa file, all of a file, or any number of files.Synonymous with unit and volume.reentrantThe attribute of a program or routine thatlets more than one user share a singlecopy of a load module.* reference <strong>for</strong>matA <strong>for</strong>mat that provides a standard method<strong>for</strong> describing <strong>COBOL</strong> source programs.reference modificationA method of defining a new categoryalphanumeric, category DBCS, or categorynational data item by specifying theleftmost character and length relative tothe leftmost character position of a USAGEDISPLAY, DISPLAY-1, orNATIONAL dataitem.* reference-modifierA syntactically correct combination ofcharacter strings and separators thatdefines a unique data item. It includes adelimiting left parenthesis separator, theleftmost character position, a colonseparator, optionally a length, and adelimiting right parenthesis separator.* relationSee relational operator or relation condition.* relation characterA character that belongs to the followingset:864 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Character Meaning> Greater than< Less than= Equal to* relation conditionThe proposition (<strong>for</strong> which a truth valuecan be determined) that the value of anarithmetic expression, data item,alphanumeric literal, or index-name has aspecific relationship to the value ofanother arithmetic expression, data item,alphanumeric literal, or index name. Seealso relational operator.* relational operatorA reserved word, a relation character, agroup of consecutive reserved words, or agroup of consecutive reserved words andrelation characters used in theconstruction of a relation condition. Thepermissible operators and their meaningsare:CharacterIS GREATER THANIS >IS NOT GREATER THANIS NOT >IS LESS THANIS


SSBCS See single-byte character set (SBCS).scope terminatorA <strong>COBOL</strong> reserved word that marks theend of certain PROCEDURE DIVISIONstatements. It can be either explicit(END-ADD, <strong>for</strong> example) or implicit(separator period).* sectionA set of zero, one, or more paragraphs orentities, called a section body, the first ofwhich is preceded by a section header.Each section consists of the section headerand the related section body.* section headerA combination of words followed by aseparator period that indicates thebeginning of a section in any of thesedivisions: ENVIRONMENT, DATA, orPROCEDURE. IntheENVIRONMENT DIVISIONand DATA DIVISION, a section header iscomposed of reserved words followed bya separator period. The permissiblesection headers in the ENVIRONMENTDIVISION are:CONFIGURATION SECTION.INPUT-OUTPUT SECTION.The permissible section headers in theDATA DIVISION are:FILE SECTION.WORKING-STORAGE SECTION.LOCAL-STORAGE SECTION.LINKAGE SECTION.In the PROCEDURE DIVISION, a sectionheader is composed of a section-name,followed by the reserved word SECTION,followed by a separator period.* section-nameA user-defined word that names a sectionin the PROCEDURE DIVISION.selection structureA program processing logic in which oneor another series of statements isexecuted, depending on whether acondition is true or false.* sentenceA sequence of one or more statements, thelast of which is terminated by a separatorperiod.* separately compiled programA program that, together with itscontained programs, is compiledseparately from all other programs.* separatorA character or two or more contiguouscharacters used to delimit characterstrings.* separator commaA comma (,) followed by a space used todelimit character strings.* separator periodA period (.) followed by a space used todelimit character strings.* separator semicolonA semicolon (;) followed by a space usedto delimit character strings.sequence structureA program processing logic in which aseries of statements is executed insequential order.* sequential accessAn access mode in which logical recordsare obtained from or placed into a file ina consecutive predecessor-to-successorlogical record sequence determined by theorder of records in the file.* sequential fileA file with sequential organization.* sequential organizationThe permanent logical file structure inwhich a record is identified by apredecessor-successor relationshipestablished when the record is placed intothe file.serial searchA search in which the members of a setare consecutively examined, beginningwith the first member and ending withthe last.session beanIn EJB, an enterprise bean that is createdby a client and that usually exists only <strong>for</strong>the duration of a single client/serversession. (Sun)77-level-description-entryA data description entry that describes anoncontiguous data item that haslevel-number 77.866 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


* sign conditionThe proposition (<strong>for</strong> which a truth valuecan be determined) that the algebraicvalue of a data item or an arithmeticexpression is either less than, greater than,or equal to zero.signature(1) The name of an operation and itsparameters. (2) The name of a methodand the number and types of its <strong>for</strong>malparameters.* simple conditionAny single condition chosen from this set:v Relation conditionv Class conditionv Condition-name conditionv Switch-status conditionv Sign conditionSee also condition and negated simplecondition.single-byte character set (SBCS)A set of characters in which eachcharacter is represented by a single byte.See also ASCII and EBCDIC (ExtendedBinary-Coded Decimal Interchange Code).slack bytesBytes inserted between data items orrecords to ensure correct alignment ofsome numeric items. Slack bytes containno meaningful data. In some cases, theyare inserted by the compiler; in others, itis the responsibility of the programmer toinsert them. The SYNCHRONIZED clauseinstructs the compiler to insert slack byteswhen they are needed <strong>for</strong> properalignment. Slack bytes between recordsare inserted by the programmer.* sort fileA collection of records to be sorted by aSORT statement. The sort file is createdand can be used by the sort function only.* sort-merge file description entryAn entry in the FILE SECTION of the DATADIVISION that is composed of the levelindicator SD, followed by a file-name, andthen followed by a set of file clauses asrequired.* SOURCE-COMPUTERThe name of an ENVIRONMENT DIVISIONparagraph in which the computer||environment, where the source program iscompiled, is described.* source computer entryAn entry in the SOURCE-COMPUTERparagraph of the ENVIRONMENT DIVISION;this entry contains clauses that describethe computer environment in which thesource program is to be compiled.* source itemAn identifier designated by a SOURCEclause that provides the value of aprintable item.source programAlthough a source program can berepresented by other <strong>for</strong>ms and symbols,in this document the term always refersto a syntactically correct set of <strong>COBOL</strong>statements. A <strong>COBOL</strong> source programcommences with the IDENTIFICATIONDIVISION or a COPY statement andterminates with the end program marker,if specified, or with the absence ofadditional source program lines.source unitA unit of <strong>COBOL</strong> source code that can beseparately compiled: a program or a classdefinition. Also known as a compilationunit.special characterA character that belongs to the followingset:Character Meaning+ Plus sign- Minus sign (hyphen)* Asterisk/ Slant (<strong>for</strong>ward slash)= Equal sign$ Currency sign, Comma; Semicolon. Period (decimal point, full stop)″ Quotation mark’ Apostrophe( Left parenthesis) Right parenthesis> Greater than< Less than: Colon_UnderscoreSPECIAL-NAMESThe name of an ENVIRONMENT DIVISIONGlossary 867


paragraph in which environment-namesare related to user-specifiedmnemonic-names.* special names entryAn entry in the SPECIAL-NAMES paragraphof the ENVIRONMENT DIVISION; this entryprovides means <strong>for</strong> specifying thecurrency sign; choosing the decimal point;specifying symbolic characters; relatingimplementor-names to user-specifiedmnemonic-names; relatingalphabet-names to character sets orcollating sequences; and relatingclass-names to sets of characters.* special registersCertain compiler-generated storage areaswhose primary use is to store in<strong>for</strong>mationproduced in conjunction with the use of aspecific <strong>COBOL</strong> feature.Standard <strong>COBOL</strong> 85The <strong>COBOL</strong> language defined by thefollowing standards:v ANSI INCITS 23-1985, <strong>Programming</strong>languages - <strong>COBOL</strong>, as amended byANSI INCITS 23a-1989, <strong>Programming</strong>Languages - <strong>COBOL</strong> - Intrinsic FunctionModule <strong>for</strong> <strong>COBOL</strong> and ANSI INCITS23b-1993, <strong>Programming</strong> Languages -Correction Amendment <strong>for</strong> <strong>COBOL</strong>v ISO 1989:1985, <strong>Programming</strong> languages -<strong>COBOL</strong>, as amended by ISO/IEC1989/AMD1:1992, <strong>Programming</strong> languages- <strong>COBOL</strong>: Intrinsic function module andISO/IEC 1989/AMD2:1994, <strong>Programming</strong>languages - Correction and clarificationamendment <strong>for</strong> <strong>COBOL</strong>* statementA syntactically valid combination ofwords, literals, and separators, beginningwith a verb, written in a <strong>COBOL</strong> sourceprogram.structured programmingA technique <strong>for</strong> organizing and coding acomputer program in which the programcomprises a hierarchy of segments, eachsegment having a single entry point and asingle exit point. Control is passeddownward through the structure withoutunconditional branches to higher levels ofthe hierarchy.* subclassA class that inherits from another class.When two classes in an inheritancerelationship are considered together, thesubclass is the inheritor or inheritingclass; the superclass is the inheritee orinherited class.* subject of entryAn operand or reserved word thatappears immediately following the levelindicator or the level-number in a DATADIVISION entry.* subprogramSee called program.* subscriptAn occurrence number that is representedby either an integer, a data-nameoptionally followed by an integer with theoperator + or -, or an index-nameoptionally followed by an integer with theoperator + or -, that identifies a particularelement in a table. A subscript can be theword ALL when the subscripted identifieris used as a function argument <strong>for</strong> afunction allowing a variable number ofarguments.* subscripted data-nameAn identifier that is composed of adata-name followed by one or moresubscripts enclosed in parentheses.substitution characterA character that is used in a conversionfrom a source code page to a target codepage to represent a character that is notdefined in the target code page.* superclassA class that is inherited by another class.See also subclass.surrogate pairIn the UTF-16 <strong>for</strong>mat of Unicode, a pairof encoding units that together representsa single Unicode graphic character. Thefirst unit of the pair is called a highsurrogate and the second a low surrogate.The code value of a high surrogate is inthe range X’D800’ through X’DBFF’. Thecode value of a low surrogate is in therange X’DC00’ through X’DFFF’.Surrogate pairs provide <strong>for</strong> morecharacters than the 65,536 characters thatfit in the Unicode 16-bit coded characterset.switch-status conditionThe proposition (<strong>for</strong> which a truth value868 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


can be determined) that an UPSI switch,capable of being set to an on or off status,has been set to a specific status.* symbolic-characterA user-defined word that specifies auser-defined figurative constant.syntax(1) The relationship among characters orgroups of characters, independent of theirmeanings or the manner of theirinterpretation and use. (2) The structureof expressions in a language. (3) The rulesgoverning the structure of a language. (4)The relationship among symbols. (5) Therules <strong>for</strong> the construction of a statement.* system-nameA <strong>COBOL</strong> word that is used tocommunicate with the operatingenvironment.T* tableA set of logically consecutive items ofdata that are defined in the DATA DIVISIONby means of the OCCURS clause.* table elementA data item that belongs to the set ofrepeated items comprising a table.text deckSynonym <strong>for</strong> object deck or object module.* text-nameA user-defined word that identifies librarytext.* text wordA character or a sequence of contiguouscharacters between margin A and marginR in a <strong>COBOL</strong> library, source program, orpseudo-text that is any of the followingcharacters:v A separator, except <strong>for</strong> space; apseudo-text delimiter; and the openingand closing delimiters <strong>for</strong> alphanumericliterals. The right parenthesis and leftparenthesis characters, regardless ofcontext within the library, sourceprogram, or pseudo-text, are alwaysconsidered text words.v A literal including, in the case ofalphanumeric literals, the openingquotation mark and the closingquotation mark that bound the literal.threadv Any other sequence of contiguous<strong>COBOL</strong> characters except commentlines and the word COPY bounded byseparators that are neither a separatornor a literal.A stream of computer instructions(initiated by an application within aprocess) that is in control of a process.token In the <strong>COBOL</strong> editor, a unit of meaning ina program. A token can contain data, alanguage keyword, an identifier, or otherpart of the language syntax.top-down designThe design of a computer program usinga hierarchic structure in which relatedfunctions are per<strong>for</strong>med at each level ofthe structure.top-down developmentSee structured programming.trailer-label(1) A file or data-set label that follows thedata records on a unit of recordingmedium. (2) Synonym <strong>for</strong> end-of-file label.troubleshootTo detect, locate, and eliminate problemsin using computer software.* truth valueThe representation of the result of theevaluation of a condition in terms of oneof two values: true or false.typed object referenceA data-name that can refer only to anobject of a specified class or any of itssubclasses.U* unary operatorA plus (+) or a minus (-) sign thatprecedes a variable or a left parenthesis inan arithmetic expression and that has theeffect of multiplying the expression by +1or -1, respectively.UnicodeA universal character encoding standardthat supports the interchange, processing,and display of text that is written in anyof the languages of the modern world.There are multiple encoding schemes torepresent Unicode, including UTF-8,UTF-16, and UTF-32. <strong>Enterprise</strong> <strong>COBOL</strong>Glossary 869


supports Unicode using UTF-16 inbig-endian <strong>for</strong>mat as the representation<strong>for</strong> the national data type.Uni<strong>for</strong>m Resource Identifier (URI)A sequence of characters that uniquelynames a resource; in <strong>Enterprise</strong> <strong>COBOL</strong>,the identifier of a namespace. URI syntaxis defined by the document Uni<strong>for</strong>mResource Identifier (URI): Generic Syntax.unit A module of direct access, the dimensionsof which are determined by IBM.universal object referenceA data-name that can refer to an object ofany class.unrestricted storageStorage below the 2-GB bar. It can beabove or below the 16-MB line. If it isabove the 16-MB line, it is addressableonly in 31-bit mode.* unsuccessful executionThe attempted execution of a statementthat does not result in the execution of allthe operations specified by that statement.The unsuccessful execution of a statementdoes not affect any data referenced bythat statement, but can affect statusindicators.UPSI switchA program switch that per<strong>for</strong>ms thefunctions of a hardware switch. Eight areprovided: UPSI-0 through UPSI-7.URI See Uni<strong>for</strong>m Resource Identifier (URI).* user-defined wordA <strong>COBOL</strong> word that must be supplied bythe user to satisfy the <strong>for</strong>mat of a clauseor statement.V* variableA data item whose value can be changedby execution of the object program. Avariable used in an arithmetic expressionmust be a numeric elementary item.variable-length itemA group item that contains a tabledescribed with the DEPENDING phrase ofthe OCCURS clause.* variable-length recordA record associated with a file whose filedescription or sort-merge descriptionentry permits records to contain a varyingnumber of character positions.* variable-occurrence data itemA variable-occurrence data item is a tableelement that is repeated a variablenumber of times. Such an item mustcontain an OCCURS DEPENDING ON clause inits data description entry or besubordinate to such an item.* variably located groupA group item following, and notsubordinate to, a variable-length table inthe same record. The group item can bean alphanumeric group or a nationalgroup.* variably located itemA data item following, and notsubordinate to, a variable-length table inthe same record.* verbA word that expresses an action to betaken by a <strong>COBOL</strong> compiler or objectprogram.volumeA module of external storage. For tapedevices it is a reel; <strong>for</strong> direct-accessdevices it is a unit.volume switch proceduresSystem-specific procedures that areexecuted automatically when the end of aunit or reel has been reached be<strong>for</strong>eend-of-file has been reached.VSAM file systemA file system that supports <strong>COBOL</strong>sequential, relative, and indexedorganizations.WWeb serviceA modular application that per<strong>for</strong>msspecific tasks and is accessible throughopen protocols like HTTP and SOAP.white spaceCharacters that introduce space into adocument. They are:v Spacev Horizontal tabulationv Carriage returnv Line feedv Next line870 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


as named in the Unicode Standard.windowed date fieldA date field containing a windowed(two-digit) year. See also date field andwindowed year.windowed yearA date field that consists only of atwo-digit year. This two-digit year can beinterpreted using a century window. Forexample, 09 could be interpreted as 2009.See also century window. Compare withexpanded year.* wordA character string of not more than 30characters that <strong>for</strong>ms a user-defined word,a system-name, a reserved word, or afunction-name.* WORKING-STORAGE SECTIONThe section of the DATA DIVISION thatdescribes working-storage data items,composed either of noncontiguous itemsor working-storage records or of both.workstationA generic term <strong>for</strong> computers used byend users including personal computers,3270 terminals, intelligent workstations,and UNIX terminals. Often a workstationis connected to a mainframe or to anetwork.wrapperAn object that provides an interfacebetween object-oriented code andprocedure-oriented code. Using wrapperslets programs be reused and accessed byother systems.XxXMLThe symbol in a PICTURE clause that canhold any character in the character set ofthe computer.Extensible Markup Language. A standardmetalanguage <strong>for</strong> defining markuplanguages that was derived from and is asubset of SGML. XML omits the morecomplex and less-used parts of SGML andmakes it much easier to write applicationsto handle document types, author andmanage structured in<strong>for</strong>mation, andtransmit and share structured in<strong>for</strong>mationacross diverse computing systems. Theuse of XML does not require the robustapplications and processing that is||||||||necessary <strong>for</strong> SGML. XML is developedunder the auspices of the World WideWeb Consortium (W3C).XML dataData that is organized into a hierarchicalstructure with XML elements. The datadefinitions are defined in XML elementtype declarations.XML declarationXML text that specifies characteristics ofthe XML document such as the version ofXML being used and the encoding of thedocument.XML documentA data object that is well <strong>for</strong>med asdefined by the W3C XML specification.XML namespaceA mechanism, defined by the W3C XMLNamespace specifications, that limits thescope of a collection of element namesand attribute names. A uniquely chosenXML namespace ensures the uniqueidentity of an element name or attributename across multiple XML documents ormultiple contexts within an XMLdocument.XML schemaA mechanism, defined by the W3C, <strong>for</strong>describing and constraining the structureand content of XML documents. An XMLschema, which is itself expressed in XML,effectively defines a class of XMLdocuments of a given type, <strong>for</strong> example,purchase orders.Yyear field expansionExplicit expansion of date fields thatcontain two-digit years to containfour-digit years in files and databases,and then use of these fields in expanded<strong>for</strong>m in programs. This is the onlymethod <strong>for</strong> assuring reliable dateprocessing <strong>for</strong> applications that have usedtwo-digit years.Zzoned decimal data itemAn external decimal data item that isdescribed implicitly or explicitly as USAGEDISPLAY and that contains a validcombination of PICTURE symbols 9, S, P,Glossary 871


and V. The content of a zoned decimaldata item is represented in characters 0through 9, optionally with a sign. If thePICTURE string specifies a sign and theSIGN IS SEPARATE clause is specified, thesign is represented as characters + or -. IfSIGN IS SEPARATE is not specified, thesign is one hexadecimal digit thatoverlays the first 4 bits of the signposition (leading or trailing).872 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


List of resources<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong>Compiler and Runtime Migration <strong>Guide</strong>, GC23-8527Customization <strong>Guide</strong>, SC23-8526Language Reference, SC23-8528Licensed Program Specifications, GI11-7871<strong>Programming</strong> <strong>Guide</strong>, SC23-8529Softcopy publicationsThe following collection kits contain <strong>Enterprise</strong><strong>COBOL</strong> and other product publications:z/<strong>OS</strong> Software Products Collection, SK3T-4270z/<strong>OS</strong> and Software Products DVD Collection,SK3T-4271SupportPer<strong>for</strong>mance Tuning, www.ibm.com/support/docview.wss?uid=swg27001475If you have a problem using <strong>Enterprise</strong> <strong>COBOL</strong><strong>for</strong> z/<strong>OS</strong>, see the following site, which providesup-to-date support in<strong>for</strong>mation:www.ibm.com/software/awdtools/cobol/zos/support/.Related publicationsCICS Transaction Server <strong>for</strong> z/<strong>OS</strong>Application <strong>Programming</strong> <strong>Guide</strong>, SC34-7022Application <strong>Programming</strong> Reference, SC34-7023Customization <strong>Guide</strong>, SC34-7001External Interfaces <strong>Guide</strong>, SC34-7019z/<strong>OS</strong> XL C/C++<strong>Programming</strong> <strong>Guide</strong>, SC09-4765Run-Time Library Reference, SA22-7821DB2 <strong>for</strong> z/<strong>OS</strong>Application <strong>Programming</strong> and SQL <strong>Guide</strong>, SC18-9841Command Reference, SC18-9844SQL Reference, SC18-9854Debug ToolReference and Messages, GC23-9535User’s <strong>Guide</strong>, SC23-9536z/<strong>OS</strong> DFSMSAccess Method Services <strong>for</strong> Catalogs, SC26-7394Checkpoint/Restart, SC26-7401Macro Instructions <strong>for</strong> Data Sets, SC26-7408Using Data Sets, SC26-7410Utilities, SC26-7414DFSORTApplication <strong>Programming</strong> <strong>Guide</strong>, SC26-7523Installation and Customization, SC26-7524IMSApplication <strong>Programming</strong> API Reference, SC18-9699Application <strong>Programming</strong> <strong>Guide</strong>, SC18-9698z/<strong>OS</strong> ISPFDialog Developer’s <strong>Guide</strong> and Reference, SC34-4821User’s <strong>Guide</strong> Vol. 1, SC34-4822User’s <strong>Guide</strong> Vol. 2, SC34-4823z/<strong>OS</strong> Language EnvironmentConcepts <strong>Guide</strong>, SA22-7567Customization, SA22-7564© Copyright IBM Corp. 1991, 2009 873


Debugging <strong>Guide</strong>, GA22-7560<strong>Programming</strong> <strong>Guide</strong>, SA22-7561<strong>Programming</strong> Reference, SA22-7562Run-Time Messages, SA22-7566Run-Time Application Migration <strong>Guide</strong>, GA22-7565Writing Interlanguage Communication Applications,SA22-7563z/<strong>OS</strong> MVSJCL Reference, SA22-7597JCL User’s <strong>Guide</strong>, SA22-7598Program Management: User’s <strong>Guide</strong> and Reference,SA22-7643System Commands, SA22-7627z/<strong>OS</strong> TSO/ECommand Reference, SA22-7782Primer, SA22-7787User’s <strong>Guide</strong>, SA22-7794z/<strong>OS</strong> UNIX System ServicesCommand Reference, SA22-7802<strong>Programming</strong>: Assembler Callable Services Reference,SA22-7803User’s <strong>Guide</strong>, SA22-7801z/ArchitecturePrinciples of Operation, SA22-7832Softcopy publications <strong>for</strong> z/<strong>OS</strong>The following collection kit contains z/<strong>OS</strong> andrelated product publications:z/<strong>OS</strong> CD Collection Kit, SK3T-4269JavaIBM SDK <strong>for</strong> Java - Tools Documentation,publib.boulder.ibm.com/infocenter/javasdk/tools/index.jspThe Java 2 <strong>Enterprise</strong> Edition Developer’s <strong>Guide</strong>,java.sun.com/j2ee/sdk_1.2.1/techdocs/guides/ejb/html/Dev<strong>Guide</strong>TOC.htmlJava 2 SDK, Standard Edition Documentation,java.sun.com/j2se/1.4.2/docs/Java 2 on z/<strong>OS</strong>, www.ibm.com/servers/eserver/zseries/software/java/The Java EE 5 Tutorial, java.sun.com/javaee/5/docs/tutorial/doc/The Java Language Specification, Third Edition, byGosling et al., java.sun.com/docs/books/jls/The Java Native Interface, java.sun.com/j2se/1.4.2/docs/guide/jni/Unicode and character representationUnicode, www.unicode.org/Character Data Representation Architecture: Referenceand Registry, SC09-2190z/<strong>OS</strong> Support <strong>for</strong> Unicode: Using Unicode Services,SA22-7649WebSphere Application Server <strong>for</strong> z/<strong>OS</strong>Applications, SA22-7959XMLExtensible Markup Language (XML),www.w3.org/XML/Namespaces in XML 1.0, www.w3.org/TR/xmlnames/Namespaces in XML 1.1, www.w3.org/TR/xmlnames11/XML specification, www.w3.org/TR/xml/z/<strong>OS</strong> XML System Services User’s <strong>Guide</strong> andReference, SA23-1350874 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


IndexSpecial characters_BPX_SHAREAS environmentvariable 441_CEE_ENVFILE environment variabledescription 439indicating Java settings 297_CEE_RUNOPTS environment variabledescription 439setting XPLINK 299specifying runtime options 437_IGZ_SYSOUT environment variablesetting 439writing to stdout or stderr 39-# cob2 option <strong>for</strong> displaying compile andlink steps 288-b cob2 option<strong>for</strong> creating DLLs 286<strong>for</strong> passing in<strong>for</strong>mation to thelinker 287-c cob2 option <strong>for</strong> compiling but notlinking 287-comprc_ok cob2 option <strong>for</strong> controllingcompiler based on return code 287-e cob2 option <strong>for</strong> specifying entrypoint 288-g cob2 option equivalent to specifyingTEST 288-I cob2 option <strong>for</strong> searchingcopybooks 288-l cob2 option <strong>for</strong> specifying archivelibrary name 288-L cob2 option <strong>for</strong> specifying archivelibrary path 288-o cob2 option <strong>for</strong> specifying outputfile 288-q cob2 option <strong>for</strong> specifying compileroptions 288-v cob2 option <strong>for</strong> displaying andexecuting compile and link steps 288! character, hexadecimal values 524.a suffix with cob2 289.adt file 305.adt suffix with cob2 289.cbl suffix with cob2 289.dbg suffix with cob2 289.dek suffix with cob2 289.lst suffix with cob2 289.o suffix with cob2 289.x suffix with cob2 289*CBL statement 363*CONTROL statement 363[ character, hexadecimal values 524] character, hexadecimal values 524| character, hexadecimal values 524# character, hexadecimal values 524Numerics16-MB lineCICS programs 40816-MB line (continued)IMS programs 408per<strong>for</strong>mance options 67224-bit addressing mode 4231-bit addressing mode 42dynamic call 45364-bit addressingno support 42Aa suffix with cob2 289a.out file from cob2 289abends, compile-time 319ACCEPT statementassigning input 37reading from stdin 37under CICS 409access method servicesbuild alternate indexes inadvance 203defining VSAM data sets, z/<strong>OS</strong> 197loading a VSAM data set 191accessibilityof <strong>Enterprise</strong> <strong>COBOL</strong> xxiof this in<strong>for</strong>mation xxiiusing z/<strong>OS</strong> xxiADATA compiler option 305adding recordsto line-sequential files 211to QSAM files 163to VSAM files 193ADDRESS OF special registeruse in CALL statement 466addressesincrementing 471NULL value 471passing between programs 471passing entry-point addresses 462addressing mode, definition 42ADEXIT suboption of EXIT optionprocessing of 727syntax 720ADMODE attributewith multithreading 499adt suffix with cob2 289ADV compiler option 305AIXBLD runtime optioneffect on per<strong>for</strong>mance 676ALL subscriptexamples 87processing table elementsiteratively 86table elements as functionarguments 60ALL31 runtime optionmultioption interaction 42OFF <strong>for</strong> AMODE switching 453ALLOCATE command (TSO)compiler data sets 261with HFS files 261allocation of filesdata sets under TSO 261description 149line-sequential 209QSAM 166VSAM 200ALPHABET clause, establishing collatingsequence with 9alphabetic datacomparing to national 140MOVE statement with 34alphanumeric comparison 94alphanumeric datacomparingeffect of ZWB 360to national 140convertingto DBCS with IGZCA2D 703to national with MOVE 134to national withNATIONAL-OF 135MOVE statement with 34with double-byte characters 703alphanumeric date fields,contracting 658alphanumeric group itema group without GROUP-USAGENATIONAL 27definition 26alphanumeric literalsconversion of mixedDBCS/EBCDIC 703description 27with DBCS content 142with double-byte characters 703alphanumeric-edited datainitializingexample 31using INITIALIZE 76MOVE statement with 34alternate collating sequencechoosing 223example 9alternate entry point, calling 463alternate indexcreating 198example of 199password <strong>for</strong> 196path 198, 199per<strong>for</strong>mance considerations 203using 183ALTERNATE RECORD KEY clauseidentify alternate indexes 199identifying alternate keys in KSDSfiles 183alternate reserved-word tableCICS 415specifying 356AMODEand DLLs 487description 42© Copyright IBM Corp. 1991, 2009 875


AMODE (continued)of EXIT modules 721switchingALL31(OFF) 453examples 453overview 453AMP parameter 201ANNUITY intrinsic function 64ANSI85 translator option 414APIs, UNIX and P<strong>OS</strong>IXcalling 440AP<strong>OS</strong>T compiler option 340APPLY WRITE-ONLY clause 12argumentsdescribing in calling program 467passing BY VALUE 467specifying OMITTED 468testing <strong>for</strong> OMITTED arguments 469ARITH compiler optiondescription 306per<strong>for</strong>mance considerations 672arithmeticCOMPUTE statement simpler tocode 58error handling 234with intrinsic functions 59arithmetic comparisons 65arithmetic evaluationconversions and precision 54data <strong>for</strong>mat conversion 54examples 64, 66fixed-point contrasted withfloating-point 64intermediate results 687per<strong>for</strong>mance tips 664precedence 59, 689precision 687arithmetic expressionas reference modifier 110description of 58in nonarithmetic statement 695in parentheses 58with MLE 651arithmetic operationwith MLE 648, 651arrays<strong>COBOL</strong> 41Javadeclaring 613manipulating 614ASCIIalphabet, QSAM 177code pages supported in XMLdocuments 520converting to EBCDIC 115file labels 178job control language (JCL) 178record <strong>for</strong>mats, QSAM 177standard labels 178tape files, QSAM 177user labels 178ASCII filesCODE-SET clause 14OPTCD= parameter in DCB 14assemblerexpansion of PROCEDUREDIVISION 387assembler (continued)from LIST option 669programscalls from (in CICS) 409compiling from 263listing of 328, 669with multithreading 499ASSIGN clausecorresponds to ddname 10QSAM files 152assigning values 29assistive technologies xxiassociated-data file, creating 270assumed century window <strong>for</strong>nondates 646asynchronous signals withmultithreading 500AT END (end-of-file) 238ATTACH macro 263attribute methods 575automatic restart 629available filesQSAM 163VSAM 197avoiding coding errors 661AWO compiler optionAPPLY-WRITE ONLY clauseper<strong>for</strong>mance 12description 307per<strong>for</strong>mance considerations 672Bbackward branches, avoid 662Base classequating to java.lang.Object 567using <strong>for</strong> java.lang.Object 566base cluster name 199base locator 382, 383basis libraries 268BASIS statement 363batch compilationdescription 274LANGUAGE optionexample 278precedence of optionsexample 277overview 276Bibliography 873big-endian, converting tolittle-endian 126binary data itemgeneral description 50intermediate results 692synonyms 49using efficiently 50, 664binary searchdescription 85example 86binderc89 command 285options needed <strong>for</strong> DLLs 483recommended <strong>for</strong> DLLs 483binding OO applicationsexample 298using JCL or TSO/E 296BLANK WHEN ZERO clausecoded <strong>for</strong> numeric data 127example with numeric-editeddata 47BLOCK CONTAINS clauseFILE SECTION entry 14no meaning <strong>for</strong> VSAM files 186QSAM files 153, 159, 307block sizeASCII files 178compiler data sets 266QSAM files 159, 307fixed-length 153record layout 155using DCB 168variable-length 154system-determinedcompiler data sets 267QSAM files 160, 307BLOCK0 compiler optiondescription 307per<strong>for</strong>mance considerations 672blocking factor, definition 153blocking QSAM filesusing BLOCK CONTAINS clause 159using BLOCK0 307blocking records 159BPXBATCH utilitycalling z/<strong>OS</strong> UNIX programs 438running OO applications 296branch, implicit 98buffersbest use of 12obtaining <strong>for</strong> QSAM 173BUFOFF= 178BUFSIZE compiler option 309BY CONTENT 465BY REFERENCE 465BY VALUEdescription 465restrictions 467valid data types 467byte order mark not generated 548byte-stream filesprocessing with QSAM 174CC/C++ programswith <strong>COBOL</strong> DLLs 490with multithreading 499c89 command <strong>for</strong> link step 285CALL command (TSO) 261CALL identifieralways dynamic 453dynamic calls 451making from DLLs 485with NODLL 451with NODYNAM 455CALL literaldynamic calls 451static calls 450with DYNAM 451with NODLL 450, 451with NODYNAM 450, 455CALL statementAMODE processing 453876 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


CALL statement (continued)BY CONTENT 465BY REFERENCE 465BY VALUEdescription 465restrictions 467CICS restrictions 409effect of EXIT option on registers 721exception condition 244<strong>for</strong> error handling 244function-pointer 463handling of program-name in 338Language Environment callableservices 683overflow condition 244RETURNING 475to alternate entry points 463USING 467with CANCEL 452with DYNAM 320with ON EXCEPTION 244with ON OVERFLOW 22, 244calls31-bit addressing mode 453AMODE switching <strong>for</strong> 24-bitprograms 453between <strong>COBOL</strong> and non-<strong>COBOL</strong>programs 447between <strong>COBOL</strong> programs 447, 449CICS restrictions 409dynamicexample 456making 451per<strong>for</strong>mance 455restrictions 451with static calls 455exception condition 244interlanguage 447LINKAGE SECTION 469OMITTED arguments 468overflow condition 244passing arguments 467passing data 465receiving parameters 468recursive 461staticexample 456making 450per<strong>for</strong>mance 455with dynamic calls 455to and from object-orientedprograms 461to JNI services 607to Language Environment callableservices 683CANCEL statementcannot use with DLL linkage 487<strong>for</strong> subprograms 452handling of program-name in 338with dynamic CALL 452case structure, EVALUATE statement<strong>for</strong> 91cataloged procedureJCL <strong>for</strong> compiling 250to compile (IGYWC) 251to compile and link-edit(IGYWCL) 252cataloged procedure (continued)to compile, link-edit, run(IGYWCLG) 253to compile, load, run (IGYWCG) 254to compile, prelink, link-edit(IGYWCPL) 255to compile, prelink, link-edit, run(IGYWCPLG) 256to compile, prelink, load, run(IGYWCPG) 258to prelink and link-edit(IGYWPL) 258CBL statementoverview 363specifying compiler options 272cbl suffix with cob2 289CBLPSHPOP runtime option 416CBLQDA runtime option 163CCSIDconflict in XML documents 528, 529definition 125EBCDIC multibyte CCSIDs 312in PARSE statement 506of DB2 string data 425of XML documents 520of XML documents to be parsed 506specifying with CODEPAGEoption 310century windowassumed <strong>for</strong> nondates 646fixed 639sliding 639chained-list processingexample 472overview 471changingcharacters to numbers 113file-name 11title on source listing 7CHAR intrinsic function, example 116character set, definition 125CHECK runtime optionper<strong>for</strong>mance considerations 672reference modification 109checking <strong>for</strong> valid dataconditional expressions 94checkpointdesigning 626example of JCL <strong>for</strong> restart 631messages generated during 628methods 626multiple 626, 628overview 625record data set 627restart during DFSORT 231restrictions during sort 626setting 625single 626disk 628tape 628Standard <strong>COBOL</strong> 85 626testing 627Chinese GB 18030 dataprocessing 138CHKPT keyword 231CICSalternate reserved-word table 415CICS (continued)calling nested programs 410CICS HANDLE 416example 417LABEL value 416coding programs to run undercalls 409DISPLAY statement 408I/O 408overview 407restrictions 407SORT statement 416command-level interface 407commands and the PROCEDUREDIVISION 407compiling with CICS option 411developing programs <strong>for</strong> 407DFHCOMMAREA parametercalling nested programs 410calling separately compiledprograms 409DFHEIBLK parametercalling nested programs 410calling separately compiledprograms 409ECI calls and RETURN-CODE specialregister 411EXIT compiler option and 734in a multithreaded environment 499integrated translatoradvantages 413calling nested programs 410compiler options <strong>for</strong> 412overview 413interlanguage communicationunder 410macro-level interface 407NODYNAM compiler option 410per<strong>for</strong>mance considerations 417, 676restrictions16-MB line 408OO programs 561OUTDD compiler option 338parsing with validation usingFILE 516separate translator 413sorting 232separate translatorcalling nested programs 410compiler options <strong>for</strong> 414restrictions 413using 414sorting underchange reserved-word table 416overview 231restrictions 232Standard <strong>COBOL</strong> 85considerations 414system date, getting 409CICS compiler optiondescription 309enables integrated translator 413multioption interaction 304specifying suboptions 310, 413using 411CISZ (control interval size), per<strong>for</strong>manceconsiderations 203, 676Index 877


CKPT keyword 231classdefining 564definition of 561factory data 594instance data 568instantiating<strong>COBOL</strong> 588Java 587nameexternal 567, 579in a program 566object, obtaining reference withJNI 608user-defined 10class conditiontesting<strong>for</strong> DBCS 143<strong>for</strong> Kanji 143<strong>for</strong> numeric 56overview 94validating data 369CLASSPATH environment variabledescription 439example of setting 296specifying location of Javaclasses 294clientdefining 578definition of 578CL<strong>OS</strong>E statementline-sequential files 209QSAM 161VSAM 187closing filesline-sequential 211multithreading serialization 496QSAMoverview 165with multithreading 165VSAMoverview 194with multithreading 195closing files, automaticline-sequential 211QSAM 165VSAM 194cluster, VSAM 197cob2 commandcompiling withexamples 287overview 285description 287<strong>for</strong> compiling OO applications 291<strong>for</strong> creating DLLs 286<strong>for</strong> linking OO applications 292input and output 289linking withexamples 287overview 285options and syntax 287COBJVMINITOPTIONS environmentvariabledescription 439specifying JVM options 295<strong>COBOL</strong>and Javabinding 296communicating between 607compatibility 300compiling under z/<strong>OS</strong> UNIX 291compiling using JCL orTSO/E 296linking 292running 293, 297structuring applications 603under IMS 432object-orientedbinding 296compiling under z/<strong>OS</strong> UNIX 291compiling using JCL orTSO/E 296linking 292running 293under IMS 432<strong>COBOL</strong> clientexample 597example of passing objectreferences 584<strong>COBOL</strong> DLL programs, calling 488<strong>COBOL</strong> terms 25<strong>COBOL</strong>3 translator option 414COBOPT environment variable 283codecopy 679optimized 669, 670code pageconflict in XML documents 528, 529DBCS 312definition 125euro currency support 67hexadecimal values of specialcharacters 524of DB2 string data 425overriding 136specifying 310specifying <strong>for</strong> alphanumeric XMLdocument 523code point, definition 125CODE-SET clause 14coded character setdefinition 125in XML documents 520CODEPAGE compiler optionDBCS code pages 312description 310<strong>for</strong> national literals 133items that are not affected 311operations that override 311codingclass definition 564clients 578condition tests 95constructor methods 595DATA DIVISION 13decisions 89efficiently 661ENVIRONMENT DIVISION 7EVALUATE statement 91factory definition 594factory methods 595file input/output (overview) 145coding (continued)IDENTIFICATION DIVISION 5IF statement 89input/output overview 148input/output statements<strong>for</strong> line-sequential files 209<strong>for</strong> QSAM files 161<strong>for</strong> VSAM files 187instance methods 569, 592interoperable data types withJava 612loops 97OO programsmust be reentrant 464overview 561PROCEDURE DIVISION 19programs to run under CICScalls 409DISPLAY statement 408I/O 408must be reentrant 464overview 407restrictions 407SORT statement 416system date, getting 409programs to run under DB2CCSID of string data 425overview 419stored procedures must bereentrant 464programs to run under IMSmust be reentrant 464overview 431restrictions 431simplifying 679SQL statements 420subclassesexample 592overview 589tables 69techniques 13, 661test conditions 95collating sequencealternatechoosing 223example 9ASCII 9binary <strong>for</strong> national keys 222EBCDIC 9HIGH-VALUE 9ISO 7-bit code 9LOW-VALUE 9MERGE 9, 223NATIVE 9nonnumeric comparisons 9ordinal position of a character 115SEARCH ALL 9SORT 9, 223specifying 9STANDARD-1 9STANDARD-2 9symbolic characters in the 10COLLATING SEQUENCE phrasedoes not apply to national keys 222overrides PROGRAM COLLATINGSEQUENCE clause 9, 223use in SORT or MERGE 223878 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


columns in tables 69COMMON attribute 6, 458COMP (COMPUTATIONAL) 50COMP-1 (COMPUTATIONAL-1)<strong>for</strong>mat 52per<strong>for</strong>mance tips 665COMP-2 (COMPUTATIONAL-2)<strong>for</strong>mat 52per<strong>for</strong>mance tips 665COMP-3 (COMPUTATIONAL-3) 52COMP-4 (COMPUTATIONAL-4) 50COMP-5 (COMPUTATIONAL-5) 51comparing data itemsdate fields 643nationaloverview 139to alphabetic, alphanumeric, orDBCS 140to alphanumeric groups 141to numeric 140two operands 139object references 581zoned decimal and alphanumeric,effect of ZWB 360compatibilitydatesin comparisons 643in DATA DIVISION 643in PROCEDURE DIVISION 643Java and <strong>COBOL</strong> 300object-oriented syntax 300compatibility mode 45, 687compilationcon<strong>for</strong>mance to Standard <strong>COBOL</strong>85 303results 273with HFS files 252compilation statistics 381COMPILE compiler optiondescription 313use NOCOMPILE to find syntaxerrors 372compile-time considerationscompiler-directed errors 280display compile and link steps 288dump, generating a 319error messagesdetermining what severity level toproduce 322severity levels 281executing compile and link steps afterdisplay 288compilercalculation of intermediateresults 688date-related messages, analyzing 656environment variables under z/<strong>OS</strong>UNIX 283generating list of error messages 279invoking in the z/<strong>OS</strong> UNIX shellexamples 287overview 285limitsDATA DIVISION 13messageschoosing severity to beflagged 374compiler (continued)messages (continued)customizing 730determining what severity level toproduce 322embedding in source listing 374from exit modules 733sending to terminal 269severity levels 281, 731return codedepends on highest severity 281effect of messagecustomization 732overview 281compiler data setsin the HFS 250, 260input and output 265required <strong>for</strong> compilation 265SYSADATA (ADATA records) 270SYSDEBUG (debug records) 270SYSIN 267SYSJAVA 270SYSLIB (libraries) 268SYSLIN (object code) 269SYSMDECK (library processing) 271SYSOPTF 267SYSOUT (listing) 269SYSPUNCH (object code) 269SYSTERM (messages) 269with cob2 289compiler listingsgetting 377compiler optionsabbreviations 301ADATA 305ADV 305AP<strong>OS</strong>T 340ARITHdescription 306per<strong>for</strong>mance considerations 672AWOdescription 307per<strong>for</strong>mance considerations 672BLOCK0description 307per<strong>for</strong>mance considerations 672BUFSIZE 309CICS 309CODEPAGE 310COMPILE 313conflicting 304CURRENCY 313DATA 314DATEPROC 315DBCS 317DECK 317DIAGTRUNC 318DLL 318DUMP 319DYNAM 320, 672EXIT 321, 719EXPORTALL 321FASTSRT 225, 322per<strong>for</strong>mance considerations 672FLAG 322, 374FLAGSTD 323<strong>for</strong> CICS integrated translator 412compiler options (continued)<strong>for</strong> CICS separate translator 411, 414<strong>for</strong> debuggingoverview 372TEST restriction 370THREAD restriction 370IMS, recommended <strong>for</strong> 431in effect 389INTDATE 325LANGUAGEdescription 326example in batch compilation 278LIB 327LINECOUNT 327LIST 328, 377MAP 328, 376, 377MDECK 329NAME 331NOCOMPILE 372NOFASTSRT 227NSYMBOL 331NUMBER 332, 379NUMPROC 333NUMPROC(PFD)per<strong>for</strong>mance considerations 672NUMPROC(PFD|NOPFD|MIG) 55OBJECT 334OFFSET 335on compiler invocation 381OPTFILE 335OPTIMIZE 336, 669per<strong>for</strong>mance considerations 672OUTDD 337per<strong>for</strong>mance considerations 672PGMNAME 338precedence ofexample 277in batch 276in SYSOPTF data sets 268, 336under z/<strong>OS</strong> 271under z/<strong>OS</strong> UNIX 284QUOTE 340RENTdescription 341per<strong>for</strong>mance considerations 672RMODEdescription 342per<strong>for</strong>mance considerations 672SEQUENCE 343signature in<strong>for</strong>mation bytes 389SIZE 344SOURCE 344, 377SPACE 345specifying 271specifying under TSO 273specifying under z/<strong>OS</strong> 273specifying under z/<strong>OS</strong> UNIX 284specifying with PROCESS (CBL) 272specifying with SYSOPTF dataset 267SQLdescription 345using with DB2 423SQLCCSIDdescription 347effect on CCSID of stringdata 425Index 879


compiler options (continued)SQLCCSID (continued)per<strong>for</strong>mance considerations 427recommended with DB2coprocessor 426SSRANGE 347, 373per<strong>for</strong>mance considerations 672Standard <strong>COBOL</strong> 85con<strong>for</strong>mance 303status 381table of 301TERMINAL 348TESTdescription 349per<strong>for</strong>mance considerations 672use <strong>for</strong> debugging 377THREADdebugging restriction 370description 352per<strong>for</strong>mance considerations 672TRUNCdescription 353per<strong>for</strong>mance considerations 672under IMS and CICS 408VBREF 356, 377WORD 356XMLPARSE 357XREF 358, 376YEARWINDOW 360ZWB 360compiler-directing statementsdescription 363overview 22compilingbatch 274control of 271data sets <strong>for</strong> 265DLLs 286from an assembler program 263OO applicationscob2 command 291example 293, 298under z/<strong>OS</strong> UNIX 291using JCL or TSO/E 296under TSO 261under z/<strong>OS</strong> 249under z/<strong>OS</strong> UNIX 283using shell script 290using the cob2 commandexamples 287overview 285with cataloged procedures 250compile 251compile and link-edit 252compile, link-edit, run 253compile, load, run 254compile, prelink, link-edit 255compile, prelink, link-edit,run 256compile, prelink, load, run 258with JCL (job control language) 249compiling and linking in the z/<strong>OS</strong> UNIXshellDLLs 286examples 287OO applicationscob2 command 292compiling and linking in the z/<strong>OS</strong> UNIXshell (continued)OO applications (continued)example 293overview 285completion codemerge 224sort 224complex OCCURS DEPENDING ONbasic <strong>for</strong>ms of 697complex ODO item 697variably located data item 697variably located group 697computationarithmetic data items 664constant data items 663duplicate 663of indexes 74of subscripts 667COMPUTATIONAL (COMP) 50COMPUTATIONAL-1 (COMP-1)<strong>for</strong>mat 52per<strong>for</strong>mance tips 665COMPUTATIONAL-2 (COMP-2)<strong>for</strong>mat 52per<strong>for</strong>mance tips 665COMPUTATIONAL-3 (COMP-3)date fields, potential problems 657description 52COMPUTATIONAL-4 (COMP-4) 50COMPUTATIONAL-5 (COMP-5) 51COMPUTE statementassigning arithmetic results 36simpler to code 58computer, describing 7concatenating data items (STRING) 101condition handlingclosing QSAM files 165closing VSAM files 195in input or output procedures 219using Language Environment 681condition testing 95condition-name 645conditional expressionEVALUATE statement 89IF statement 89PERFORM statement 99conditional statementoverview 21with NOT phrase 21with object references 581CONFIGURATION SECTION 7conflicting compiler options 304con<strong>for</strong>mance requirementsexample of passing object referencesin INVOKE 584RETURNING phrase of INVOKE 585Standard <strong>COBOL</strong> 85 303USING phrase of INVOKE 583constantscomputations 663data items 663definition 28figurative, definition 28contained program integration 670CONTENT-CHARACTERS XML eventexample 539CONTENT-CHARACTERS XML event(continued)when parsing segments 519continuationentry 230of program 235syntax checking 313CONTINUE statement 89contracting alphanumeric dates 658controlin nested programs 458program flow 89transfer 447control interval size (CISZ), per<strong>for</strong>manceconsiderations 203, 676CONTROL statement 363converting data itemsbetween code pages 115between data <strong>for</strong>mats 54exceptions with national data 136precision 54reversing order of characters 113to alphanumericwith DISPLAY 38with DISPLAY-OF 136to Chinese GB 18030 fromnational 138to integers with INTEGER,INTEGER-PART 110to nationalfrom Chinese GB 18030 138from UTF-8 137with ACCEPT 37with MOVE 134with NATIONAL-OF 135to numbers with NUMVAL,NUMVAL-C 113to uppercase or lowercasewith INSPECT 112with intrinsic functions 113to UTF-8 from national 137with INSPECT 111with intrinsic functions 112converting files to expanded date <strong>for</strong>m,example 641CONVERTING phrase (INSPECT),example 112coprocessor, DB2CCSID determination of stringdata 425differences from the precompiler 427enable with SQL compiler option 423overview 419recommended compiler optionSQLCCSID 426required compiler options 423using SQL INCLUDE with 420copy librariesCOPY statement 363data set 265example 680search order 364specifying 268SYSLIB 268z/<strong>OS</strong> UNIX search order 283, 288COPY statementDB2 considerations 427880 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


COPY statement (continued)description 363example 680nested 679, 724UNIX considerations 364z/<strong>OS</strong> considerations 268copybookdescription 363obtaining from user-suppliedmodule 720searching <strong>for</strong> 288, 364copybook cross-reference,description 376copybookscross-reference 400using 679COUNT IN phraseUNSTRING 103XML GENERATE 548countingcharacters (INSPECT) 111generated XML characters 544creatingassociated-data file 270library-processing output file 271line-sequential files, z/<strong>OS</strong> 209object code 269objects 586QSAM files, z/<strong>OS</strong> 166, 169SYSJAVA file 270variable-length tables 81cross-referenceCOPY/BASIS 400COPY/BASIS statements 377copybooks 377data and procedure-names 376embedded 377list 358program-name 400special definition symbols 402text-names and data sets 376verb list 356verbs 377CRP (file position indicator) 189, 192CURRENCY compiler option 313currency signseuro 67hexadecimal literals 67multiple-character 67using 67CURRENT-DATE intrinsic functionexample 63under CICS 409customer support xviii, 873DD-<strong>for</strong>mat recordlayout 155requesting 154DASD (direct-access storage device) 203dataconcatenating (STRING) 101converting between alphanumeric andDBCS 703efficient execution 661<strong>for</strong>mat conversion of 54data (continued)<strong>for</strong>mat, numeric types 48grouping 470incompatible 56naming 14numeric 45passing 465record size 14splitting (UNSTRING) 103validating 56data and procedure-name cross-reference,description 376data areas, dynamic 320DATA compiler optiondescription 314influencing data location 43multioption interaction 42per<strong>for</strong>mance considerations 672when passing data 43data definition 382data description entry 13DATA DIVISIONclient 580coding 13description 13entries <strong>for</strong> line-sequential files 208entries <strong>for</strong> QSAM files 152entries <strong>for</strong> VSAM files 185factory data 594factory method 596FD entry 13FILE SECTION 13GROUP-USAGE NATIONALclause 70instance data 568, 592instance method 571items present in 391limits 13LINKAGE SECTION 13, 18listing 377LOCAL-STORAGE SECTION 13mapping of items 328, 377OCCURS clause 69OCCURS DEPENDING ON (ODO)clause 81REDEFINES clause 77restrictions 13signature in<strong>for</strong>mation bytes 391USAGE clause at the group level 27USAGE IS INDEX clause 74USAGE NATIONAL clause at thegroup level 130WORKING-STORAGE SECTION 13data itemalphanumeric with double-bytecharacters 703coding Java types 612common, in subprogram linkage 468concatenating (STRING) 101converting characters (INSPECT) 111converting characters to numbers 113converting to uppercase orlowercase 113converting with intrinsicfunctions 112counting characters (INSPECT) 111DBCS 703data item (continued)elementary, definition 26evaluating with intrinsicfunctions 115finding the smallest or largestitem 116group, definition 26index, referring to table elementswith 72initializing, examples of 30map 273numeric 45reference modification 107referring to a substring 107replacing characters (INSPECT) 111reversing characters 113splitting (UNSTRING) 103unused 336, 382variably located 697data manipulationcharacter data 101DBCS data 703DATA RECORDS clause 14data setalternate data-set names 263checkpoint record 627compiler-option 267defining with environmentvariable 149example of checkpoint/restart 631JAVAERR 297JAVAIN 297JAVAOUT 297names, alternate 263output 269source code 267SYSADATA 270SYSDEBUG 270SYSIN 267SYSJAVA 270SYSLIB 268SYSLIN 269SYSMDECK 271SYSOPTF 267SYSPRINT 269SYSPUNCH 269SYSTERM 269used interchangeably <strong>for</strong> file 8data sets used <strong>for</strong> compiling 265data-definition attribute codes 382data-namecross-reference 398cross-reference list 273in MAP listing 382OMITTED 14password <strong>for</strong> VSAM files 196date and time operationsLanguage Environment callableservices 681date arithmetic 652date comparisons 643date field expansionadvantages 638description 641date fields, potential problems with 657DATE FORMAT clausecannot use with national data 636Index 881


DATE FORMAT clause (continued)use <strong>for</strong> automatic daterecognition 635use <strong>for</strong> sorting on windowed datefields 224date operationsfinding date of compilation 119intrinsic functions <strong>for</strong> 41date processing with internal bridges,advantages 638date windowingadvantages 638example 639, 645how to control 653MLE approach 638when not supported 644DATE-COMPILED paragraph 5DATE-OF-INTEGER intrinsicfunction 63DATEPROC compiler optionanalyzing warning-levelmessages 656description 315per<strong>for</strong>mance 649DATEVAL intrinsic functionexample 655using 654DB2coding considerations 419coprocessorCCSID determination of stringdata 425database request module(DBRM) 420, 424differences from theprecompiler 427enable with SQL compileroption 423overview 419recommended compiler optionSQLCCSID 426required compiler options 423using SQL INCLUDE with 420DYNAM compiler option with TSO orIMS 429NODYNAM compiler option withCICS or CAF 429precompilerdifferences from thecoprocessor 427recommended compiler optionN<strong>OS</strong>QLCCSID 426specifying code page <strong>for</strong> hostvariables 421SQL compiler option 423SQL statementsCCSID determination 425coding 420overview 419return codes 423SQL DECLARE 421SQL INCLUDE 420using binary data in 423using character data in 421using national decimal data 422SQLCCSID compiler option 425DBCS comparison 94DBCS compiler optiondescription 317<strong>for</strong> Java interoperability 291, 296<strong>for</strong> OO <strong>COBOL</strong> 291, 296multioption interaction 304DBCS datacomparingto national 140convertingto alphanumeric withIGZCD2A 706to and from alphanumeric 703to national, overview 143declaring 142encoding and storage 133literalsdescription 28maximum length 142using 142MOVE statement with 34notation <strong>for</strong> 703testing <strong>for</strong> 143dbg suffix with cob2 289DBRM data setdefining 424description 420DCB 161DD control statementAMP parameter 201ASCII tape files 178creating line-sequential files 209creating QSAM files 166, 169DBRMLIB 424DCB overrides data-set label 168define file 10defining merge data sets 219defining sort data sets 219JAVAERR 297JAVAIN 297JAVAOUT 297RLS parameter 202SYSADATA 270SYSDEBUG 270SYSIN 267SYSJAVA 270SYSLIB 268SYSLIN 269SYSMDECK 271SYSOPTF 267SYSPRINT 269SYSPUNCH 269ddname definition 10deadlock in I/O error declarative 238Debug Toolcompiler options <strong>for</strong> 377description 367debuggingand per<strong>for</strong>mance 350compiler options <strong>for</strong>overview 372TEST restriction 370THREAD restriction 370defining data set 270dynamic 351overview 367runtime options <strong>for</strong> 370using <strong>COBOL</strong> language features 367debugging (continued)using the debugger 377debugging, language featuresclass test 369debugging lines 370debugging statements 370declaratives 370DISPLAY statements 368file status keys 369INITIALIZE statements 370scope terminators 368SET statements 370WITH DEBUGGING MODEclause 370DECK compiler option 317declarative proceduresEXCEPTION/ERROR 238with multithreading 238LABEL 176USE FOR DEBUGGING 370deferred restart 629definingdebug data set 270files, overview 10, 145libraries 268line-sequential files to z/<strong>OS</strong> 209QSAM filesto z/<strong>OS</strong> 166, 169sort or merge files under z/<strong>OS</strong> 219VSAM files 197to z/<strong>OS</strong> 197dek suffix with cob2 289DELETE statementcompiler-directing 365multithreading serialization 496VSAM, coding 187deleting records from VSAM file 194delimited scope statementdescription of 21nested 23DEPENDING ON clause 154, 186depth in tables 71deviceclasses 265requirements 265DFHCOMMAREA parametercalling nested CICS programs 410calling separately compiled CICSprograms 409DFHEIBLK parametercalling nested CICS programs 410calling separately compiled CICSprograms 409DFSORTdefining data sets <strong>for</strong> 219error message <strong>for</strong> RETURNstatement 218diagnostics, program 381DIAGTRUNC compiler option 318direct-accessdirect indexing 74file organization 146storage device (DASD) 203directoriesadding a path to 288disability xxi882 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


DISPLAY (USAGE IS)encoding and storage 133external decimal 49floating point 50display floating-point data (USAGEDISPLAY) 50DISPLAY statementdirecting output 337displaying data values 38displaying on the system logicaloutput device 39interaction with OUTDD 39suppressing line spacing 39under CICS 408using in debugging 368writing to stdout or stderr 39DISPLAY-1 (USAGE IS)encoding and storage 133DISPLAY-OF intrinsic functionexample with Chinese data 138example with Greek data 137example with UTF-8 data 137using 136with XML documents 522DLL compiler optiondescription 318<strong>for</strong> Java interoperability 291, 296<strong>for</strong> OO <strong>COBOL</strong> 291, 296multioption interaction 304DLL igzcjava.xbinding withexample 298preparing OO applications 296linking withexample 293preparing OO applications 292DLL libjvm.xbinding withexample 298preparing OO applications 296linking withexample 293preparing OO applications 292with EBCDIC services 618DLLs (see dynamic link libraries) 481do loop 99do-until 99do-while 99documentation of program 7DSA memory map 387dumprequesting 233with DUMP compiler option 273DUMP compiler optiondescription 319multioption interaction 304output 273duplicate computations, grouping 663DYNAM compiler optiondescription 320multioption interaction 304per<strong>for</strong>mance considerations 672under DB2 with TSO or IMS 429with dynamic calls 451dynamic callsexample 456making 451dynamic calls (continued)per<strong>for</strong>mance 455restrictions 451using with DLL linkage 486when to use 452with static calls 455dynamic data areas, allocatingstorage 43dynamic debugging 351dynamic file allocationorder of allocation 149using CBLQDA 163using environment variablesline-sequential files 209QSAM files 166VSAM files 200dynamic link librariesabout 481binder options <strong>for</strong> DLLs 483compiler options required 286compiling 482creatingfrom the z/<strong>OS</strong> UNIX shell 286overview 481creating <strong>for</strong> OO 292<strong>for</strong> Java interoperability 292in OO <strong>COBOL</strong> applications 491linking 483prelinker needed if DLL to be inPDS 485prelinker needed if DLL to reside inPDS 483prelinking 485programs with DLL support must bereentrant 464search order <strong>for</strong> in HFS 486using CALL identifier with 485using with C/C++ programs 490using with dynamic calls 486using with Java interoperability 293using with OO 293EE-level error message 281, 374EBCDICcode pages supported in XMLdocuments 520converting to ASCII 115JNI services 617multibyte CCSIDs supported <strong>for</strong>DBCS 312ECI calls and RETURN-CODE specialregister 411efficiency of coding 661EJECT statement 365embedded cross-referencedescription 377example 401embedded error messages 374embedded MAP summary 376, 383enclave 447encodingconflicts in XML documents 528, 529controlling in generated XMLoutput 547description 133encoding (continued)language characters 125of XML documents 520, 521of XML documents to be parsed 506specifying <strong>for</strong> alphanumeric XMLdocument 523specifying with CODEPAGEoption 310encoding declarationpreferable to omit 523specifying 523end-of-file phrase (AT END) 238END-OF-INPUT XML eventexample 539when parsing segments 519enhancing XML outputexample of converting hyphens tounderscores 557example of modifying datadefinitions 554rationale and techniques 553ENTER statement 365entry pointalternate 463alternate in ENTRY statement 462ENTRY label 463passing entry addresses of 462procedure-pointer data item 462ENTRY statement<strong>for</strong> alternate entry points 462handling of program-name in 338ENVAR runtime option 297ENVIRONMENT DIVISIONclass 566client 579collating sequence coding 9CONFIGURATION SECTION 7description 7entries <strong>for</strong> line-sequential files 207entries <strong>for</strong> QSAM files 151entries <strong>for</strong> VSAM files 181INPUT-OUTPUT SECTION 7instance method 571items present in, programinitialization code 392signature in<strong>for</strong>mation bytes 392subclass 591environment variables_BPX_SHAREAS 441_CEE_ENVFILEdescription 439indicating Java settings 297_CEE_RUNOPTSdescription 439setting XPLINK 299specifying runtime options 437_IGZ_SYSOUT 439and copybooks 363CLASSPATHdescription 439example of setting 296specifying location of Javaclasses 294COBJVMINITOPTIONSdescription 439specifying JVM options 295COBOPT 283Index 883


environment variables (continued)compiler 283defining files, example 10defining line-sequential files 209defining QSAM files 166example of setting and accessing 440LIBPATHdescription 439example of setting 296specifying location <strong>for</strong> <strong>COBOL</strong>classes 294library-name 283, 363PATHdescription 439example of setting 296runtime 439setting and accessing 438STEPLIBdescription 439example 285SYSLIBdescription 283specifying location of JNI.cpy 291text-name 283, 363using to allocate files 149environment-name 7ERRMSG, <strong>for</strong> generating list of errormessages 279errorarithmetic 234compiler options, conflicting 304handling 233handling <strong>for</strong> input-output 150listing 273message tableexample using indexing 80example using subscripting 79processingline-sequential files 212QSAM files 165VSAM files 195XML GENERATE 548XML PARSE 528routines <strong>for</strong> handling 244error messagescompilerchoosing severity to beflagged 374correcting source 279customizing 730determining what severity level toproduce 322embedding in source listing 374<strong>for</strong>mat 280from exit modules 733generating a list of 279location in listing 280sending to terminal 269severity levels 281, 731compiler-directed 280ESDS (entry-sequenced data sets)file access mode 185organization 182euro currency sign 67EVALUATE statementcase structure 91coding 91EVALUATE statement (continued)contrasted with nested IFs 92, 93example that tests severalconditions 93example with multiple WHENphrases 93example with THRU phrase 92per<strong>for</strong>mance 92structured programming 662testing multiple values, example 96,97use to test multiple conditions 89evaluating data item contentsclass test<strong>for</strong> numeric 56overview 94INSPECT statement 111intrinsic functions 115exception conditionCALL 244XML GENERATE 548XML PARSE 528exception handlingwith Java 608with XML GENERATE 548with XML PARSE 526EXCEPTION XML event 528EXCEPTION/ERROR declarativedescription 238file status key 240line-sequential error processing 212QSAM error processing 165VSAM error processing 195EXEC control statement, RD parameterof 628EXIT compiler optionconsiderations <strong>for</strong> SQL and CICSstatements 734description 321register usage 721user-exit work area 721using 719with the DUMP compiler option 304exit modulescalled <strong>for</strong> SYSADATA data set 727calling <strong>COBOL</strong> programs 721error messages generated 733used <strong>for</strong> message severitycustomization 729used in place of library-name 723used in place of SYSLIB 723used in place of SYSPRINT 726EXIT PROGRAM statementin subprogram 448with multithreading 448explicit scope terminator 22exponentiationevaluated in fixed-pointarithmetic 690evaluated in floating-pointarithmetic 695per<strong>for</strong>mance tips 665EXPORTALL compiler optiondescription 321DLL considerations 482multioption interaction 304extended mode 45, 687external class-name 567, 579EXTERNAL clauseexample <strong>for</strong> files 476<strong>for</strong> data items 475<strong>for</strong> sharing files 14, 475external dataobtaining storage <strong>for</strong> 44sharing 475storage location of 44external decimal datanational 49zoned 49external file 475external floating-point datadisplay 50national 50FF-<strong>for</strong>mat recordlayout 153requesting 153factoring expressions 662factory datadefining 594definition of 561making it accessible 595private 595factory definition, coding 594factory methodsdefining 595definition of 561hiding 596invoking 597using to wrap proceduralprograms 603FACTORY paragraphfactory data 594factory methods 595factory section, defining 594FASTSRT compiler optiondescription 322improving sort per<strong>for</strong>mance 225, 672in<strong>for</strong>mation message 225requirementsJCL 226QSAM 226sort input and output files 226VSAM 227FD (file description) entry 14figurative constantsdefinition 28HIGH-VALUE restriction 128national-character 128file access modechoosing 147dynamic 185example 185<strong>for</strong> indexed files (KSDS) 185<strong>for</strong> relative files (RRDS) 185<strong>for</strong> sequential files (ESDS) 185per<strong>for</strong>mance considerations 203random 185sequential 185summary table of 181file allocation 149884 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


file availabilityQSAM files under z/<strong>OS</strong> 163VSAM files under z/<strong>OS</strong> 197file conversionwith millennium languageextensions 641file description (FD) entry 14file organizationchoosing 147comparison of ESDS, KSDS,RRDS 181indexed 145, 182line-sequential 207overview 145QSAM 151relative 145relative-record 184sequential 145, 182VSAM 180file position indicator (CRP) 189, 192FILE SECTIONBLOCK CONTAINS clause 14CODE-SET clause 14DATA RECORDS clause 14description 13EXTERNAL clause 14FD entry 14GLOBAL clause 14LABEL RECORDS clause 14LINAGE clause 14OMITTED 14RECORD CONTAINS clause 14record description 13RECORD IS VARYING 14RECORDING MODE clause 14VALUE OF 14FILE STATUS clausedescription 150example 243line-sequential error processing 212NOFASTSRT error processing 227QSAM error processing 165using 239VSAM error processing 195with VSAM status code 241file status code02 19205 18930 19135 18937 16239 162, 170, 174, 18949 19490 160, 165, 19592 194, 441using 235file status keychecking <strong>for</strong> I/O errors 239checking <strong>for</strong> successful OPEN 239,240error handling 369set <strong>for</strong> error handling 150used with VSAM status code 241VSAM, importance of in 195FILE-CONTROL paragraphexample of entries 8relation to FD entries 11filesassociating program files to externalfiles 7attributes 170availableQSAM 163VSAM 197changing name 11<strong>COBOL</strong> codingDATA DIVISION entries 152, 185,208ENVIRONMENT DIVISIONentries 151, 181, 207input/output statements 161, 187,209overview 148defining to operating system 10describing 13external 475identifying to z/<strong>OS</strong> 166, 169, 197,209labels 178multithreaded processingexample 498recommended organization 497recommended usage patterns 497serialization 496optionalQSAM 163VSAM 190overview 146processingline-sequential 207QSAM 151VSAM 179with multithreading 496sort per<strong>for</strong>manceFASTSRT 225variable-length files 220storage of file-definition records 497unavailableQSAM 163VSAM 197usage explanation 11used interchangeably <strong>for</strong> data set 8FIPS messagescategories 731FLAGSTD compiler option 323fixed century window 639fixed-length recordsQSAMlayout 153requesting 153VSAMdefining 186RRDS 180fixed-point arithmeticcomparisons 65evaluation 64example evaluations 66exponentiation 690fixed-point databinary 50conversions and precision 54conversions between fixed- andfloating-point 54external decimal 49fixed-point data (continued)intermediate results 689packed-decimal 52planning use of 664FLAG compiler optioncompiler output 375description 322using 374flags and switches 95FLAGSTD compiler option 323multioption interaction 304floating-point arithmeticcomparisons 65evaluation 64example evaluations 66exponentiation 695floating-point dataconversions and precision 54conversions between fixed- andfloating-point 54external 50intermediate results 694internal<strong>for</strong>mat 52per<strong>for</strong>mance tips 665planning use of 664<strong>for</strong>mat of recordfixed-lengthdefining <strong>for</strong> VSAM 186layout of QSAM 153requesting <strong>for</strong> QSAM 153<strong>for</strong> QSAM ASCII tape 177<strong>for</strong>mat D 177layout 155requesting 154<strong>for</strong>mat F 177layout 153requesting 153<strong>for</strong>mat Slayout 157overview 157requesting 156<strong>for</strong>mat U 177layout 159requesting 158<strong>for</strong>mat V 177layout 155requesting 154spannedlayout 157overview 157requesting 156undefinedlayout 159requesting 158variable-lengthdefining <strong>for</strong> VSAM 186layout of QSAM 155requesting <strong>for</strong> QSAM 154<strong>for</strong>matted dump 233freeing object instances 588full date field expansion,advantages 638function-pointer data itemaddressing JNI services 741CALL statement 463calling <strong>COBOL</strong> 463Index 885


function-pointer data item (continued)calling DLL programexample 489calling Language Environmentservices 463definition 462SET function-pointer 462with DLLs 488Ggarbage collection 588GB 18030 dataconverting to or from national 138processing 138generating XML outputexample 549overview 543get and set methods 575GETMAIN, saving address of 721GLOBAL clause <strong>for</strong> files 14, 18global names 460Glossary 839GO TO MORE-LABELS 176GOBACK statementin main program 448in subprogram 448with multithreading 448group itemcannot subordinate alphanumericgroup within national group 131comparing to national data 141definition 26<strong>for</strong> defining tables 69group move contrasted withelementary move 35, 131initializingusing a VALUE clause 78using INITIALIZE 32, 76MOVE statement with 35passing as an argument 470treated as a group itemexample with INITIALIZE 76in INITIALIZE 33variably located 697group move contrasted with elementarymove 35, 131GROUP-USAGE NATIONAL clausecommunicating with Java 612defining a national group 130defining tables 70example of declaring a nationalgroup 26initializing a national group 33grouping data to pass as anargument 470Hheader labeldefinition 175using 175header on listing 7HEAP runtime optioninfluencing data location 43multioption interaction 42hexadecimal literalsas currency sign 67nationaldescription 28using 127hiding factory methods 596hierarchical file system (HFS)compiler data sets 252defining file with environmentvariable 149processing files with QSAM 174reading file with ACCEPT 37search order <strong>for</strong> DLLs in 486writing files with DISPLAY 39hierarchy of compiler optionsin batch 276in SYSOPTF data sets 336under z/<strong>OS</strong> 271under z/<strong>OS</strong> UNIX 284II-level message 281, 374IDENTIFICATION DIVISIONclass 566CLASS-ID paragraph 566, 590client 578coding 5DATE-COMPILED paragraph 5errors 5listing header example 7method 570PROGRAM-ID paragraph 5required paragraphs 5subclass 590TITLE statement 7IF statementcoding 89nested 90use EVALUATE instead <strong>for</strong> multipleconditions 90with null branch 89IGZBRDGE macrowith multithreading 500IGZCA2D service routine 703IGZCD2A service routine 706igzcjava.xbinding withexample 298preparing OO applications 296linking withexample 293preparing OO applications 292IGZEOPT modulewith multithreading 500IGZETUN modulewith multithreading 500IGZSRTCD data set 229imperative statement, list 21implicit scope terminator 22IMS<strong>COBOL</strong>-Java interoperabilityaccessing databases 434calling <strong>COBOL</strong> method fromJava 432calling Java method from<strong>COBOL</strong> 433IMS (continued)<strong>COBOL</strong>-Java interoperability(continued)messages 434restriction on EXEC SQL 434STOP RUN 434synchronizing transactions 434using the AIB 435coding programs underoverview 431restrictions 8, 431compiling and linking <strong>for</strong> 431per<strong>for</strong>mance considerations 676using EXEC SQL under IMS 434incrementing addresses 471indexassigning a value to 74computation of element displacement,example 72creating with OCCURS INDEXED BYclause 74definition 72incrementing or decrementing 74initializing 75key, detecting faulty 243range checking 373referencing other tables with 74index data itemcannot use as subscript or index 75creating with USAGE IS INDEXclause 74indexed file organizationdescription 145specifying 182indexingcomputation of element displacement,example 72definition 72example 80preferred to subscripting 665tables 74INEXIT suboption of EXIT optionprocessing of 722syntax 720inheritance hierarchy, definition of 563INITIAL attribute 449effect on nested programs 7effect on subprograms 450, 451setting programs to initial state 7use of dynamic call and CANCELinstead 452INITIALIZE statementexamples 30loading group values 32loading national group values 33loading table values 76REPLACING phrase 76using <strong>for</strong> debugging 370initializinga group itemusing a VALUE clause 78using INITIALIZE 32, 76a national group itemusing a VALUE clause 78using INITIALIZE 33, 76a structure using INITIALIZE 32886 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


initializing (continued)a tableall occurrences of an element 78at the group level 78each item individually 77using INITIALIZE 76using PERFORM VARYING 100examples 30instance data 586variable-length group 83inline PERFORMexample 98overview 98inputcoding <strong>for</strong> CICS 408coding <strong>for</strong> line-sequential files 209coding <strong>for</strong> QSAM files 161coding <strong>for</strong> VSAM files 187from files 145to compiler, under z/<strong>OS</strong> 265input procedurecoding 216example 222FASTSRT option not effective 226requires RELEASE or RELEASEFROM 217restrictions 219INPUT-OUTPUT SECTION 7input/outputchecking <strong>for</strong> errors 239coding overview 148controlling with FASTSRT option 322logic flow after error 235overview 145processing errorsline-sequential files 212QSAM files 165, 235VSAM files 195, 235input/output codingAT END (end-of-file) phrase 238checking <strong>for</strong> successful operation 239checking VSAM status codes 241detecting faulty index key 243error handling techniques 235EXCEPTION/ERRORdeclaratives 238INSERT statement 365INSPECT statementavoid with UTF-8 data 525examples 111using 111inspecting data (INSPECT) 111instancecreating 586definition of 561deleting 588instance datadefining 568, 592definition of 561initializing 586making it accessible 575private 568instance methodsdefining 569, 592definition of 561invoking overridden 586overloading 574instance methods (continued)overriding 573INTDATE compiler optiondescription 325effect on calendar starting date 62INTEGER intrinsic function,example 110INTEGER-OF-DATE intrinsicfunction 63INTEGER-PART intrinsic function 110integrated CICS translatoradvantages 413compiler options <strong>for</strong> 412overview 413interactive program, example 819Interactive System Productivity Facility(ISPF) 819interlanguage communicationand PL/I tasking 499between <strong>COBOL</strong> and Java 607IMS applications 434subprograms 447under CICS 410with multithreading 499intermediate results 687internal bridgesadvantages 638example 640<strong>for</strong> date processing 639internal floating-point data (COMP-1,COMP-2) 52interoperable data types with Java 612interrupts 625intrinsic functionsas reference modifiers 110converting alphanumeric data itemswith 112converting national data itemswith 112DATEVALexample 655using 654evaluating data items 115example ofANNUITY 64CHAR 116CURRENT-DATE 63DISPLAY-OF 137INTEGER 110INTEGER-OF-DATE 63LENGTH 63, 117, 118LOG 64LOWER-CASE 113MAX 63, 87, 116, 117MEAN 64MEDIAN 64, 87MIN 110NATIONAL-OF 137NUMVAL 113NUMVAL-C 63, 113ORD 115ORD-MAX 87, 116PRESENT-VALUE 63RANGE 64, 87REM 64REVERSE 113SQRT 64intrinsic functions (continued)example of (continued)SUM 87UPPER-CASE 113WHEN-COMPILED 119finding date of compilation 119finding largest or smallest item 116finding length of data items 118intermediate results 692, 695introduction to 40nesting 41numeric functionsdifferences from LanguageEnvironment callableservices 61equivalent Language Environmentcallable services 60examples of 59integer, floating-point, mixed 59nested 60special registers as arguments 60table elements as arguments 60uses <strong>for</strong> 59processing table elements 86UNDATEexample 655using 654INVALID KEY phrasedescription 243example 243INVOKE statementRETURNING phrase 585USING phrase 583using to create objects 586using to invoke methods 582with ON EXCEPTION 583, 597with PROCEDURE DIVISIONRETURNING 474invoking<strong>COBOL</strong> programs under z/<strong>OS</strong> UNIXprograms 437factory or static methods 597instance methods 582Language Environment callableservices 683ISAM data set, analogous to VSAM KSDSdata set 179ISPF (Interactive System ProductivityFacility) 819JJ2EE clientexample 619running 295Javaand <strong>COBOL</strong>binding 296communicating between 607compatibility 300compiling under z/<strong>OS</strong> UNIX 291compiling using JCL orTSO/E 296linking 292running 293, 297structuring applications 603array classes 612Index 887


Java (continued)arraysdeclaring 613example 616manipulating 614boolean array 613boolean type 612byte array 613byte type 612char array 613char type 612class types 612double array 614double type 612exampleexception handling 609J2EE client 619processing an array 616exceptioncatching 609example 609handling 608throwing 608float array 614float type 612global referencesJNI services <strong>for</strong> 611managing 610object 610passing 610int array 613int type 612interoperability 607interoperable data types, coding 612jstring class 612local referencesdeleting 610freeing 611JNI services <strong>for</strong> 611managing 610object 610passing 610per multithreading 610saving 610long array 613long type 612methodsaccess control 611object array 613running with <strong>COBOL</strong>under z/<strong>OS</strong> UNIX 293using JCL or TSO/E 297XPLINK linkage 299sharing data with 612short array 613short type 612string array 613stringsdeclaring 613manipulating 616Java virtual machineexceptions 609initializing 294object references 610java.lang.Objectreferring to as Base 566javac commandcompiling Java class definitions 291recompile <strong>for</strong> Java 5 or Java 6 300JAVAERR data set 297JAVAIN data set 297JAVAOUT data set 297JCLASCII tape files 178cataloged procedures 250example of checkpoint/restart 631FASTSRT requirement 225<strong>for</strong> compiling 249<strong>for</strong> compiling with HFS 252<strong>for</strong> line-sequential files 209<strong>for</strong> merge 219<strong>for</strong> OO applications 296example 298<strong>for</strong> QSAM files 168<strong>for</strong> sort 219<strong>for</strong> VSAM data sets 200JNIaccessing services 607comparing object references 581converting local references toglobal 587EBCDIC services 617environment structure 607addressability <strong>for</strong> 607exception handling services 608Java array services 614Java string services 616obtaining class object reference 608restrictions when using 608Unicode services 616UTF-8 services 619JNI.cpy<strong>for</strong> compiling 291<strong>for</strong> JNINativeInterface 607listing 741JNIEnvPtr special registeruse <strong>for</strong> JNI callable services 607JNINativeInterfaceenvironment structure 607JNI.cpy 607JOB control statement, RD parameterof 628job resubmission 631job stream 447jstring Java class 612KKanji comparison 94Kanji data, testing <strong>for</strong> 143keyboard navigation xxikeysalternate in KSDS file 183<strong>for</strong> binary search 85<strong>for</strong> mergingdefining 221overview 214<strong>for</strong> sortingdefining 221overview 214permissible data typesin MERGE statement 222in OCCURS clause 70keys (continued)permissible data types (continued)in SORT statement 222prime in KSDS file 182relative-record 184to specify order of table elements 70KSDS (key-sequenced data sets)file access mode 185organization 182LLABEL declarativedescription 365GO TO MORE-LABELS 176handling user labels 176LABEL RECORDS clauseFILE SECTION entry 14LABEL= 178labelsASCII file 178<strong>for</strong>mat, standard 176processing, QSAM files 174standard user 177LANGUAGE compiler optiondescription 326Language Environment callable servicescondition handling 681corresponding math intrinsicfunctions 60date and time computations 681differences from intrinsicfunctions 61dynamic storage services 681example of using 684feedback code 683<strong>for</strong> date and time 62<strong>for</strong> mathematics 60invoking with CALL 683mathematics 681message handling 681national language support 681omitted feedback code 683overview 681return code 683RETURN-CODE special register 683sample list of 682types of 681large block interface (LBI) 160largest or smallest item, finding 116last-used statesubprograms with EXIT PROGRAMor GOBACK 449subprograms without INITIALattribute 450, 451LBI (large block interface) 160LENGTH intrinsic functioncompared with LENGTH OF specialregister 118example 63, 118using 115variable-length results 117with national data 118length of data items, finding 118LENGTH OF special registerpassing 466using 118888 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


level-88 itemconditional expressions 94<strong>for</strong> windowed date fields 645restriction 646setting switches off, example 97setting switches on, example 96switches and flags 95testing multiple values, example 96testing single values, example 95level-number 382LIB compiler option 327multioption interaction 304LIBEXIT suboption of EXIT optionprocessing of 723syntax 720libjvm.xbinding withexample 298preparing OO applications 296linking withexample 293preparing OO applications 292with EBCDIC services 618LIBPATH environment variabledescription 439example of setting 296specifying location <strong>for</strong> <strong>COBOL</strong>classes 294libraryBASIS 268COPY 268defining 268directory entry 263specifying path <strong>for</strong> 363library-namealternative if not specified 288cross-reference to data-set names 400when not used 723library-name environment variable 283limits of the compilerDATA DIVISION 13user data 13line number 382line-sequential filesadding records to 211allowable control characters 208blocking 14closing 211closing to prevent reopening 210DATA DIVISION entries 208ENVIRONMENT DIVISIONentries 207input/output error processing 212input/output statements <strong>for</strong> 209national data not supported 211opening 210processing files 207reading from 210reading records from 210under z/<strong>OS</strong>creating files 209DD statement <strong>for</strong> 209defining 209environment variable <strong>for</strong> 209job control language (JCL) 209writing to 210LINECOUNT compiler option 327LINK macro 263LINKAGE SECTIONcoding 469<strong>for</strong> describing parameters 468with recursive calls 19with the THREAD option 19linked-list processing, example 472linking in the z/<strong>OS</strong> UNIX shellc89 command 285passing in<strong>for</strong>mation to cob2 287using the cob2 commandDLLs 286examples 287overview 285linking OO applicationscob2 command 292under z/<strong>OS</strong> UNIXexample 293overview 292using JCL or TSO/Eexample 298overview 296LIST compiler optionassembler code <strong>for</strong> sourceprogram 387compiler output 388, 389conflict with OFFSET option 377description 328DSA memory map 387, 398getting output 377location and size ofWORKING-STORAGE 398multioption interaction 304reading output 387symbols used in output 385TGT memory map 387List of resources 873listingsassembler expansion of PROCEDUREDIVISION 387data and procedure-namecross-reference 376embedded error messages 374generating a short listing 377line numbers, user-supplied 379sorted cross-reference ofprogram-names 400sorted cross-reference oftext-names 400terms used in MAP output 384text-name cross-reference 376literalsalphanumericdescription 27with DBCS content 142DBCSdescription 28maximum length 142using 142definition 27hexadecimalusing 127nationaldescription 28using 127numeric 28using 27little-endian, converting tobig-endian 126loading a table dynamically 75local names 460local references, converting to global 587LOCAL-STORAGE SECTIONclient 580, 581comparison withWORKING-STORAGEexample 17OO client 581overview 16determining location 43LOG intrinsic function 64logical recorddescription 145fixed-length <strong>for</strong>matdefining <strong>for</strong> VSAM 186requesting <strong>for</strong> QSAM 153QSAM, definition 152variable-length <strong>for</strong>matdefining <strong>for</strong> VSAM 186layout <strong>for</strong> QSAM 155requesting <strong>for</strong> QSAM 154loopscoding 97conditional 99do 99in a table 100per<strong>for</strong>med an explicit number oftimes 99LOWER-CASE intrinsic function 113lowercase, converting to 113lst suffix with cob2 289Mmain programand subprograms 447dynamic calls 451parameter list in UNIX 442main storage, allocating to buffers 309MAP compiler optiondata items and relative addresses 273description 328embedded MAP summary 377example 382, 386nested program map 377example 386symbols used in output 385terms used in output 384using 376, 377mapping of DATA DIVISION items 377mathematicsintrinsic functions 59, 64Language Environment callableservices 61, 681MAX intrinsic functionexample table calculation 87example with functions 63using 116MDECK compiler optiondescription 329multioption interaction 304MEAN intrinsic functionexample statistics calculation 64example table calculation 87Index 889


MEDIAN intrinsic functionexample statistics calculation 64example table calculation 87memory mapDSA 387TGT 387memory map, TGTexample 396mergealternate collating sequence 223completion code 224criteria 221data sets needed under z/<strong>OS</strong> 219DD statements <strong>for</strong> defining z/<strong>OS</strong> datasets 219description 213determining success 224diagnostic message 225files, describing 215keysdefining 221overview 214pass control statements to 229process 214restrictions 213storage use 230terminating 225MERGE statementASCENDING|DESCENDING KEYphrase 222COLLATING SEQUENCE phrase 9,223description 220GIVING phrase 220overview 213restrictions 213USING phrase 220message handling, LanguageEnvironment callable services 681messagescompilerchoosing severity to beflagged 374customizing 730date-related 656determining what severity level toproduce 322embedding in source listing 374generating a list of 279millennium languageextensions 656sending to terminal 269severity levels 281, 731compiler-directed 280from exit modules 733METHOD-ID paragraph 570methodsconstructor 595factory 595hiding factory 596instance 569, 592invoking 582, 597invoking superclass 586Java access control 611obtaining passed arguments 573overloading 574overriding 573, 596methods (continued)PROCEDURE DIVISIONRETURNING 474returning a value from 573signature 570millennium language extensionsassumed century window 646compatible dates 643concepts 636date windowing 635DATEPROC compiler option 315nondates 647objectives 637principles 636YEARWINDOW compiler option 360MIN intrinsic functionexample 110using 116mixed DBCS/EBCDIC literalalphanumeric to DBCSconversion 703DBCS to alphanumericconversion 706MLE 636mnemonic-nameSPECIAL-NAMES paragraph 7MOVE statementassigning arithmetic results 36converting to national data 134CORRESPONDING 35effect of ODO on lengths of sendingand receiving items 81group move contrasted withelementary move 35, 131with elementary receiving items 34with group receiving items 35with national items 34MSGEXIT suboption of exit optionexample user exit 735MSGEXIT suboption of EXIT optioneffect on compilation return code 732message severity levels 731processing of 729syntax 720MSGFILE runtime option 338MSGSEV operation code 729multiple currency signsexample 68using 67multiple inheritance, not permitted 564,590multiple thread environment, runningin 352multithreadingAMODE setting 499asynchronous signals 500choosing data section 493in an OO client 581closing QSAM files 165closing VSAM files 195<strong>COBOL</strong> programs 493coding file I/Oexample 498recommended organization 497recommended usage patterns 497serialization 496control transfer 495multithreading (continued)ending programs 496EXIT PROGRAM statement 448GOBACK statement 448I/O error declaratives 238IGZBRDGE 500IGZEOPT 500IGZETUN 500interlanguage communication 499limitations 499nested programs 499older compilers 500overview 493preinitializing 495preparing <strong>COBOL</strong> programs <strong>for</strong> 493recursion 495recursive requirement 499reentrancy 499reentrancy requirement 499runtime restrictions 500sort and merge restriction 213STOP RUN statement 448synchronizing access toresources 499terminology 494THREAD compiler optionrestrictions with 352when to choose 495UPSI switches 500with PL/I tasks 499NN delimiter <strong>for</strong> national or DBCSliterals 28NAME compiler optiondescription 331using 5name declarationsearching <strong>for</strong> 461NAMESPACE-DECLARATION XMLevent 513, 514namingfiles 10programs 5NATIONAL (USAGE IS)external decimal 49floating point 50national comparison 94national datacannot use with DATE FORMATclause 636communicating with Java 612comparingoverview 139to alphabetic, alphanumeric, orDBCS 140to alphanumeric groups 141to numeric 140two operands 139concatenating (STRING) 101convertingexceptions 136from alphanumeric or DBCS withNATIONAL-OF 135from alphanumeric, DBCS, orinteger with MOVE 134890 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


national data (continued)converting (continued)overview 134to alphanumeric withDISPLAY-OF 136to numbers with NUMVAL,NUMVAL-C 113to or from Chinese GB 18030 138to or from Greek alphanumeric,example 137to or from UTF-8 137to uppercase or lowercase 113with INSPECT 111defining 127displaying on output 38encoding in XML documents 521evaluating with intrinsicfunctions 115external decimal 49external floating-point 50figurative constants 128finding the smallest or largestitem 116in conditional expressions 139in generated XML documents 544in keysin MERGE statement 222in OCCURS clause 70in SORT statement 222initializing, example of 31input with ACCEPT 37inspecting (INSPECT) 111LENGTH intrinsic function and 118LENGTH OF special register 118literalsusing 127MOVE statement with 34, 134NSYMBOL compiler option if noUSAGE clause 127reference modification of 108reversing characters 113specifying 126splitting (UNSTRING) 104VALUE clause with alphanumericliteral, example 117national decimal data (USAGENATIONAL)defining 129example 45<strong>for</strong>mat 49initializing, example of 32national floating-point data (USAGENATIONAL)defining 129definition 50national group itemadvantages over alphanumericgroups 130can contain only national data 26,131communicating with Java 612contrasted with USAGE NATIONALgroup 27defining 130example 26<strong>for</strong> defining tables 70in generated XML documents 544national group item (continued)initializingusing a VALUE clause 78using INITIALIZE 33, 76LENGTH intrinsic function and 118MOVE statement with 35overview 129passing as an argument 470treated as a group itemexample with INITIALIZE 132in INITIALIZE 33in MOVE CORRESPONDING 35summary 132treated as an elementary itemexample with MOVE 35in most cases 26, 129usingas an elementary item 131overview 130VALUE clause with alphanumericliteral, example 78national language support (NLS)DBCS 141LANGUAGE compiler option 326processing data 121national literalsdescription 28using 127national-edited datadefining 127editing symbols 127initializingexample 31using INITIALIZE 76MOVE statement with 34PICTURE clause 127NATIONAL-OF intrinsic functionexample with Chinese data 138example with Greek data 137example with UTF-8 data 137using 135with XML documents 522nested COPY statement 679, 724nested delimited scope statements 23nested IF statementcoding 90CONTINUE statement 89EVALUATE statement preferred 90with null branches 89nested intrinsic functions 60nested program integration 670nested program mapdescription 377example 386nested programscalling 458description 458guidelines 458map 377, 386scope of names 460transfer of control 458nesting levelprogram 382, 386statement 382NOCBLCARD translator option 414NOCOMPILE compiler optionuse to find syntax errors 372NODLL compiler optionwith dynamic calls 451with static calls 450NODYNAM compiler optionunder CICS 410under DB2 with CICS or CAF 429with static and dynamic calls 455with static calls 450with stored procedures 429NOFASTSRT compiler option 227, 231nondates with MLE 647N<strong>OS</strong>IMVRD runtime option 184N<strong>OS</strong>QLCCSID compiler optionrecommended <strong>for</strong> compatibility withDB2 precompiler 426Notices 835NSYMBOL compiler optiondescription 331effect on N literals 28<strong>for</strong> DBCS literals 127<strong>for</strong> national data items 127<strong>for</strong> national literals 127multioption interaction 304null branch 89null-terminated stringsexample 107handling 470manipulating 106NUMBER compiler optiondescription 332<strong>for</strong> debugging 379NUMCLS installation option, effect onnumeric class test 57numeric class testchecking <strong>for</strong> valid data 56effect of NUMPROC, NUMCLS 57numeric comparison 94numeric databinaryUSAGE BINARY 50USAGE COMPUTATIONAL(COMP) 50USAGE COMPUTATIONAL-4(COMP-4) 50USAGE COMPUTATIONAL-5(COMP-5) 51can compare algebraic valuesregardless of USAGE 140comparing to national 140convertingbetween fixed- andfloating-point 54precision 54to national with MOVE 134defining 45display floating-point (USAGEDISPLAY) 50editing symbols 47external decimalUSAGE DISPLAY 49USAGE NATIONAL 49external floating-pointUSAGE DISPLAY 50USAGE NATIONAL 50internal floating-pointUSAGE COMPUTATIONAL-1(COMP-1) 52Index 891


numeric data (continued)internal floating-point (continued)USAGE COMPUTATIONAL-2(COMP-2) 52national decimal (USAGENATIONAL) 49national floating-point (USAGENATIONAL) 50packed-decimalsign representation 55USAGE COMPUTATIONAL-3(COMP-3) 52USAGE PACKED-DECIMAL 52PICTURE clause 45, 47storage <strong>for</strong>mats 48USAGE DISPLAY 45USAGE NATIONAL 45zoned decimal (USAGE DISPLAY)<strong>for</strong>mat 49sign representation 55numeric intrinsic functionsdifferences from LanguageEnvironment callable services 61equivalent Language Environmentcallable services 60example ofANNUITY 64CURRENT-DATE 63INTEGER 110INTEGER-OF-DATE 63LENGTH 63, 117LOG 64MAX 63, 87, 116, 117MEAN 64MEDIAN 64, 87MIN 110NUMVAL 113NUMVAL-C 63, 113ORD 115ORD-MAX 87PRESENT-VALUE 63RANGE 64, 87REM 64SQRT 64SUM 87integer, floating-point, mixed 59nested 60special registers as arguments 60table elements as arguments 60uses <strong>for</strong> 59numeric literals, description 28numeric-edited dataBLANK WHEN ZERO clausecoding with numeric data 127example 47defining 127editing symbols 47initializingexamples 32using INITIALIZE 76PICTURE clause 47USAGE DISPLAYdisplaying 47initializing, example of 32USAGE NATIONALdisplaying 47initializing, example of 32NUMPROC compiler optionaffected by NUMCLS 57description 333effect on sign processing 55per<strong>for</strong>mance considerations 673NUMVAL intrinsic functiondescription 113NUMVAL-C intrinsic functiondescription 113example 63NX delimiter <strong>for</strong> national literals 28Oo suffix with cob2 289objectcreating 586definition of 561deleting 588object codecompilation and listing 273creating 269generating 313producing in 80-column record 317OBJECT compiler optiondescription 334multioption interaction 304object instances, definition of 561OBJECT paragraphinstance data 568, 592instance methods 569object referencescomparing 581converting from local to global 587example of passing 584setting 581typed 580universal 580OBJECT-COMPUTER paragraph 7object-oriented <strong>COBOL</strong>bindingexample 298overview 296calls to and from OO programs 461communicating with Java 612compatibility 300compilingunder z/<strong>OS</strong> UNIX 291using JCL or TSO/E 296DLLs in 491IMSaccessing databases 434calling <strong>COBOL</strong> method fromJava 432calling Java method from<strong>COBOL</strong> 433linkingexample 293overview 292preparing applicationsunder z/<strong>OS</strong> UNIX 292using JCL or TSO/E 296programs must be reentrant 464restrictionscannot run under CICS 407CICS 561EXEC CICS statements 561object-oriented <strong>COBOL</strong> (continued)restrictions (continued)EXEC SQL statements 561sort and merge 213SQL compiler option 561runningunder z/<strong>OS</strong> UNIX 293using JCL or TSO/E 297XPLINK linkage 299writing OO programs 561objectives of millennium languageextensions 637OCCURS clauseASCENDING|DESCENDING KEYphraseexample 86needed <strong>for</strong> binary search 85specify order of table elements 70cannot use in a level-01 item 69<strong>for</strong> defining table elements 69<strong>for</strong> defining tables 69INDEXED BY phrase <strong>for</strong> creatingindexes 74nested <strong>for</strong> creating multidimensionaltables 70OCCURS DEPENDING ON (ODO)clausecomplex 697<strong>for</strong> creating variable-length tables 81initializing ODO elements 83ODO object 81ODO subject 81optimization 666simple 81variable-length recordsQSAM 154VSAM 186OCCURS INDEXED BY clause, creatingindexes with 74ODO object 81ODO subject 81OFFSET compiler optiondescription 335multioption interaction 304output 402OMITTED clause, FILE SECTION 14OMITTED parameters 683OMITTED phrase <strong>for</strong> omittingarguments 468ON EXCEPTION phraseINVOKE statement 583, 597ON SIZE ERRORwith windowed date fields 652OPEN statementfile availability 162, 189, 210file status key 239line-sequential files 209multithreading serialization 496QSAM files 161VSAM files 187opening filesline-sequential 210multithreading serialization 496QSAM 162VSAMempty 190overview 189892 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


OPTFILE compiler option 335optimizationavoid ALTER statement 662avoid backward branches 662BINARY data items 664consistent data 665constant computations 663constant data items 663contained program integration 670duplicate computations 663effect of compiler options on 671effect on parameter passing 468effect on per<strong>for</strong>mance 662factor expressions 662index computations 667indexing 665nested program integration 670OCCURS DEPENDING ON 666out-of-line PERFORM 662packed-decimal data items 664per<strong>for</strong>mance implications 666procedure integration 670structured programming 662subscript computations 667subscripting 665table elements 665top-down programming 662unreachable code 669, 670unused data items 336, 382OPTIMIZE compiler optiondescription 336effect on parameter passing 468effect on per<strong>for</strong>mance 669multioption interaction 304per<strong>for</strong>mance considerations 672using 669optimizerexample 670overview 669optional filesQSAM 163VSAM 190ORD intrinsic function, example 115ORD-MAX intrinsic functionexample table calculation 87using 116ORD-MIN intrinsic function 116order of evaluationarithmetic operators 59, 689compiler options 304out-of-line PERFORM 98OUTDD compiler optionDD not allocated 39description 337interaction with DISPLAY 39outputcoding <strong>for</strong> CICS 408coding <strong>for</strong> line-sequential files 209coding <strong>for</strong> QSAM files 161coding <strong>for</strong> VSAM files 187data set 269from compiler, under z/<strong>OS</strong> 265to files 145output files with cob2 289output procedurecoding 218example 218, 222output procedure (continued)FASTSRT option not effective 226requires RETURN or RETURNINTO 218restrictions 219overflow conditionCALL 244joining and splitting strings 234UNSTRING 103overloading instance methods 574overridingfactory methods 596instance methods 573Ppacked-decimal data itemdate fields, potential problems 657description 52sign representation 55synonym 49using efficiently 52, 664pagecontrol 164depth 14paragraphgrouping 100introduction 20parametersADEXIT 728describing in called program 468INEXIT 722LIBEXIT 725main program in UNIX 442MSGEXIT 729PRTEXIT 726parse data item, definition 506parsing XML documentsdescription 506one segment at a timeexample 537overview 518overview 504UTF-8 525white space 522with validationexample 539overview 515per<strong>for</strong>mance considerations 516restrictions 516XML declaration 522passing data between programsaddresses 471arguments in calling program 467BY CONTENT 465BY REFERENCE 465BY VALUEoverview 465restrictions 467EXTERNAL data 475in the RETURN-CODE specialregister 474JNI services 608OMITTED arguments 468options considerations 43parameters in called program 468with Java 612passwordalternate index 196example 196VSAM files 196PASSWORD clause 196PATH environment variabledescription 439example of setting 296path name<strong>for</strong> copybook search 288, 363PERFORM statementcoding loops 97<strong>for</strong> a tableexample using indexing 80example using subscripting 79<strong>for</strong> changing an index 75inline 98out-of-line 98per<strong>for</strong>med an explicit number oftimes 99TEST AFTER 99TEST BEFORE 99THRU 100TIMES 99UNTIL 99VARYING 100VARYING WITH TEST AFTER 100WITH TEST AFTER ...UNTIL 99WITH TEST BEFORE ...UNTIL 99per<strong>for</strong>manceAIXBLD runtime option 676and debugging 350APPLY WRITE-ONLY clause 12arithmetic evaluations 664arithmetic expressions 665blocking QSAM files 159, 307calls 455CBLPSHPOP considerations 417CBLPSHPOP runtime option 417CICS environment 661, 676coding 661coding tables 665compiler optionARITH 672AWO 672BLOCK0 672DYNAM 672FASTSRT 672NUMPROC 55, 672OPTIMIZE 669, 672RENT 672RMODE 672SQLCCSID 427SSRANGE 672TEST 672THREAD 353, 672TRUNC 354, 672consistent data types 665data usage 664DATEPROC(TRIG) 649effect of compiler options on 671effects of buffer size 309exponentiations 665IMS environment 431, 676OCCURS DEPENDING ON 666optimizerexample 670Index 893


per<strong>for</strong>mance (continued)optimizer (continued)overview 669order of WHEN phrases inEVALUATE 92out-of-line PERFORM compared withinline 98parsing XML documents withvalidation 516programming style 662runtime considerations 661striped extended-<strong>for</strong>mat QSAM datasets 172table handling 667table searchingbinary compared with serial 84improving serial search 84tape, QSAM 160variable subscript data <strong>for</strong>mat 73VSAM files 203, 676worksheet 675period as scope terminator 22PGMNAME compiler optionCOMPAT suboption 339description 338LONGMIXED suboption 340LONGUPPER suboption 339physical block 145physical record 14, 145PICTURE clausecannot use <strong>for</strong> internal floatingpoint 46determining symbol used 313incompatible data 56N <strong>for</strong> national data 127national-edited data 127numeric data 45numeric-edited data 127Z <strong>for</strong> zero suppression 47PL/I taskingP<strong>OS</strong>IX runtime option 499with <strong>COBOL</strong> 499pointer data itemdescription 41incrementing addresses with 471NULL value 471passing addresses 471processing chained lists 471used to process chained list 472porting applicationseffect of separate sign 46P<strong>OS</strong>IXcalling APIs 440threads 499P<strong>OS</strong>IX runtime optioneffect on DLL search order 486use in OO applications 297precedencearithmetic operators 59, 689CICS options 412compiler optionsin batch 276in SYSOPTF data sets 268, 336under z/<strong>OS</strong> 271under z/<strong>OS</strong> UNIX 284copybook search order 283preferred sign 55preinitializing the <strong>COBOL</strong> environmentwith multithreading 495prelinking cataloged procedurecompile, prelink, link-edit 255compile, prelink, link-edit, run 256compile, prelink, load, run 258prelink and link-edit 258PRESENT-VALUE intrinsic function 63preserving original sequence in asort 224priority numbers, segmentation 672procedure and data-name cross-reference,description 376PROCEDURE DIVISIONadditional in<strong>for</strong>mation 394client 578description 19in subprograms 469instance method 572RETURNINGmethods, use of 474to return a value 19signature in<strong>for</strong>mation bytes 392, 394statementscompiler-directing 22conditional 21delimited scope 21imperative 21terminology 19USINGBY VALUE 469to receive parameters 19, 468verbs present in 392procedure integration 670procedure-pointer data itemcalling C/C++ 463calling JNI services 463definition 462entry address <strong>for</strong> entry point 462passing parameters to callableservices 462SET procedure-pointer 462with DLLs 488processdefinition 494PROCESS (CBL) statementbatch compiling 276conflicting options in 304overview 365precedencein batch 276under z/<strong>OS</strong> 271under z/<strong>OS</strong> UNIX 284specifying compiler options 272processingchained listsexample 472overview 471labels <strong>for</strong> QSAM files 174tablesexample using indexing 80example using subscripting 79producing XML output 543product support xviii, 873programattribute codes 386program (continued)compiling and linking using cob2DLLs 286examples 287overview 285compiling under z/<strong>OS</strong> 249compiling under z/<strong>OS</strong> UNIX 283decisionsEVALUATE statement 89IF statement 89loops 99PERFORM statement 99switches and flags 95developing <strong>for</strong> z/<strong>OS</strong> UNIX 437diagnostics 381initialization code 388limitations 661main 447nesting level 382reentrant 464restarting 628signature in<strong>for</strong>mation bytes 389statistics 381structure 5subprogram 447PROGRAM COLLATING SEQUENCEclausedoes not affect national or DBCSoperands 9establishing collating sequence 9overridden by COLLATINGSEQUENCE phrase 9overrides default collatingsequence 223program processing table 410program terminationactions taken in main andsubprogram 448statements 448PROGRAM-ID paragraphcoding 5COMMON attribute 6INITIAL attribute 7program-namesavoid using certain prefixes 5cross-reference 400handling of case 338specifying 5protecting VSAM files 196PRTEXIT suboption of EXIT optionprocessing of 726syntax 720QQSAM filesadding records to 163ASCII tape file 177ASSIGN clause 152attributes 170BLOCK CONTAINS clause 159, 307block size 159, 307blocking enhances per<strong>for</strong>mance 159,307blocking records 159, 173closing 165closing to prevent reopening 162894 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


QSAM files (continued)DATA DIVISION entries 152ENVIRONMENT DIVISIONentries 151FASTSRT requirements 226input/output error processing 165,235input/output statements <strong>for</strong> 161label processing 174obtaining buffers <strong>for</strong> 173opening 162processingexisting files 171HFS files 174in reverse order 163new files 172overview 151replacing records 164retrieving 169striped extended-<strong>for</strong>mat 172tape per<strong>for</strong>mance 160under z/<strong>OS</strong>creating files 166, 169DD statement <strong>for</strong> 166, 169defining 166, 169environment variable <strong>for</strong> 166file availability 163job control language (JCL) 168updating files 163using same input/output file underFASTSRT 226writing to a printer 164QUOTE compiler option 340Rrailroad track diagrams, how to read xvirandom numbers, generating 61RANGE intrinsic functionexample statistics calculation 64example table calculation 87RD parameter of JOB or EXECstatement 628READ INTO <strong>for</strong> <strong>for</strong>mat-V VSAMfiles 187READ NEXT statement 187READ statementline-sequential files 209multithreading serialization 496QSAM 161VSAM 187reading recordsblock size 160from line-sequential files 210reading records from VSAM filesdynamically 192randomly 192sequentially 192reason code from XML parsing 526, 709recorddescription 13<strong>for</strong>matfixed-length QSAM 153fixed-length VSAM 186<strong>for</strong>mat D 154, 155, 177<strong>for</strong>mat F 153, 177<strong>for</strong>mat S 156, 157record (continued)<strong>for</strong>mat (continued)<strong>for</strong>mat U 158, 159, 177<strong>for</strong>mat V 154, 155, 177QSAM ASCII tape 177spanned 156, 157undefined 158, 159variable-length QSAM 154, 155variable-length VSAM 186order, effect of organization on 145RECORD CONTAINS clauseFILE SECTION entry 14RECORD KEY clauseidentifying prime key in KSDSfiles 182RECORDING MODE clausefixed-length records, QSAM 153QSAM files 14specify record <strong>for</strong>mat 152variable-length records, QSAM 154,155recursive callsand the LINKAGE SECTION 19coding 461identifying 6REDEFINES clause, making a record intoa table using 77reentrant programs 464reference modificationexample 109expression checking withSSRANGE 347generated XML documents 544intrinsic functions 107national data 108out-of-range values 109tables 73, 108UTF-8 documents 138reference modifierarithmetic expression as 110intrinsic function as, example 110variables as 108registers used by EXIT compileroption 721relation condition 94relative file organization 145RELEASE FROM statementcompared to RELEASE 217example 216RELEASE statementcompared to RELEASE FROM 217with SORT 216, 217REM intrinsic function 64RENT compiler optiondescription 341<strong>for</strong> DLLs 482<strong>for</strong> IMS 431<strong>for</strong> Java interoperability 291, 296<strong>for</strong> OO <strong>COBOL</strong> 291, 296influencing addressability 42multioption interaction 42, 304per<strong>for</strong>mance considerations 672when passing data 43REPLACE statementDB2 considerations 428description 365replacingdata items (INSPECT) 111records in QSAM file 164records in VSAM file 194text, DB2 considerations 428REPLACING phrase (INSPECT),example 111REP<strong>OS</strong>ITORY paragraphclass 566client 579coding 7subclass 591representationdata 56sign 55RERUN clausecheckpoint/restart 231reserved-word table, CICS alternateoverview 415specifying with WORD 357residency mode, definition 42restartautomatic 629deferred 629overview 625routine 625restarting a program 628restrictionsCICS16-MB line 408calls 409coding 8, 407OUTDD compiler option 338parsing with validation usingFILE 516separate translator 413sorting 232DB2 coprocessor 424IMS16-MB line 408coding 8, 431input/output procedures 219OO programs 561SQL compiler option 424subscripting 73resubmitting a job 631return codecompilerdepends on highest severity 281effect of messagecustomization 732overview 281feedback code from LanguageEnvironment services 683from CICS ECI 411from DB2 SQL statements 423from XML parsing 526, 709RETURN-CODE special register 474,683VSAM filesdescription 241example 241RLS mode 203when control returns to operatingsystem 474RETURN statementrequired in output procedure 218Index 895


RETURN statement (continued)with INTO phrase 218RETURN-CODE special registercalls to Language Environmentservices 683CICS ECI calls 411considerations <strong>for</strong> DB2 423not set by INVOKE 583passing data between programs 474sharing return codes betweenprograms 474when control returns to operatingsystem 474RETURNING phraseCALL statement 475INVOKE statement 585methods, use of 474PROCEDURE DIVISION header 573REVERSE intrinsic function 113reverse order of tape files 163reversing characters 113REWRITE statementmultithreading serialization 496QSAM 161VSAM 187RLS parameter 202RMODEdescription 42of EXIT modules 721RMODE compiler optiondescription 342influencing addressability 42multioption interaction 42per<strong>for</strong>mance considerations 672when passing data 43ROUNDED phrase 688rows in tables 71RRDS (relative-record data sets)file access mode 185fixed-length records 180, 184organization 184per<strong>for</strong>mance considerations 203simulating variable-lengthrecords 184variable-length records 180, 184run timechanging file-name 11multithreading restrictions 500per<strong>for</strong>mance considerations 661run unitdescription 447role in multithreading 494running OO applicationsunder z/<strong>OS</strong> UNIXoverview 293XPLINK linkage 299using JCL or TSO/E 297XPLINK linkage 299runtime optionsaffecting DATA compiler option 43AIXBLD 676ALL31 453CBLPSHPOP 416CHECK(OFF)per<strong>for</strong>mance considerations 672DEBUG 370ENVAR 297runtime options (continued)MSGFILE 338N<strong>OS</strong>IMVRD 184P<strong>OS</strong>IXDLL search order 486use in OO applications 297specifying under z/<strong>OS</strong> UNIX 437Standard <strong>COBOL</strong> 85con<strong>for</strong>mance 303TRAPclosing files in QSAM 165closing files in VSAM 195closing line-sequential files 212ON SIZE ERROR 234XPLINKnot recommended as adefault 299setting 299SS-<strong>for</strong>mat recordlayout 157overview 157requesting 156S-level error message 281, 374sample programs 815scope of namesglobal 460local 460scope terminatoraids in debugging 368explicit 21, 22implicit 22SD (sort description) entry, example 215SEARCH ALL statementbinary search 85example 86<strong>for</strong> changing an index 75table must be ordered 85search orderDLLs in the HFS 486SEARCH statementexample 84<strong>for</strong> changing an index 75nesting to search more than one levelof a table 84serial search 84searching<strong>for</strong> name declarations 461tablesbinary search 85overview 84per<strong>for</strong>mance 84serial search 84sectiondeclarative 23description of 20grouping 100segmentation 672SELECT clauseASSIGN clause 10naming files 10vary input-output file 11SELECT OPTIONALQSAM 163VSAM 190SELF 581sentence, definition 20separate CICS translatorcompiler options <strong>for</strong> 411, 414restrictions 413using 414separate sign<strong>for</strong> line-sequential files 211portability 46printing 46required <strong>for</strong> signed nationaldecimal 46SEQUENCE compiler option 343sequential file organization 145sequential searchdescription 84example 84sequential storage device 146serial searchdescription 84example 84serialization of files withmultithreading 496SERVICE LABEL statement 365SET condition-name TO TRUE statementexample 98, 100switches and flags 96SET statement<strong>for</strong> changing an index 74<strong>for</strong> changing index data items 74<strong>for</strong> function-pointer data items 462<strong>for</strong> object references 581<strong>for</strong> procedure-pointer data items 462<strong>for</strong> setting a condition, example 96handling of program-name in 338using <strong>for</strong> debugging 370settingindex data items 74indexes 74switches and flags 96sharingdatabetween separately compiledprograms 475coding the LINKAGESECTION 469from another program 18in recursive or multithreadedprograms 19in separately compiledprograms 18overview 465parameter-passingmechanisms 465passing arguments to amethod 583PROCEDURE DIVISIONheader 469RETURN-CODE specialregister 474returning a value from amethod 585scope of names 460with Java 612filesscope of names 460using EXTERNAL clause 14, 475896 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


sharing (continued)files (continued)using GLOBAL clause 14short listing, example 379sign conditiontesting sign of numeric operand 94using in date processing 650SIGN IS SEPARATE clause<strong>for</strong> line-sequential files 211portability 46printing 46required <strong>for</strong> signed national decimaldata 46sign representation 55signaturedefinition of 570must be unique 570signature in<strong>for</strong>mation bytescompiler options in effect 389DATA DIVISION 391ENVIRONMENT DIVISION 392PROCEDURE DIVISION 392, 394SIZE compiler option 344size of printed page, control 164skip a block of records 160sliding century window 639softcopy in<strong>for</strong>mation xviiisortalternate collating sequence 223checkpoint/restart 231completion code 224controlling behavior of 228criteria 221data sets needed under z/<strong>OS</strong> 219DD statements <strong>for</strong> defining z/<strong>OS</strong> datasets 219description 213determining success 224diagnostic message 225FASTSRT compiler optionimproving per<strong>for</strong>mance 225requirements 226using same QSAM file <strong>for</strong> inputand output 226files, describing 215input procedurescoding 216example 222keysdefining 221overview 214NOFASTSRT compiler option 227output procedurescoding 218example 218, 222pass control statements to 229per<strong>for</strong>manceFASTSRT 225variable-length files 220preserving original sequence 224process 214restrictions 213restrictions on input/outputprocedures 219special registers 228storage use 230terminating 225sort (continued)under CICS 231variable-length records 220windowed date fields 223workspace 231SORT statementASCENDING|DESCENDING KEYphrase 222COLLATING SEQUENCE phrase 9,223description 220GIVING phrase 220overview 213restrictions 213restrictions <strong>for</strong> CICS applications 232under CICS 231change reserved-word table 416USING phrase 220SORT-CONTROL special register 229SORT-CORE-SIZE special register 229SORT-FILE-SIZE special register 229SORT-MESSAGE special register 229SORT-MODE-SIZE special register 229SORT-RETURN special register 229determining sort or mergesuccess 224terminating sort or merge 225SORTCKPT DD statement 231SOURCE and NUMBER output,example 381source codecompiler data set 267line number 382, 386listing, description 377program listing 273SOURCE compiler optiondescription 344getting output 377SOURCE-COMPUTER paragraph 7SPACE compiler option 345spanned files 157spanned record <strong>for</strong>matdescription 156layout 157requesting 156special feature specification 7special registerADDRESS OFuse in CALL statement 466arguments in intrinsic functions 60JNIEnvPtruse <strong>for</strong> JNI callable services 607LENGTH OF 118, 466RETURN-CODE 474SORT-RETURNdetermining sort or mergesuccess 224terminating sort or merge 225using in XML parsing 508, 510WHEN-COMPILED 119XML-CODE 508, 511XML-EVENT 508, 510XML-NAMESPACE 508, 513XML-NAMESPACE-PREFIX 509, 514XML-NNAMESPACE 509, 513XML-NNAMESPACE-PREFIX 509,514special register (continued)XML-NTEXT 508, 512XML-TEXT 508, 512SPECIAL-NAMES paragraphcoding 7QSAM files 177splitting data items (UNSTRING) 103SQL compiler optiondescription 345multioption interaction 304restrictionscompiling in batch 424OO programs 561using 423SQL statementsCCSID determination 425coding 420EXIT compiler option and 734overview 419return codes 423SQL DECLARE 421SQL INCLUDE 420use <strong>for</strong> DB2 services 419using binary data in 423using character data in 421using national decimal data 422SQLCAdeclare <strong>for</strong> programs that use SQLstatements 420return codes from DB2 423SQLCCSID compiler optiondescription 347effect on CCSID of string data 425per<strong>for</strong>mance considerations 427recommended with DB2coprocessor 426SQRT intrinsic function 64SSRANGE compiler optiondescription 347per<strong>for</strong>mance considerations 672reference modification 109turn off by using CHECK(OFF)runtime option 672using 373STACK runtime optioninfluencing data location 43multioption interaction 42STANDARD clause, FD entry 14Standard <strong>COBOL</strong> 85checkpoints 626considerations <strong>for</strong> CICS 414required compiler options 303required runtime options 303standard label <strong>for</strong>mat 176standard label, QSAM 178START statementmultithreading serialization 496VSAM 187statementcompiler-directing 22conditional 21definition 20delimited scope 21explicit scope terminator 22imperative 21implicit scope terminator 22nesting level 382Index 897


static callsexample 456making 450per<strong>for</strong>mance 455with dynamic calls 455static data areas, allocating storage 43static data, definition of 561static methodsdefinition of 561invoking 597statistics intrinsic functions 64status code, VSAM filesdescription 241example 241stderrcontrolling line spacing 39directing with DISPLAY 39setting DISPLAY to 439stdinreading with ACCEPT 37stdoutcontrolling line spacing 39directing with DISPLAY 39setting DISPLAY to 439STEPLIB environment variabledescription 439example of specifying compiler 285STOP RUN statementin main program 448in subprogram 448with multithreading 448storagecharacter data 133devicedirect-access 146sequential 146<strong>for</strong> arguments 467management with LanguageEnvironment callable services 681mapping 377use during sort 230stride, table 667STRING statementexample 102overflow condition 234using 101with DBCS data 703stringshandling 101Javadeclaring 613manipulating 616null-terminated 470striped extended-<strong>for</strong>mat QSAM file 172structure, initializing usingINITIALIZE 32structured programming 662structuring OO applications 603subclasscodingexample 592overview 589instance data 592subprogramand main program 447definition 465description 447subprogram (continued)linkage 447common data items 468PROCEDURE DIVISION in 469terminationeffects 448subscriptcomputations 667definition 72literal, example 72range checking 373variable, example 72subscriptingdefinition 72example 79literal, example 72reference modification 73relative 73restrictions 73use data-name or literal 73variable, example 72substitution character 128substringsof table elements 108reference modification of 107SUM intrinsic function, example tablecalculation 87SUPER 586support xviii, 873switch-status condition 94switches and flagsdefining 95description 95resetting 96setting switches off, example 97setting switches on, example 96testing multiple values, example 96testing single values, example 95SYMBOLIC CHARACTERS clause 10symbolic constant 663syntax diagrams, how to read xvisyntax errorsfinding with NOCOMPILE compileroption 372SYSABEND filedescription 265SYSADATAfile, creating 270output 305records, exit module 727SYSADATA filedescription 265example 749file contents 747record descriptions 750record types 748SYSDEBUG data setdefining 270use of 350SYSDEBUG filedescription 265SYSIN data setdefining 267description 265SYSJAVA filedefining 270description 265SYSLIB data setdefining 268description 265when not used 723SYSLIB environment variabledescription 283specifying location of JNI.cpy 291SYSLIN data set 269description 265SYSMDECK filedefining 271description 265SYSMDUMP filedescription 265SYSOPTF data setdefining 267description 265SYSPRINT data setdefining 269description 265when not used 726SYSPUNCH data setdescription 265, 269requirements <strong>for</strong> DECK compileroption 317system dateunder CICS 409system dump 233system-determined block sizecompiler data sets 267QSAM files 160, 307system-name 7SYSTERM data setdefining 269description 265sending messages to 348SYSUDUMP filedescription 265SYSUT data set 265Ttableassigning values to 77columns 69compare to array 41defining with OCCURS clause 69definition 69depth 71description 41dynamically loading 75efficient coding 665, 667elements 69identical element specifications 665index, definition 72initializingall occurrences of an element 78at the group level 78each item individually 77using INITIALIZE 76using PERFORM VARYING 100loading values in 75looping through 100multidimensional 70one-dimensional 69processing with intrinsicfunctions 86898 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


table (continued)redefining a record as 77reference modification 73referencing substrings ofelements 108referencing with indexes, example 72referencing with subscripts,example 72referring to elements 72rows 71searchingbinary 85overview 84per<strong>for</strong>mance 84sequential 84serial 84stride computation 667subscript, definition 72three-dimensional 71two-dimensional 71variable-lengthcreating 81example of loading 82initializing 83preventing overlay in 699TALLYING phrase (INSPECT),example 111tape filesper<strong>for</strong>mance 160reverse order 163TERMINAL compiler option 348terminal, sending messages to 348terminating XML parsing 530termination 448terminologyVSAM 179terms used in MAP output 384testconditions 99data 94numeric operand 94UPSI switch 94TEST AFTER 99TEST BEFORE 99TEST compiler optiondescription 349multioption interaction 304per<strong>for</strong>mance considerations 672use <strong>for</strong> debugging 377text-name cross-reference,description 376text-name environment variable 283TGT memory mapdescription 387example 396THREAD compiler optionand the LINKAGE SECTION 19cannot use with nestedprograms 458description 352<strong>for</strong> Java interoperability 291, 296<strong>for</strong> OO <strong>COBOL</strong> 291, 296multioption interaction 304per<strong>for</strong>mance considerations 672threadingand preinitialization 495control transfer 495threading (continued)ending programs 496z/<strong>OS</strong> UNIX considerations 437TITLE statement 365controlling header on listing 7top-down programmingconstructs to avoid 662TRACK OVERFLOW option 161Trademarks 837trailer labeldefinition 175using 175transferring controlbetween <strong>COBOL</strong> and non-<strong>COBOL</strong>programs 447between <strong>COBOL</strong> programs 449, 458called program 447calling program 447main and subprograms 447nested programs 458trans<strong>for</strong>ming <strong>COBOL</strong> data to XMLexample 549overview 543TRAP runtime optionclosing line-sequential files 212closing QSAM files 165closing VSAM files 195ON SIZE ERROR 234TRUNC compiler optiondescription 353per<strong>for</strong>mance considerations 672suboptions <strong>for</strong> separate CICStranslator 415TSOALLOCATE command 261CALL command 261compiling under 261SYSTERM <strong>for</strong> compiler messages 269tuning considerations, per<strong>for</strong>mance 671,672typed object references 580UU-<strong>for</strong>mat recordlayout 159requesting 158U-level error message 281, 374unavailable filesQSAM 163VSAM 197UNDATE intrinsic functionexample 655using 654undefined record <strong>for</strong>matlayout 159QSAM 177requesting 158unfilled tracks 161Unicodedescription 125encoding and storage 133JNI services 616processing data 121using with DB2 421universal object references 580UNIXaccessing environment variablesexample 440overview 438accessing main parameters 442example 443calling APIs 440compiler environment variables 283compiling from script 290compiling OO applicationsexample 293overview 291compiling under 283copybook search order 283, 288, 364copybooks 364developing programs 437execution environments 437linking OO applicationsexample 293overview 292preparing OO applicationsexample 293overview 292programs must be reentrant 464restrictions 437running OO applicationsoverview 293XPLINK linkage 299running programs 437setting environment variablesexample 440overview 438sort and merge restriction 213specifying compiler options 284unreachable code 669, 670UNSTRING statementexample 104overflow condition 234using 103with DBCS data 703updating VSAM records 193UPPER-CASE intrinsic function 113uppercase, converting to 113UPSI switches with multithreading 500USAGE clauseat the group level 27incompatible data 56INDEX phrase, creating index dataitems with 74NATIONAL phrase at the grouplevel 130OBJECT REFERENCE 580USE...LABEL declarative 176USE AFTER STANDARD LABEL 178USE FOR DEBUGGING declarativesoverview 370USE statement 365user labelexits 178QSAM 178standard 177user-defined condition 94user-exit work area 721user-label track 175USING phraseINVOKE statement 583Index 899


USING phrase (continued)PROCEDURE DIVISION header 469,573UTF-16definition 125encoding <strong>for</strong> national data 125UTF-8avoid INSPECT 525avoid moves that truncate 525avoid reference modification withXML documents 138converting to or from national 137definition 125encoding and storage 133encoding <strong>for</strong> ASCII invariantcharacters 125example of generating an XMLdocument 545JNI services 619parsing XML documents 525processing data items 137VV-<strong>for</strong>mat recordlayout 155requesting 154validating XML documentsexample 539overview 515per<strong>for</strong>mance considerations 516restrictions 516VALUE clausealphanumeric literal with nationaldata, example 117alphanumeric literal with nationalgroup, example 78assigning table valuesat the group level 78to each item individually 77to each occurrence of anelement 78assigning to a variable-lengthgroup 83cannot use <strong>for</strong> external floatingpoint 50initializing internal floating-pointliterals 46large literals with COMP-5 51large, with TRUNC(BIN) 355VALUE IS NULL 471VALUE OF clause 14variableas reference modifier 108definition 25variable-length recordsOCCURS DEPENDING ON (ODO)clause 666QSAMlayout 155requesting 154sorting 220VSAMdefining 186RRDS 180variable-length tableassigning values to 83variable-length table (continued)creating 81example 82example of loading 82preventing overlay in 699variables, environmentexample of setting and accessing 440library-name 363runtime 439variably located data item 697variably located group 697VBREF compiler optiondescription 356output example 403using 377verb cross-reference listingdescription 377verbs used in program 377VSAM filesadding records to 193allocating with environmentvariable 200closing 195coding input/output statements 187comparison of file organizations 181creating alternate indexes 198DATA DIVISION entries 185deleting records from 194ENVIRONMENT DIVISIONentries 181error processing 235file position indicator (CRP) 189, 192file status key 195input/output error processing 195loadingdynamically or randomly 190extended <strong>for</strong>mat 191sequentially 190with access method services 191openingempty 190overview 189per<strong>for</strong>mance considerations 203processing files 179protecting with password 196reading records from 192record-level sharing (RLS)error handling 203overview 202preventing update problems 202restrictions 203replacing records in 194status codesdescription 241example 241under z/<strong>OS</strong>defining data sets 197file availability 197JCL 200RLS mode 202updating records 193VSAM terminologyBDAM data set 179comparison to non-VSAM terms 179ESDS <strong>for</strong> QSAM 179KSDS <strong>for</strong> ISAM 179RRDS <strong>for</strong> BDAM 179WW-level message 281, 374WHEN phraseEVALUATE statement 91SEARCH ALL statement 85SEARCH statement 84WHEN-COMPILED intrinsicfunction 119WHEN-COMPILED special register 119white space in XML documents 522windowed date fieldscontracting 658sorting on 223WITH DEBUGGING MODE clause<strong>for</strong> debugging lines 370<strong>for</strong> debugging statements 370WITH POINTER phraseSTRING 101UNSTRING 103WORD compiler optiondescription 356multioption interaction 304recommended <strong>for</strong> CICS integratedtranslator 412recommended <strong>for</strong> CICS separatetranslator 415work data sets <strong>for</strong> compiling 265WORKING-STORAGE SECTIONclient 580, 581comparison with LOCAL-STORAGEexample 17OO client 581overview 16factory data 594finding location and size of 398instance data 568, 592instance method 571multithreading considerations 581storage location <strong>for</strong> data 314workspaceuse during sort 231wrapper, definition of 603wrapping procedure-orientedprograms 603write a block of records 160WRITE ADVANCING statement 164WRITE statementline-sequential files 209multithreading serialization 496QSAM 161VSAM 187Xx suffix with cob2 289XML declarationgenerating 545specifying encoding declaration 523white space cannot precede 522XML documentaccessing 506code pages supported 520controlling the encoding of 547EBCDIC special characters 524encoding 520, 521900 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


XML document (continued)enhancingexample of converting hyphens tounderscores 557example of modifying datadefinitions 554rationale and techniques 553eventsexample 535generatingexample 549overview 543handling parsing exceptions 526national language 521parser 504parsingdescription 506example 532, 535, 537one segment at a time 518UTF-8 525parsing with validationexample 539overview 515per<strong>for</strong>mance considerations 516restrictions 516processing 503specifying encoding ifalphanumeric 523white space 522XML declaration 522XML eventCONTENT-CHARACTERSexample 539when parsing segments 519encoding conflicts 528, 529END-OF-INPUTexample 539when parsing segments 519EXCEPTION 528fatal errors 528NAMESPACE-DECLARATION 513,514overview 510processing 504, 508processing procedure 506XML exception codes<strong>for</strong> generating 718<strong>for</strong> parsing withXMLPARSE(COMPAT)handleable 711not handleable 715<strong>for</strong> parsing withXMLPARSE(XMLSS) 709XML GENERATE statementCOUNT IN 548NAMESPACE 545NAMESPACE-PREFIX 546NOT ON EXCEPTION 547ON EXCEPTION 548WITH ATTRIBUTES 545WITH ENCODING 547XML-DECLARATION 545XML generationcounting generated characters 544description 543XML generation (continued)enhancing outputexample of converting hyphens tounderscores 557example of modifying datadefinitions 554rationale and techniques 553example 549generating attributes 545generating elements 544handling errors 548ignored data items 544no byte order mark 548overview 543using namespace prefixes 546using namespaces 545XML outputcontrolling the encoding of 547enhancingexample of converting hyphens tounderscores 557example of modifying datadefinitions 554rationale and techniques 553generatingexample 549overview 543XML PARSE statementNOT ON EXCEPTION 507ON EXCEPTION 507overview 504using 506XML parsererror handling 528overview 504XML parsingcontrol flow with processingprocedure 511description 506fatal errors 528handling encoding conflicts 528, 529handling exceptions 526one segment at a timeexample 537overview 518overview 503reason code 526, 709return code 526, 709special registers 508, 510terminating 530with validationexample 539overview 515per<strong>for</strong>mance considerations 516restrictions 516XML processing procedurecontrol flow with parser 511error with EXIT PROGRAM orGOBACK 509exampleone segment at a time 537parsing with validation 539program <strong>for</strong> processing XML 532handling encoding conflicts 529handling parsing exceptions 526multiple segments 519restriction on XML PARSE 509XML processing procedure (continued)setting XML-CODE in 529specifying 506using special registers 508, 510writing 508XML schemas 517XML-CODE special registercontent 511continuation after nonzero value 530control flow between parser andprocessing procedure 511description 508exception codes <strong>for</strong> generating 718exception codes <strong>for</strong> parsing withXMLPARSE(COMPAT)encoding conflicts 527handleable 711not handleable 715exception codes <strong>for</strong> parsing withXMLPARSE(XMLSS) 709fatal errors 528reason code 526, 709return code 526, 709setting to -1 507, 511, 530setting to 1 519subtracting 100,000 from 529terminating parsing 530using in generating 547using in parsing 503with code-page conflicts 528with encoding conflicts 529with generating exceptions 548with parsing exceptions 528XML-EVENT special registercontent 510, 531description 508using 503, 508with parsing exceptions 528XML-NAMESPACE special registercontent 513description 508using 503XML-NAMESPACE-PREFIX specialregistercontent 514description 509using 503XML-NNAMESPACE special registercontent 513description 509using 503XML-NNAMESPACE-PREFIX specialregistercontent 514description 509using 503XML-NTEXT special registercontent 512description 508using 503with parsing exceptions 528XML-TEXT special registercontent 512, 531description 508using 503with parsing exceptions 528Index 901


XMLPARSE compiler optionchoosing the parser 503description 357XPLINK linkage convention in OOapplications 299XPLINK runtime optionnot recommended as a default 299setting 299XREF compiler optiondescription 358finding copybook data sets 376finding data- andprocedure-names 376getting output 377XREF outputCOPY/BASIS cross-references 400data-name cross-references 398program-name cross-references 400Yyear field expansion 641year windowingadvantages 638how to control 653MLE approach 638when not supported 644year-first date fields 643year-last date fields 643year-only date fields 643YEARWINDOW compiler optiondescription 360effect on sort/merge 229Zz/<strong>OS</strong>compiling under 249zero comparison (See signcondition) 650zero suppressionexample of BLANK WHEN ZEROclause 47PICTURE symbol Z 47zoned decimal data (USAGE DISPLAY)effect of ZWB on comparison toalphanumeric 360example 45<strong>for</strong>mat 49sign representation 55ZWB compiler option 360902 <strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong> <strong>V4.2</strong> <strong>Programming</strong> <strong>Guide</strong>


Readers’ Comments — We’d Like to Hear from You<strong>Enterprise</strong> <strong>COBOL</strong> <strong>for</strong> z/<strong>OS</strong><strong>Programming</strong> <strong>Guide</strong>Version 4 Release 2Publication No. SC23-8529-01We appreciate your comments about this publication. Please comment on specific errors or omissions, accuracy,organization, subject matter, or completeness of this book. The comments you send should pertain to only thein<strong>for</strong>mation in this manual or product and the way in which the in<strong>for</strong>mation is presented.For technical questions and in<strong>for</strong>mation about products and prices, please contact your IBM branch office, yourIBM business partner, or your authorized remarketer.When you send comments to IBM, you grant IBM a nonexclusive right to use or distribute your comments in anyway it believes appropriate without incurring any obligation to you. IBM or any other organizations will only usethe personal in<strong>for</strong>mation that you supply to contact you about the issues that you state on this <strong>for</strong>m.Comments:Thank you <strong>for</strong> your support.Send your comments to the address on the reverse side of this <strong>for</strong>m.If you would like a response from IBM, please fill in the following in<strong>for</strong>mation:NameAddressCompany or OrganizationPhone No.E-mail address


Readers’ Comments — We’d Like to Hear from YouSC23-8529-01SC23-8529-01_________________________________________________________________________________________Fold and Tape Please do not staple Fold and TapeBUSINESS REPLY MAILFIRST-CLASS MAIL PERMIT NO. 40 ARMONK, NEW YORKP<strong>OS</strong>TAGE WILL BE PAID BY ADDRESSEEIBM CorporationReader CommentsDTX/E269555 Bailey AvenueSan Jose, CAU.S.A. 95141-9989NO P<strong>OS</strong>TAGENECESSARYIF MAILED IN THEUNITED STATES_________________________________________________________________________________________Fold and Tape Please do not staple Fold and Tape___________________________________________________________________________________________________Cut or FoldAlong LineCut or FoldAlong Line


Program Number: 5655-S71Printed in USASC23-8529-01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!