Credit to devdocs.io

gnu_cobol

gnu_cobol

GnuCOBOL

1. Introduction

The original principal developers of GnuCOBOL were Keisuke Nishida and Roger While. Since then many others of the GnuCobol community are directly involved in it’s development at any one time.

This document is intended to serve as a full-function reference and user’s guide suitable for both those readers learning COBOL for the first time as usage as a training tool, as well as those already familiar with some dialect of the COBOL language.

A separate manual exists that just contains the details of the GNUCobol implementation which is designed strictly for experienced Cobol programmers taken from this guide. This document (GnuCobol Quick Reference) does NOT contain any training subject matter.

Caution. Although this document is for version 2.2 of the compiler, it also includes a description of the functions of the RWCS (Report Writer module) which is not included in the compiler version 2.2. Please see availability notes on this at 1.3.13.

1.1. Additional Reference Sources

If you like to hold a book in your hands, I strongly recommend "Murach’s Structured COBOL", by Mike Murach, Anne Prince and Raul Menendez (2000) - ISBN 9781890774059. Mike Murach and his various writing partners have been writing outstanding COBOL textbooks for decades, and this text is no exception. It’s an excellent book for those familiar with the concepts of programming in other languages, but unfamiliar with COBOL.

Would you prefer a web-based tutorial? Try the University of Limerick (Ireland) COBOL web site - ‘http://www.csis.ul.ie/cobol/’.

1.2. Introducing COBOL

COBOL, first introduced to the programming public in 1959, was the very first programming language to become standardized (in 1960). This meant that a standard-compliant COBOL program written on computer "A" made by company "B" would be able to be compiled and executed on computer "X" made by company "Y" with very few, if any, changes. This may not seem like such a big deal today, but it was a radical departure from all programming languages that came before it and even many that came after it.

The name COBOL actually says it all — COBOL is an acronym that stands for "(CO)mmon (B)usiness (O)riented (L)anguage". Note the fact that the word "common" comes before all others. The word "business" is a close second. Therein lies the key to Cobol’s success.

1.2.1. Why YOU Should Learn COBOL

  1. They conform to the principles of Object-Oriented Programming (OOP). This is desired for one major reason — it facilitates "code re-usability", thus improving the productivity of programmers by allowing them to re-use previously written (and debugged) code in new applications. For one reason or another, COBOL is perceived as being weak in this regard. It isn’t (especially today), as we’ll see in the next section, but perception is important.
  2. Those languages aren’t limited to mainframe computers, as COBOL is perceived to be. Some, like .NET and Ruby, aren’t even available on mainframes. The "modern" programming languages were designed and intended for use on the full variety of computer platforms, from shirt-pocket computers (i.e. smart phones) up to the most massive of supercomputers.
  3. There are several excellent commercially available COBOL implementations available for non-mainframe systems (Micro Focus COBOL, AccuCOBOL, NetCOBOL and Elastic COBOL, just to name a few), including Windows and UNIX/Linux systems. These aren’t cheap, however.
  4. Universities love the "Modern" languages. In the U.S., 73% of colleges lack even one COBOL course on their curricula. COBOL, it appears, is no longer "cool" enough for students to fill a classroom.

Just because COBOL doesn’t traditionally support objects, classes, and the like doesn’t mean that its "procedural" approach to computing isn’t valuable — after all, it runs 70% of the worlds business transactions, and does so:

  • Using programs that, for the most part, are much more self-documenting than would be the case with any other programming language.
  • Effortlessly providing arithmetic accuracy to 31 digits, with performance approaching that of well-written assembly-language programs. Don’t think this isn’t critically important to banks, investment houses and any business interested in tracking revenues, expenses and profits (duh - like ALL of them).
  • Integrating well with non-COBOL infrastructures such as XML, SOA, MQ, almost any DBMS, Transaction Processing platforms, Queue-Management facilities and other programming languages.
  • By running on almost as many different computing platforms as Java can. You can’t run COBOL programs in your smart phone, but desktops, workstations, midframes/servers, mainframes and supercomputers are all fair game.

Today’s IT managers and business leaders are faced with a challenging dilemma — how do you maintain the enormous COBOL code base that is still running their businesses when academia has all but abandoned the language they need their people to use to keep the wheels rolling? The problem is compounded by the fact that those programmers that are skilled in COBOL are retiring and taking their knowledge with them. In some markets, this appears to be having an inflationary effect on the cost of resources (COBOL programmers) whose supply is becoming smaller and smaller. The pressure to update applications to make use of more up-to-date graphical user interfaces is also perceived as a reason to abandon COBOL in favour of GUI-friendly languages such as Java.

Businesses are addressing the COBOL challenge in different ways:

  1. By undertaking so-called "modernization projects", where existing applications are either rewritten in "modern" languages or replaced outright with purchased packages. Most of these businesses are using such activities as an excuse to abandon "expensive" mainframes in favour of (presumably) less-expensive "open systems" (mid frame/server) solutions.
  2. Many times these businesses are finding the cost of the system/networking engineering, operational management and monitoring and risk management (i.e. disaster recovery) infrastructures necessary to support truly mission-critical applications to be so high that the "less-expensive" solution really isn’t; in these cases the mainframe may remain the best option, thus leaving COBOL in play and businesses seeking another solution for at least part of their application base.
  3. Training their own COBOL programmers. Since colleges, universities and technical schools have lost interest in doing so, many businesses have undertaken the task of "growing their own" new crop of COBOL programmers. Fear of being pigeon-holed into a niche technology is a factor inhibiting many of today’s programmers from willingly volunteering for such training.
  4. By moving the user-interface onto the desktop; such efforts involve running modern-language front-end clients on user desktops (or laptops or smart phones, etc.) with COBOL programs providing server functionality on mainframe or midframe platforms, providing all the database and file "heavy lifting" on the back-end. Solutions like this provide users with the user-interfaces they want/need while still leveraging Cobol’s strengths on (possibly) downsized legacy mainframe or midframe systems.

It’s probably a true that an IT professional can no longer afford to allow COBOL to be the only wrench in their toolbox, but with a massive code base still in production now and for the foreseeable future, adding COBOL to a multi-lingual curriculum vitae (CV) and/or resume (yes — they ARE different) is not a bad thing at all. Knowing COBOL as well as the language du-jour will make you the smartest person in the room when the discussion of migrating the current "legacy" environment to a "modern" implementation comes around.

You’ll find COBOL an easy language to learn and a FAR EASIER language to master than many of the "modern" languages.

The whole reason you’re reading this is that you’ve discovered GnuCOBOL — another implementation of COBOL in addition to those mentioned earlier. The distinguishing characteristic of GnuCOBOL versus those others is that GnuCOBOL is FREE open-source and therefore FREE to obtain and use. It is community-enhanced and community-supported. Later in this document (see So What is GnuCOBOL?), you’ll begin to learn more about this COBOL implementation’s capabilities.

1.2.2. Programmer Productivity

The amount of programming necessary to accomplish a given task — including rework needed by any errors found during testing (testing is sometimes jokingly defined as: "that time during which an application is actually in production, allowing users to discover the problems") is the measure of programmer productivity. Anything that reduces that effort will therefore reduce the time spent in such activities therefore reducing the expense of same. When the expense of programming is reduced, programmer productivity is increased.

Sometimes the quest for improved programmer productivity (and therefore reduced programming expense) has taken the form of introducing new features in programming languages, or even new languages altogether. Sometimes it has resulted in new ways of using the existing languages.

While many technological and procedural developments have made evolutionary improvements to programmer productivity, each of the following three events has been responsible for revolutionary improvements:

  • The development of so-called "higher-level" programming languages that enable a programmer to specify in a single statement of the language an action that would have required many more separate statements in a prior programming language. The standardization of such languages, making them usable on a wide variety of computers and operating systems, was a key aspect of this development. COBOL was a pioneering development in this area, being a direct descendant of the very first higher-level language (FLOW-MATIC, developed by US Naval Lieutenant Grace Hopper) and the first to become standardized.
  • The establishment of programming techniques that make programs easier to read and therefore easier to understand. Not only do such techniques reduce the amount of rework necessary simply to make a program work as designed, but they also reduce the amount of time a programmer needs to study an existing program in order how to best adapt it to changing business requirements. The foremost development in this area was structured programming. Introduced in the late 1970’s, this approach to programming spawned new programming languages (PASCAL, ALGOL, PL/1 and so forth) designed around it. With the ANSI 85 standard, COBOL embraced the principles espoused by structured programming mavens as well as any of the languages designed strictly around it.
  • The establishment of programming techniques AND the introduction of programming language capabilities to facilitate the re-usability of program code. Anything that supports code re-usability can have a profound impact to the amount of time it takes to develop new applications or to make significant changes to existing ones. In recent years, object-oriented programming (OOP) has been the industry "poster child" for code re-usability. By enabling program logic and the data structures that logic manipulates to be encapsulated into easily stored and retrieved (and therefore "reusable") modules called classes, the object-oriented languages such as Java, C++ and C# have become the favourites of academia. Since students are being trained in these languages and only these, by and large, it’s no surprise that — today — object-oriented programming languages are the darlings of the industry.

    The reality is, however, that good programmers have been practising code re-usability for more than a half-century. Up until recently, COBOL programmers have had some of the best code re-usability tools available — they’ve been doing it with copybooks and subprograms rather than classes, methods and attributes but the net results have been similar. With the COBOL2002 standard and proposed COBOL 20XX standard, the COBOL programming language has become just as "object-oriented" as the "modern" languages, while preserving the ability to support, modify, compile and execute "legacy" COBOL programs as well.

While GnuCOBOL supports few of the OOP programming constructs defined by the COBOL2002 and COBOL20xx standards, it supports every aspect of the ANSI 85 standard and therefore fully meets the needs of points #1 and #2, above. With it’s supported feature set (see So What is GnuCOBOL?), it provides significant programmer productivity capabilities.

1.3. So What is GnuCOBOL?

The MinGW approach is a personal favourite with the author of this manual because it creates a GnuCOBOL compiler and runtime library that require only a single MinGW DLL to be available for the GnuCOBOL compiler, runtime library and user programs. That DLL is freely distributable under the terms of the GNU General Public License. A MinGW build of GnuCOBOL fits easily on and runs from a 128MB flash drive with no need to install any software onto the Windows computer that will be using it. Some functionality of the language, dealing with the sharing of files between concurrently executing GnuCOBOL programs and record locking on certain types of files, is sacrificed however as the underlying operating system routines needed to implement them aren’t available to Windows and aren’t provided by MinGW. The current version for MinGW is available at the download link along with various other platforms at the GnuCobol download website (https://sourceforge.net/projects/open-cobol/files/gnu-cobol/2.0/).

GnuCOBOL has also been built as a truly native Windows application utilizing Microsoft’s freely-downloadable Visual Studio Express package to provide the C compiler and linker/loader. This approach does not lend itself well to a "portable" distribution.

The GnuCOBOL compiler generates C code from your COBOL programs; that C code is then automatically compiled and linked using your system’s C compiler (typically, but not limited to, "gcc").

GnuCOBOL fully supports much of the ANSI 85 standard for COBOL (the only major exclusion is the Communications Module) and also supports some of the components of the COBOL2002 standard, such as theSCREEN SECTION(see SCREEN SECTION), table-basedSORT(see Table SORT) and user-defined functions.

1.3.1. Language Reserved Words

The GnuCOBOL language specification defines over 900 ’Reserved Words

Programmers may use a reserved word as part of a word they are creating themselves, but may not create their own word as an exact duplicate (without regard to case) of a COBOL reserved word. Note that a reserved word includes all classes, such as intrinsic functions, mnemonics names, system routines and reserved words.

See Appendix B - Reserved Word List, for a complete list of GnuCOBOL reserved words for the current release.

1.3.2. User-Defined Words

User-defined words may be composed from the characters "A" through "Z" (upper- and/or lower-case), "0" through "9", dash ("-")

Other programming language provide the programmer with a similar capability of creating their own words (names) for parts of a program; COBOL is somewhat unusual when compared to other languages in that user-defined words may start with a digit.

With the exception of logic procedure names, which may consist entirely of nothing but digits, user-defined words must contain at least one letter.

1.3.3. Case Insensitivity

The only time the case used does matter is within quoted character strings, where character values will be exactly as coded.

By convention throughout this document, COBOL reserved words will be shown entirely in UPPER-CASE while those words that were created by a programmer will be represented by tokens in mixed or lower case.

This isn’t a bad practice to use in actual programs, as it leads to programs where it is much easier to distinguish reserved words from user-defined ones!

1.3.4. Readability of Programs

Here are two different "Hello World" applications — one written in Java and the second in GnuCOBOL. First, the Java version:

    Class HelloWorld {
        public static void main(String[] args) {
            System.out.println("Hello World!");
        }
    }

And here is the same program, written in GnuCOBOL:

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HelloWorld.
    PROCEDURE DIVISION.
        DISPLAY "Hello World!".

Both of the above programs could have been written on a single line, if desired, and both languages allow a programmer to use (or not use) indentation as they see fit to improve program readability. Sounds like a tie so far.

Let’s look at how much more "wordy" COBOL is than Java. Count the characters in the two programs. The Java program has 95 (not counting carriage returns and any indentation). The COBOL program has 89 (again, not counting carriage returns and indentation)! Technically, it could have been only 65 because theIDENTIFICATION DIVISION.header is actually optional. Clearly, "Hello World" doesn’t look any more concise in Java than it does in COBOL.

Let’s look at a different problem. Surely a program that asks a user to input a positive integer, generates the sum of all positive integers from 1 to that number and then prints the result will be MUCH shorter and MUCH easier to understand when coded in Java than in COBOL, right?

You can be the judge. First, the Java version:

    import java.util.Scanner;
    public class sumofintegers {
        public static void main(String[] arg) {
            System.out.println("Enter a positive integer");
            Scanner scan=new Scanner(System.in);
            int n=scan.nextInt();
            int sum=0;
            for (int i=1;i<=n;i++) {
                sum+=i;
            }
            System.out.println("The sum is "+sum);
        }
    }

And now for the COBOL version:

    IDENTIFICATION DIVISION.
    PROGRAM-ID. SumOfIntegers.
    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01 n   BINARY-LONG.
    01 i   BINARY-LONG.
    01 sum BINARY-LONG VALUE 0.
    PROCEDURE DIVISION.
    DISPLAY "Enter a positive integer"
    ACCEPT n
    PERFORM VARYING i FROM 1 BY 1 UNTIL i > n
        ADD i TO sum
    END-PERFORM
    DISPLAY "The sum is " sum.

My familiarity with COBOL may be prejudicing my opinion, but it doesn’t appear to me that the Java code is any simpler than the COBOL code. In case you’re interested in character counts, the Java code comes in at 278 (not counting indentation characters). The COBOL code is 298 (274 without theIDENTIFICATION DIVISION.header).

Despite what you’ve seen here, the more complex the programming logic being implemented, the more concise the Java code will appear to be, even compared to 2002-standard COBOL. That conciseness comes with a price though — program code readability. Java (or C or C++ or C#) programs are generally intelligible only to trained programmers. COBOL programs can, however, be quite understandable by non-programmers. This is actually a side-effect of the "wordiness" of the language, where COBOL statements use natural English words to describe their actions. This inherent readability has come in handy many times throughout my career when I’ve had to learn obscure business (or legal) processes by reading the COBOL program code that supports them.

The "modern" languages, like Java, also have their own "boilerplate" infrastructure overhead that must be coded in order to write the logic that is necessary in the program. Take for example thepublic static void main(String[] arg)andimport java.util.Scanner;statements. The critics tend to forget about this when they criticize COBOL for it’s structural "overhead".

When it first was developed, Cobol’s easily-readable syntax made it profoundly different from anything that had been seen before. For the first time, it was possible to specify logic in a manner that was — at least to some extent — comprehensible even to non-programmers. Take for example, the following code written in FORTRAN — a language developed only a year before COBOL:

    EXT = PRICE * IQTY
    INVTOT = INVTOT + EXT

With its original limitation on the length of variable names (one- to six-character names comprised of a letter followed by up to five letters and/or digits), it’s implicit rule that variable were automatically created as real (floating-point) unless their name started with a letter in the range I-N, and its use of algebraic notation to express actions being taken, FORTRAN wasn’t a particularly readable language, even for programmers. Compare this with the equivalent COBOL code:

    MULTIPLY price BY quantity GIVING extended-amount
    ADD extended-amount TO invoice-total

Clearly, even a non-programmer could at least conceptually understand what was going on! Over time, languages like FORTRAN evolved more robust variable names, and COBOL introduced a more formula-based syntactical capability for arithmetic operations, but FORTRAN was never as readable as COBOL.

Because of its inherent readability, I would MUCH rather be handed an assignment to make significant changes to a COBOL program about which I know nothing than to be asked to do the same with a C, C++, C# or Java program.

Those that argue that it is too boring / wasteful / time-consuming / insulting (pick one) to have to code a COBOL program "from scratch" are clearly ignorant of the following facts:

  • Many systems have program-development tools available to ease the task of coding programs; those tools that concentrate on COBOL are capable of providing templates for much of the "overhead" verbiage of any program…
  • Good programmers have — for decades — maintained their own skeleton "template" programs for a variety of program types; simply load a template into a text editor and you’ve got a good start to the program…
  • Legend has it that there’s actually only been ONE program ever written in COBOL, and all programs ever "written" thereafter were simply derivatives of that one. Although this is clearly intended as a (probably) bad joke, it is nevertheless close to the very simple truth that many programmers"reuse" existing COBOL programs when creating new ones. There’s certainly nothing preventing this from happening with programs written in other languages, but it does seem to happen more in COBOL shops. It’s ironic that "code re-usability" is one of the arguments used to justify the existence of the "modern" languages.

1.3.5. Divisions Organize Programs

Each division may consist of a variety of sections and each section consists of one or more paragraphs. A paragraph consists of sentences, each of which consists of one or more statements.

This hierarchical structure of program components standardizes the composition of all COBOL programs. Much of this manual describes the various divisions, sections, paragraphs and statements that may comprise any COBOL program.

1.3.6. Copybooks

Today’s current programming languages have a statement (usually, this statement is named "import", "include" or "#include") that performs this same function. What makes the COBOL copybook feature different than the "include" facility in newer languages, however, is the fact that theCOPYstatement can edit the imported source code as it is being copied. This capability makes copybook libraries extremely valuable to making code reusable.

1.3.7. Structured Data

COBOL introduced the concept of structured data. The principle of structured data in COBOL is based on the idea of being able to group related and contiguously-allocated data items together into a single aggregate data item, called a ’Group Item

A data item that isn’t itself formed from other data items is referred to in COBOL as an ’Elementary Item

1.3.8. Files

ORGANIZATION LINE SEQUENTIAL

These are files with the simplest of all internal structures. Their contents are structured simply as a series of identically- or differently-sized data records, each terminated by a special end-of-record delimiter character. An ASCII line-feed character (hexadecimal 0A) is the end-of-record delimiter character used by any UNIX or pseudo-UNIX (MinGW, Cygwin, OSX) GnuCOBOL build. A truly native Windows build would use a carriage-return, line-feed (hexadecimal 0D0A) sequence.

Records must be read from or written to these files in a purely sequential manner. The only way to read (or write) record number 100 would be to have read (or written) records number 1 through 99 first.

When the file is written to by a GnuCOBOL program, the delimiter sequence will be automatically appended to each data record as it is written to the file. AWRITE(see WRITE) to this type of file will be done as if aBEFORE ADVANCING 1 LINEclause were specified on theWRITE if noADVANCINGclause is coded.

When the file is read, the GnuCOBOL runtime system will strip the trailing delimiter sequence from each record. The data will be padded (on the right) with spaces if the data just read is shorter than the area described for data records in the program. If the data is too long, it will be truncated and the excess will be lost.

These files should not be defined to contain any exact binary data fields because the contents of those fields could inadvertently have the end-of-record sequence as part of their values — this would confuse the runtime system when reading the file, and it would interpret that value as an actual end-of-record sequence.

LINE ADVANCING

These are files with an internal structure similar to that of a line sequential file. These files are defined (without an explicitORGANIZATIONspecification) using theLINE ADVANCINGclause on theirSELECTstatement (see SELECT).

When this kind of file is written to by a GnuCOBOL program, an end-of-record delimiter sequence will be automatically added to each data record as it is written to the file. AWRITEto this type of file will be done as if anAFTER ADVANCING 1 LINEclause were specified on theWRITE if noADVANCINGclause is coded.

Like line sequential files, these files should not be defined to contain any exact binary data fields because the contents of those fields could inadvertently have the end-of-record sequence as part of their values — this would confuse the runtime system when reading the file, and it would interpret that value as an actual end-of-record sequence.

ORGANIZATION SEQUENTIAL

These files also have a simple internal structure. Their contents are structured simply as an arbitrarily-long sequence of data characters. This sequence of characters will be treated as a series of fixed-length records simply by logically splitting the sequence of characters up into fixed-length segments, each as long as the maximum record size defined in the program. There are no special end-of-record delimiter characters in the file and when the file is written to by a GnuCOBOL program, no delimiter sequence is appended to the data.

Records in this type of file are all the same physical length, except possibly for the very last record in the file, which may be shorter than the others. If variable-length logical records are defined to the program, the space occupied by each physical record in the file will occupy the space described by the longest record description in the program.

So, if a file contains 1275 characters of data, and a program defines the structure of that file as containing 100-character records, then the file contents will consist of twelve (12) 100-character records with a final record containing only 75 characters.

It would appear that it should be possible to locate and process any record in the file directly simply by calculating its starting character position based upon the program-defined record size. Even so, however, records must be still be read or written to these files in a purely sequential manner. The only way to read (or write) record number 100 would be to have read (or written) records number 1 through 99 first.

When the file is read, the data is transferred into the program exactly as it exists in the file. In the event that a short record is read as the very last record, that record will be padded (to the right) with spaces.

Care must be taken that programs reading such a file describe records whose length is exactly the same as that used by the program that created the file. For example, the following shows the contents of aSEQUENTIALfile created by a program that wrote five 6-character records to it. The "A", "B", … values reflect the records that were written to the file:

AAAAAABBBBBBCCCCCCDDDDDDEEEEEE

Now, assume that another program reads this file, but describes 10-character records rather than 6. Here are the records that program will read:

AAAAAABBBB
BBCCCCCCDD
DDDDEEEEEE

There may be times where this is exactly what you were looking for. More often than not, however, this is not desirable behaviour. Suggestion: use a copybook to describe the record layouts of any file; this guarantees that multiple programs accessing that file will "see" the same record sizes and layouts by coding aCOPYstatement (see COPY) to import the record layout(s) rather than hand-coding them.

These files can contain exact binary data fields. This is possible because — since there is no character sequence that constitutes an end-of-record delimiter — the contents of record fields are irrelevant to the reading process.

ORGANIZATION RELATIVE

The contents of these files consist of a series of fixed-length data records prefixed with a four-byte record header. The record header contains the length of the data, in bytes. The byte-count does not include the four-byte record header.

Records in this type of file are all the same physical length. If variable-length logical records are defined to the program, the space occupied by each physical record in the file will occupy the maximum possible space, and the logical record length field will contain the number of bytes of data in the record that are actually in use.

This file organization was defined to accommodate either sequential or random processing. With aRELATIVEfile, it is possible to read or write record 100 directly, without having to have first read or written records 1-99. The GnuCOBOL runtime system uses the program-defined maximum record size to calculate a relative byte position in the file where the record header and data begin, and then transfers the necessary data to or from the program.

When the file is written by a GnuCOBOL program, no delimiter sequence is appended to the data, but a record-length field is added to the beginning of each physical record.

When the file is read, the data is transferred into the program exactly as it exists in the file.

Care must be taken that programs reading such a file describe records whose length is exactly the same as that used by the programs that created the file. It won’t end well if the GnuCOBOL runtime library interprets a four-byte ASCII character string as a record length when it transfers data from the file into the program!

Suggestion: use a copybook to describe the record layouts of any file; this guarantees that multiple programs accessing that file will "see" the same record sizes and layouts by coding aCOPYstatement (see COPY) to import the record layout(s) rather than hand-coding them.

These files can contain exact binary data fields. The contents of record fields are irrelevant to the reading process as there is no end-of-record delimiter.

ORGANIZATION INDEXED

This is the most advanced file structure available to GnuCOBOL programs. It’s not possible to describe the physical structure of such files because that structure will vary depending upon which advanced file-management facility was included into the GnuCOBOL build you will be using (Berkeley Database [BDB], VBISAM, etc.). We will — instead — discuss the logical structure of the file.

There will be multiple structures stored for anINDEXEDfile. The first will be a data component, which may be thought of as being similar to the internal structure of a relative file. Data records may not, however, be directly accessed by their record number as would be the case with a relative file, nor may they be processed sequentially by their physical sequence in the file.

The remaining structures will be one or more index components. An index component is a data structure that (somehow) enables the contents of a field, called a primary key, within each data record (a customer number, an employee number, a product code, a name, etc.) to be converted to a record number so that the data record for any given primary key value can be directly read, written and/or deleted. Additionally, the index data structure is defined in such a manner as to allow the file to be processed sequentially, record-by-record, in ascending sequence of the primary key field values. Whether this index structure exists as a binary-searchable tree structure (b-tree), an elaborate hash structure or something else is pretty much irrelevant to the programmer — the behaviour of the structure will be as it was just described. The actual mechanism used will depend upon the advanced file-management package was included into your GnuCOBOL implementation when it was built.

The runtime system will not allow two records to be written to an indexed file with the same primary key value.

The capability exists for an additional field to be defined as what is known as an alternate key. Alternate key fields behave just like primary keys, allowing both direct and sequential access to record data based upon the alternate key field values, with one exception. That exception is the fact that alternate keys may be allowed to have duplicate values, depending upon how the alternate key field is described to the GnuCOBOL compiler.

There may be any number of alternate keys, but each key field comes with a disk space penalty as well as an execution time penalty. As the number of alternate key fields increases, it will take longer and longer to write and/or modify records in the file.

These files can contain exact binary data fields. The contents of record fields are irrelevant to the reading process as there is no end-of-record delimiter.

All files are initially described to a GnuCOBOL program using aSELECTstatement (see SELECT). In addition to defining a name by which the file will be referenced within the program, theSELECTstatement will specify the name and path by which the file will be known to the operating system along with its organization, locking and sharing attributes.

A file description in theFILE SECTION(see FILE SECTION) will define the structure of records within the file, including whether or not variable-length records are possible and — if so — what the minimum and maximum length might be. In addition, the file description entry can specify file I/O block sizes.

1.3.9. Table Handling

The first can search a table sequentially, stopping only when either a table entry matching one of any number of search conditions is found, or when all table entries have been checked against the search criteria and none matched any of those criteria.

The second can perform an extremely fast search against a table sorted by and searched against a key field contained in each table entry. The algorithm used for such a search is a binary search (also known as a half-interval search). This algorithm ensures that only a small number of entries in the table need to be checked in order to find a desired entry or to determine that the desired entry doesn’t exist in the table. The larger the table, the more effective this search becomes. For example, a binary search of a table containing 32,768 entries will be able to locate a particular entry or determine the entry doesn’t exist by looking at no more than fifteen (15) entries! The algorithm is explained in detail in the documentation of theSEARCH ALLstatement (see SEARCH ALL).

Finally, COBOL has the ability to perform in-place sorts of the data that is found in a table.

1.3.10. Sorting and Merging Data

A companion statement —MERGE(see MERGE) — can combine the contents of multiple files together, provided those files are all pre-sorted in a similar manner according to the same key structure. The resulting output will consist of the contents of all of the input files, merged together and sequenced according to the common key structure(s). The output generated by aMERGEstatement may be written automatically to one or more output files or may be processed internally by the program.

A special form of theSORTstatement also exists just to sort the data that resides in a table. This is particularly useful if you wish to useSEARCH ALLagainst the table.

1.3.11. String Manipulation Features

COBOL is no exception, although it does include some very powerful string manipulation capabilities; GnuCOBOL actually has even more string-manipulation capabilities than many other COBOL implementations. The following summarizes GnuCOBOL’s string-processing capabilities:

Concatenate two or more strings:

Conversion of a numeric time or date to a formatted character string:

Convert a binary value to its corresponding character in the program’s character set:

  • CHARintrinsic function (see CHAR). Add 1 to argument before invoking the function; the description of theCHARintrinsic function presents a technique utilizing theMOVEstatement that will accomplish the same thing without the need of adding 1 to the numeric argument value first.

Convert a character string to lower-case:

  • LOWER-CASEintrinsic function (see LOWER-CASE).
  • C$TOLOWERbuilt-in system subroutine (see C$TOLOWER).
  • CBL_TOLOWERbuilt-in system subroutine (see CBL_TOLOWER).

Convert a character string to upper-case:

  • UPPER-CASEintrinsic function (see UPPER-CASE).
  • C$TOUPPERbuilt-in system subroutine (see C$TOUPPER).
  • CBL_TOUPPERbuilt-in system subroutine (see CBL_TOUPPER).

Convert a character string to only printable characters:

  • C$PRINTABLEbuilt-in system subroutine (see C$PRINTABLE).

Convert a character to its numeric value in the program’s character set:

  • ORDintrinsic function (see ORD). Subtract 1 from the result; the description of theORDintrinsic function presents a technique utilizing theMOVEstatement that will accomplish the same thing without the need of adding 1 to the numeric argument value first.

Count occurrences of sub strings in a larger string:

  • INSPECTstatement (see INSPECT) with theTALLYINGclause.

Decode a formatted numeric string back to a numeric value:

  • NUMVALintrinsic function (see NUMVAL).
  • NUMVAL-Cintrinsic function (see NUMVAL-C).

Determine the length of a string or data-item capable of storing strings:

  • LENGTHintrinsic function (see LENGTH).
  • BYTE-LENGTHintrinsic function (see BYTE-LENGTH).

Extract a sub string from a string based on its starting character position and length:

Format a numeric item for output, including thousands-separators ("," in the USA), currency symbols ("$" in the USA), decimal points, credit/Debit Symbols, Leading Or Trailing Sign Characters:

  • MOVEstatement (see MOVE) with picture-symbol editing applied to the receiving field:

Justification (left, right or centred) of a string field:

  • C$JUSTIFYbuilt-in system subroutine (see C$JUSTIFY).

Monoalphabetic substitution of one or more characters in a string with different characters:

Parse a string, breaking it up into sub strings based upon one or more delimiting character sequences1:

Removal of leading or trailing spaces from a string:

  • TRIMintrinsic function (see TRIM).

Substitution of a single sub string with another of the same length, based upon the sub strings starting character position and length:

Substitution of one or more sub strings in a string with replacement sub strings of the same length, regardless of where they occur:

Substitution of one or more sub strings in a string with replacement sub strings of a potentially different length, regardless of where they occur:

1.3.12. Screen Formatting Features

These features allow fields to be displayed at specific row/column positions, various colors and video attributes to be assigned to screen fields and the pressing of specific function keys (F1, F2, …) to be detectable. All of this takes place through the auspices of theSCREEN SECTION(see SCREEN SECTION) and special formats of theACCEPTstatement (see ACCEPT) and theDISPLAYstatement (see DISPLAY).

The COBOL2002 standard, and therefore GnuCOBOL, only covers textual user interface (TUI) screens (those comprised of ASCII characters presented using a variety of visual attributes) and not the more-advanced graphical user interface (GUI) screen design and processing capabilities built into most modern operating systems. There are subroutine-based packages available that can do full GUI presentation — most of which may be called by GnuCOBOL programs, with a moderate research time investment (Tcl/Tk, for example) — but none are currently included with GnuCOBOL.

1.3.12.1. A Sample Screen

A Sample Screen Produced by a GnuCOBOL Program:

================================================================================
 GCic (2014/01/02 11:24) GnuCOBOL 2.1 23NOV2013 Interactive Compilation
+------------------------------------------------------------------------------+
: Filename: GCic.cbl                                                           :
: Folder:   E:\Programs\GCic\2013-11-23                                        :
+------------------------------------------------------------------------------+
 Set/Clr Switches Via F1-F9; Set Config Via F12; ENTER Key Compiles; ESC Quits
+------------------------------------------------------------------------------+
: F1  Assume WITH DEBUGGING MODE  F6 >"FUNCTION" Is Optional      : Current    :
: F2  Procedure+Statement Trace   F7 >Enable All Warnings         : Config:    :
: F3  Make a Library (DLL)        F8  Source Is Free-Format       : DEFAULT    :
: F4  Execute If Compilation OK   F9 >No COMP/BINARY Truncation   :            :
: F5  Listing Off                                                 :            :
+------------------------------------------------------------------------------+
 Extra "cobc" Switches, If Any ("-save-temps=xxx" Prevents Listings):
+------------------------------------------------------------------------------+
: ____________________________________________________________________________ :
: ____________________________________________________________________________ :
+------------------------------------------------------------------------------+
 Program Execution Arguments, If Any:
+------------------------------------------------------------------------------+
: ____________________________________________________________________________ :
: ____________________________________________________________________________ :
+------------------------------------------------------------------------------+
 GCic for Windows/MinGW Copyright (C) 2009-2014, Gary L. Cutler, GPL
================================================================================

The above screen was produced by the GnuCOBOL Interactive Compiler, or GCic. See GCic in GnuCOBOL Sample Programs, for the source and cross-reference listing of this program. PDF versions of this document will include an actual graphical image of this sample screen.

Screens are defined in the screen section of the data division. Once defined, screens are used at run-time via theACCEPTandDISPLAYstatements.

1.3.12.2. Color Palette and Video Attributes

GnuCOBOL supports the following visual attribute specifications in theSCREEN SECTION(see SCREEN SECTION):

Color

Eight (8) different colors may be specified for both the background (screen) and foreground (text) color of any row/column position on the screen. Colors are specified by number, although a copybook supplied with all GnuCOBOL distributions ("screenio.cpy") defines COB-COLOR-xxxxxx names for the various colors so they may be specified as a more meaningful name rather than a number. The eight colors, by number, with the constant names defined in screenio.cpy, are as follows:

  1. Black: COB-COLOR-BLACK
  2. Blue: COB-COLOR-BLUE
  3. Green: COB-COLOR-GREEN
  4. Cyan (Turquoise): COB-COLOR-CYAN
  5. Red: COB-COLOR-RED
  6. Magenta: COB-COLOR-MAGENTA
  7. Yellow: COB-COLOR-YELLOW
  8. White: COB-COLOR-WHITE
Text Brightness

There are three possible brightness levels supported for text — lowlight (dim), normal and highlight (bright). Not all GnuCOBOL implementations will support all three (some treat lowlight the same as normal). The deciding factor as to whether two or three levels are supported lies with the version of the "curses" package that is being used. This is a utility screen-IO package that is included into the GnuCOBOL run-time library when the GnuCOBOL software is built.

As a general rule of thumb, Windows implementations support two levels while Unix ones support all three.

Blinking

This too is a video feature that is dependent upon the "curses" package built into your version of GnuCOBOL. If blinking is enabled in that package, text displayed in fields defined in the screen section as being blinking will endlessly cycle between the brightest possible setting (highlight) and an "invisible" setting where the text color matches that of the field background color. A Windows build, which generally uses the "pcurses" package, will uses a brighter-than-normal background color to signify "blinking".

Reverse Video

This video attribute simply swaps the foreground and background colors and display options.

Field Outlining

It is possible, if supported by the "curses" package being used, to draw borders on the top, left and/or bottom edges of a field.

Secure Input

If desired, screen fields used as input fields may defined as "secure" fields, where each input character (regardless of what was actually typed) will appear as an asterisk (*) character. The actual character whose key was pressed will still be stored into the field in the program, however. This is very useful for password or account number fields.

Prompt Character

Input fields may have any character used as a fill character. These fill characters provide a visual indication of the size of the input field, and will automatically be transformed into spaces when the input field is processed by the program. If no such character is defined for an input field, an underscore ("_") will be assumed.

1.3.13. Report Writer Features

  1. Controlling the pagination of reports, including:
    1. The automatic production of a one-time notice on the first page of the report (report heading).
    2. The production of zero or more header lines at the top of every page of the report (page heading).
    3. The production of zero or more footer lines at the bottom of every page of the report (page footing).
    4. The automatic numbering of printed pages.
    5. The formatting of those report lines that make up the main body of the report (detail).
    6. Full awareness of where the "pen" is about to "write" on the current page, automatically forcing an eject to a new page, along with the automatic generation of a page footer to close the old page and/or a page header to begin the new one.
    7. The production of a one-time notice at the end of the last page of a report (report footing).
  2. Performing special reporting actions based upon the fact that the data being used to generate the report has been sorted according to one or more key fields:
    1. Automatically suppressing the presentation of one or more fields of data from the detail group when the value(s) of the field(s) duplicate those of the previously generated detail group. Fields such as these are referred to as group-indicate fields.
    2. Automatically causing suppressed detail group-indicate fields to re-appear should a detail group be printed on a new page.
    3. Recognizing when control fields on the report — fields tied to those that were used asSORTstatement (see SORT) keys — have changed. This is known as a control break. The RWCS can automatically perform the following reporting actions when a control break occurs:
      • Producing a footer, known as a control footing after the detail lines that shared the same old value for the control field.
      • Producing a header, known as a control heading before the detail lines that share the same new value for the control field.
  3. Perform data summarise, as follows:
    1. Automatically generating subtotals in control and/or report footings, summarizing values of any fields in the detail group.
    2. Automatically generating crossfoot totals in detail groups. These would be sums of two or more values presented in the detail group.

TheREPORT SECTION(see REPORT SECTION) documentation explores the description of reports and thePROCEDURE DIVISION(see PROCEDURE DIVISION) chapter documents the various language statements that actually produce reports. Before reading these, you might find it helpful to read Report Writer Usage Notes, which is dedicated to putting the pieces together for you.

1.3.14. Data Initialization

  1. When a program or subprogram is first executed, much of the data in it’s data division will be initialized as follows:
    • Alphanumeric and alphabetic (i.e. text) data items will be initialized toSPACES
    • Numeric data items will be initialized to a value ofZERO
    • Data items with an explicitVALUE(see VALUE) clause in their definition will be initialized to that specific value.

    The various sections of the data division each have their own rules as to when the actions described above will occur — consult the documentation on those sections for additional information.

    These default initialization rules can vary quite substantially from one COBOL implementation to another. For example, it is quite common for data division storage to be initialized to all binary zeros except for those data items whereVALUEclauses are present. Take care when working with applications originally developed for another COBOL implementation to ensure that GnuCOBOL’s default initialization rules won’t prove disruptive.

  2. A programmer may use theINITIALIZEstatement (see INITIALIZE) to initialise any group or elementary data item at any time. This statement provides far more initialization options than just the simple rules stated above.
  3. When theALLOCATEstatement (see ALLOCATE) statement is used to allocate a data item or to simply allocate an area of storage of a size specified on theALLOCATE that allocation may occur with or without initialization, as per the programmer’s needs.

1.3.15. Syntax Diagram Conventions

MANDATORY-RESERVED-WORD
~~~~~~~~~~~~~~~~~~~~~~~

Reserved words of the COBOL language will appear in UPPER-CASE. When they appear underlined, as this one is, they are required reserved words.

OPTIONAL-RESERVED-WORD

When reserved words appear without underlining, as this one is, they are optional; such reserved words are available in the language syntax merely to improve readability — their presence or absence has no effect upon the program.

ABBREVIATION
~~~~

When only a portion of a reserved word is underlined, it indicates that the word may either be coded in its full form or may be abbreviated to the portion that is underlined.

substitutable-items

Generic terms representing user-defined substitutable items will be shown entirely in lower-case in syntax diagrams. When such items are referenced in text, they will appear as <substitutable-items>.

Complex-Syntax-Clause

Items appearing in Mixed Case within a syntax diagram represent complex clauses of other syntax elements that may appear in that position. Some COBOL syntax gets quite complicated, and using a convention such as this significantly reduces the complexity of a syntax diagram. When such items are referenced in text, they will appear as <<Complex-Syntax-Clause>>.

[ ]

Square bracket meta characters on syntax diagrams document language syntax that is optional. The [] characters themselves should not be coded. If a syntax diagram contains "a [b] c", the "a" and "c" syntax elements are mandatory but the "b" element is optional.

|

Vertical bar meta characters on syntax diagrams document simple choices. The | character itself should not be coded. If a syntax diagram contains "a|b|c", exactly one of the items "a", "b" or "c" must be selected.

{ xxxxxx }
{ yyyyyy }
{ zzzzzz }

A vertical list of items, bounded by multiple brace characters, is another way of signifying a choice between a series of items where exactly one item must be selected. This form is used to show choices when one or more of the selections is more complex than just a single word, or when there are too many choices to present horizontally with "|" meta characters.

| xxxxxx |
| yyyyyy |
| zzzzzz |

A vertical list of items, bounded by multiple vertical bar characters, signifies a choice between a series of items where one or more of the choices could be selected.

...

The ... meta character sequence signifies that the syntax element immediately preceding it may be repeated. The ... sequence itself should not be coded. If a syntax diagram containsa b... c syntax element "a" must be followed by at least one "b" element (possibly more) and the entire sequence must be terminated by a "c" syntax element.

{ }

The braces ({}) meta characters may be used to group a sequence of syntax elements together so that they may be treated as a single entity. The {} characters themselves should not be coded. These are typically used in combination with the "|" or "..." meta characters.

$*^()-+=:"'<,>./

Any of these characters appearing within a syntax diagram are to be interpreted literally, and are characters that must be coded — where allowed — in the statement whose format is being described. Note that a "." character is a literal character that must be coded on a statement whereas a "..." symbol is the meta character sequence described above.

1.3.16. Format of Program Source Lines

As of the COBOL2002 standard, a second mode now exists for COBOL source code statements — in this mode of operation, COBOL statements may each be up to 255 characters long, with no specific requirements as to what should appear in which columns.

Of course, in keeping with the long-standing COBOL tradition of maintaining backwards compatibility with older standards, programmers (and, of course, compliant COBOL compilers) are capable of working in either mode. It is even possible to switch back and forth in the same program. The terms ’Fixed Format Mode

The GnuCOBOL compiler (cobc) supports both of these source line format modes, defaulting to Fixed Format Mode lacking any other information.

The compiler can be instructed to operate in either mode in any of the following four ways:

  1. Using a compiler option switch — use the-fixedswitch
  2. You may use theSOURCEFORMAT AS FIXEDandSOURCEFORMAT AS FREEclauses of the>>SETCDF directive (see >>SET) within your source code to switch to Fixed or Free Format Mode, respectively.
  3. You may use the>>FORMAT IS FIXEDandFORMAT IS FREEclauses of the>>DEFINECDF directive (see >>DEFINE) within your source code to switch to Fixed or Free Format Mode, respectively.
  4. You may use the>>SOURCECDF directive (see >>SOURCE) to switch to Free Format Mode >>SOURCE FORMAT IS FREE or Fixed Format Mode >>SOURCE FORMAT IS FIXED

Using methods 2-4 above, you may switch back and forth between the two formats at will.

The last three options above are all equivalent; all three are supported by GnuCOBOL so that source code compatibility may be maintained with a wide variety of other COBOL implementations. With all three, if the compiler is currently in Fixed Format Mode, the>>must begin in column 8 or beyond, provided no part of the directive extends past column 72. If the compiler is currently in Free Format Mode, the>>may appear in any column, provided no part of the directive extends past column 255.

Depending upon which source format mode the compiler is in, you will need to follow various rules for the format mode currently in effect. These rules are presented in the upcoming paragraphs.

The following discussion presents the various components of every GnuCOBOL source line record when the compiler is operating in Fixed Format Mode. Remember that this is the default mode for the GnuCOBOL compiler.

1-6

Historically, back in the days when punched-cards were used to submit COBOL program source to a COBOL compiler, this part of a COBOL statement was reserved for a six-digit sequence number. While the contents of this area are ignored by COBOL compilers, it existed so that a program actually punched on 80-character cards could — if the card deck were dropped on the floor — be run through a card sorter machine and restored to it’s proper sequence. Of course, this isn’t necessary today; if truth be told, it hasn’t been necessary for a long time.

See Marking Changes in Programs, for discussion of a valuable use to which the sequence number area may be put today.

7

Column 7 serves as an indicator in which one of five possible values will appear — space,D(ord,-(dash),/or* The meanings of these characters are as follows:

space

No special meaning — this is the normal character that will appear in this area.

D/d

The line contains a valid GnuCOBOL statement that is normally treated as a comment unless the program is being compiled in debugging mode.

*

The line is a comment.

/

The line is a comment that will also force a page eject in the compilation listing. While GnuCOBOL will honour such a line as a comment, it will not form-feed any generated listing.

-

The line is a continuation of the previous line. These are needed only when an alphanumeric literal (quoted character string), reserved word or user-defined word are being split across lines.

8-11

Language DIVISION, SECTION and paragraph section headers must begin in Area A, as must the level numbers 01, 77 in data description entries and the "FD" and "SD" file and SORT description headers.

12-72

All other COBOL programming language components are coded in these columns.

73-80

This is another obsolete area of COBOL statements. This part of every statement also hails back to the day when programs were punched on cards; it was expected that the name of the program (or at least the first 8 characters of it) would be punched here so that — if a dropped COBOL source deck contained more than one program — that handy card sorter machine could be used to first separate the cards by program name and then sort them by sequence number. Today’s COBOL compilers (including GnuCOBOL) simply ignore anything past column 72.

See Marking Changes in Programs, for discussion of a valuable use to which the program name area may be put today.

1.3.17. Program Structure

Complete GnuCOBOL Program Syntax

 [ IDENTIFICATION DIVISION. ]
   ~~~~~~~~~~~~~~~~~~~~~~~
   PROGRAM-ID|FUNCTION-ID.  name-1 [ Program-Options ] .
   ~~~~~~~~~~ ~~~~~~~~~~~
 [ ENVIRONMENT DIVISION. ]
   ~~~~~~~~~~~ ~~~~~~~~
 [ CONFIGURATION SECTION. ]
   ~~~~~~~~~~~~~ ~~~~~~~
 [ SOURCE-COMPUTER.         Compilation-Computer-Specification . ]
   ~~~~~~~~~~~~~~~
 [ OBJECT-COMPUTER.         Execution-Computer-Specification . ]
   ~~~~~~~~~~~~~~~
 [ REPOSITORY.              Function-Specification... . ]
   ~~~~~~~~~~
 [ SPECIAL-NAMES.           Program-Configuration-Specification . ]
   ~~~~~~~~~~~~~
 [ INPUT-OUTPUT SECTION. ]
   ~~~~~~~~~~~~ ~~~~~~~
 [ FILE-CONTROL.            General-File-Description... . ]
   ~~~~~~~~~~~~
 [ I-O-CONTROL.             File-Buffering-Specification... . ]
   ~~~~~~~~~~~
 [ DATA DIVISION. ]
   ~~~~~~~~~~~~~
 [ FILE SECTION.            Detailed-File-Description... . ]
   ~~~~~~~~~~~~
 [ WORKING-STORAGE SECTION. Permanent-Data-Definition... . ]
   ~~~~~~~~~~~~~~~ ~~~~~~~
 [ LOCAL-STORAGE SECTION.   Temporary-Data-Definition... . ]
   ~~~~~~~~~~~~~ ~~~~~~~
 [ LINKAGE SECTION.         Subprogram-Argument-Description... . ]
   ~~~~~~~ ~~~~~~~
 [ REPORT SECTION.          Report-Description... . ]
   ~~~~~~ ~~~~~~~
 [ SCREEN SECTION.          Screen-Layout-Definition... . ]
   ~~~~~~ ~~~~~~~
   PROCEDURE DIVISION [ { USING Subprogram-Argument...      } ]
   ~~~~~~~~~ ~~~~~~~~   { ~~~~~                             }
                        { CHAINING Main-Program-Argument... }
                          ~~~~~~~~
                      [   RETURNING identifier-1 ] .
 [ DECLARATIVES. ]        ~~~~~~~~~
   ~~~~~~~~~~~~
 [ Event-Handler-Routine... . ]
 [ END DECLARATIVES. ]
   ~~~ ~~~~~~~~~~~~
   General-Program-Logic
 [ Nested-Subprogram... ]
 [ END PROGRAM|FUNCTION name-1 ]
   ~~~ ~~~~~~~ ~~~~~~~~

Each program consists of up to four ’Divisions

  1. Not all divisions are needed in every program, but they must be specified in the order shown when they are used.
  2. The following points pertain to the identification division
    • TheIDENTIFICATION DIVISION.header is always optional.
  3. The following points pertain to the environment division:
    • If both optional sections of this division are coded, they must be coded in the sequence shown.
    • Each of these sections consists of a series of specific paragraphs SOURCE-COMPUTERandOBJECT-COMPUTER for example). Each of these paragraphs serves a specific purpose. If no code is required for the purpose one of the paragraphs serves, the entire paragraph may be omitted.
    • If none of the paragraphs within one of the sections are coded, the section header itself may be omitted.
    • The paragraphs within each section may only be coded in that section, but may be coded in any order.
    • If none of the sections within the environment division are coded, theENVIRONMENT DIVISION.header itself may be omitted.
  4. The following points pertain to the data division:
    • The data division consists of six optional sections — when used, those sections must be coded in the order shown in the syntax diagram.
    • Each of these sections consists of code which serves a specific purpose. If no code is required for the purpose one of those sections serves, the entire section, including it’s header, may be omitted.
    • If none of the sections within the data division are coded (a highly unlikely, but theoretically possible circumstance), theDATA DIVISION.header itself may be omitted.
  5. The following points pertain to the procedure division:
    • As with the other divisions, the procedure division may consist of sections and those sections may — in turn — consist of paragraphs. Unlike the other divisions, however, section and paragraph names are defined by the programmer, and there may not be any defined at all if the programmer so wishes.
    • Each Event-Handler-Routine will be a separate section devoted to trapping a particular run-time event. If there are no such sections coded, theDECLARATIVES.andEND DECLARATIVES.lines may be omitted.
  6. A single file of COBOL source code may contain:
    • A portion of a program; these files are known as copybooks
    • A single program. In this case, theEND PROGRAMorEND FUNCTIONstatement is optional.
    • Multiple programs, separated from one another byEND PROGRAMorEND FUNCTIONstatements. The final program in such a source code file need not have anEND PROGRAMorEND FUNCTIONstatement.
  7. Subprogram "B" may be nested inside program "A" by including program B’s source code at the end of program A’s procedure division without an interveningEND PROGRAM A.orEND FUNCTION A.statement. For now, that’s all that will be said about nesting. See Independent vs Contained vs Nested Subprograms, for more information.
  8. Regardless of how many programs comprise a single GnuCOBOL source file, only a single output executable program will be generated from that source file when the file is compiled.

1.3.18. Comments

Comment Type Source Mode — Description
Blank Lines FIXED — Blank lines may be inserted as desired. FREE — Blank lines may be inserted as desired.
Full-line comments FIXED — An entire source line will be treated as a comment (and will be ignored by the compiler) by coding an asterisk ("*") in column seven (7). FREE — An entire source line will be treated as a comment (and will be ignored by the compiler) by coding the sequence "*>", starting in any column, as the first non-blank characters on the line.
Full-line comments with form-feed FIXED — An entire source line will be treated as a comment by coding a slash ("/") in column seven (7). Many COBOL compilers will also issue a form-feed in the program listing so that the "/" line is at the top of a new page. The GnuCOBOL compiler does not support this form-feed behaviour. The GnuCOBOL Interactive Compiler, or GCic, does support this form-feed behaviour when it generates program source listings! See GCic in GnuCOBOL Sample Programs, for the source and cross-reference listing (produced by GCic) of this program — you can see the effect of "/" there. FREE — There is no Free Source Mode equivalent to "/".
Partial-line comments FIXED — Any text following the character sequence "*>" on a source line will be treated as a comment. The "*" must appear in column seven (7) or beyond. FREE — Any text following the character sequence "*>" on a source line will be treated as a comment. The "*" may appear in any column.
Comments that may be treated as code, typically for debugging purposes FIXED — By coding a "D" in column 7 FREE — By specifying the character sequence ">>D" Debugging statements may be compiled either by specifying the-fdebugging-lineswitch

1.3.19. Literals

1.3.19.1. Numeric Literals

  • Integers such as 1, 56, 2192 or -54.
  • Non-integer fixed point values such as 1.317 or -2.95.
  • Floating-point values using "Enn" notation such as 9.92E25, representing 9.92 x 10^25 (10 raised to the 25th power) or 5.7E-14, representing 5.7 x 10^-14 (10 raised to the -14th power). Both the mantissa (the number before the E) and the exponent (the number after the E) may be explicitly specified as positive (with a +), negative (with a -) or unsigned (and therefore implicitly positive). A floating-point literals value must be within the range -1.7 x 10^308 to +1.7 x 10^308 with no more than 15 decimal digits of precision.
  • Hexadecimal numeric literals

1.3.19.2. Alphanumeric Literals

An alphanumeric literal is not valid for use in arithmetic expressions unless it is first converted to it’s numeric computational equivalent; there are three numeric conversion intrinsic functions built into GnuCOBOL that can perform this conversion —NUMVAL(see NUMVAL),NUMVAL-C(see NUMVAL-C) andNUMVAL-F(see NUMVAL-F).

Alphanumeric literals may take any of the following forms:

  • A sequence of characters enclosed by a pair of single-quote (’)
  • A literal formed according to the same rules as for a string literal (above), but prefixed with the letter "Z" (upper- or lower-case) constitutes a zero-delimited string literal. These literals differ from ordinary string literals in that they will be explicitly terminated with a byte of hexadecimal value 00. These ’Zero-Delimited Alphanumeric Literals
  • A ’Hexadecimal Alphanumeric Literal

Alphanumeric literals too long to fit on a single line may be continued to the next line in one of two ways:

  1. If you are using Fixed Format Mode, the alphanumeric literal can be run right up to and including column 72. The literal may then be continued on the next line anywhere after column 11 by coding another quote or apostrophe (whichever was used to begin the literal originally). The continuation line must also have a hyphen (-)
         1         2         3         4         5         6         7   
1234567890123456789012345678901234567890123456789012345678901234567890123

       01  LONG-LITERAL-VALUE-DEMO     PIC X(60) VALUE "This is a long l
      -                                                "ong literal that
      -                                                " must be continu
      -                                                "ed.".
  1. Regardless of whether the compiler is operating in Fixed or Free Format Mode, GnuCOBOL allows alphanumeric literals to be broken up into separate fragments. These fragments have their own beginning and ending quote/apostrophe characters and are "glued together" at compilation time using "&"
         1         2         3         4         5         6         7   
1234567890123456789012345678901234567890123456789012345678901234567890123

      01  LONG-LITERAL-VALUE-DEMO      PIC X(60) VALUE "This is a" &
                                        " long literal that must " &
                                                    "be continued.".

If your program is using Free Format Mode, there’s less need to continue long alphanumeric literals because statements may be as long as 255 characters.

Numeric literals may be split across lines just as alphanumeric literals are, using either of the above techniques and both reserved and user-defined words can be split across lines too (using the first technique). The continuation of numeric literals and user-defined/reserved words is provided merely to provide compatibility with older COBOL versions and programs, but should not be used with new programs — it just makes for ugly-looking programs.

1.3.19.3. Figurative Constants

05 FILLER                PIC 9(10) VALUE ZEROS.
   ...
MOVE SPACES TO Employee-Name

But this is not:

CALL "SUBPGM" USING SPACES

The following are the GnuCOBOL figurative constants and their respective equivalent values.

ZERO

This figurative constant has a value of numeric 0 (zero).ZEROSandZEROESare both synonyms ofZERO

SPACE

This figurative constant has a value of one or more space characters.SPACESis a synonym ofSPACE

QUOTE

This figurative constant has a value of one or more double-quote characters (").QUOTESis a synonym ofQUOTE

LOW-VALUE

This figurative constant has a value of one or more of whatever character occupies the lowest position in the program’s collating sequence as defined in theOBJECT-COMPUTER(see OBJECT-COMPUTER) paragraph or — if no such specification was made — in whatever default character set the program is using (typically, this is the ASCII character set).LOW-VALUESis a synonym ofLOW-VALUE

When the character set in use is ASCII with no collating sequence modifications, theLOW-VALUESfigurative constant value is the ASCII "NUL" character. Because character sets can be redefined, however, you should not rely on this fact — use theNULLfigurative constant instead.

HIGH-VALUE

This figurative constant has a value of one or more of whatever character occupies the highest position in the program’s collating sequence as defined in theOBJECT-COMPUTERparagraph or — if no such specification was made — in whatever default character set the program is using (typically, this is the ASCII character set).HIGH-VALUESis a synonym ofHIGH-VALUE

NULL

A character comprised entirely of zero-bits (regardless of the programs collating sequence).

Programmers may create their own figurative constants via theSYMBOLIC CHARACTERS(see Symbolic-Characters-Clause) clause of theSPECIAL-NAMES(see SPECIAL-NAMES) paragraph.

1.3.20. Punctuation

The use of comma characters can cause confusion to a COBOL compiler if theDECIMAL POINT IS COMMAclause is used in theSPECIAL-NAMES(see SPECIAL-NAMES) paragraph, as might be the case in Europe. The following statement, which calls a subroutine passing it two arguments (the numeric constants 1 and 2):

CALL "SUBROUTINE" USING 1,2

Would — withDECIMAL POINT IS COMMAin effect — actually be interpreted as a subroutine call with 1 argument (the non-integer numeric literal whose value is 1 and 2 tenths). For this reason, it is best to always follow a comma with a space.

The period character (".")

The rules for where and when periods are needed in the procedure division are somewhat complicated. See Use of Periods, for the details.

1.3.21. LENGTH OF

LENGTH OF Syntax

 LENGTH OF numeric-literal-1 | identifier-1
 ~~~~~~

Alphanumeric literals and identifiers may optionally be prefixed with theLENGTH OFclause. The compile-time value generated by this clause will be the number of bytes in the alphanumeric literal or the defined size (in bytes) of the identifier.

  1. The reserved wordOFis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.

    Here is an example. The following two GnuCOBOL statements both display the same result (27):

    01  Demo-Identifier          PIC X(27).
    ...
        DISPLAY LENGTH OF "This is a LENGTH OF Example"
        DISPLAY LENGTH OF Demo-Identifier
    
  2. TheLENGTH OFclause on a literal or identifier reference may generally be used anywhere a numeric literal might be specified, with the following exceptions:
    • As part of theFROMclause of aWRITE(see WRITE) orRELEASEstatement (see RELEASE).
    • As part of theTIMESclause of aPERFORMstatement (see PERFORM).

1.3.22. Interfacing to Other Environments

Through theCALLstatement, COBOL programs may invoke other COBOL programs serving as subprograms. This is quite similar to cross-program linkage capabilities provided by other languages. In GnuCOBOL’s case, theCALLfacility is powerful enough to be tailored to the point where a GnuCOBOL program can communicate with operating system, database management and run-time library APIs, even if they weren’t written in COBOL themselves. See GnuCOBOL Main Programs CALLing C Subprograms, for an example of how a GnuCOBOL program could invoke a C-language subprogram, passing information back and forth between the two.

The fact that GnuCOBOL supports a full-featured two-way interface with C-language programs means that — even if you cannot access a library API directly — you could always do so via a small C "wrapper" program that isCALLd by a GnuCOBOL program.

2. CDF - Compiler Directing Facility

When the compiler is operating in Fixed Format Mode, all CDF statements must begin in column eight (8) or beyond.

There are two types of supported CDF statements in GnuCOBOL — Text Manipulation Statements and Compiler Directives.

The CDF text manipulation statementsCOPYandREPLACEare used to introduce new code into programs either with or without changes, or may be used to modify existing statements already in the program. Text manipulation statements are always terminated with a period.

CDF directives, denoted by the presence of a ">>" character sequence as part of the statement name itself, are used to influence the process of program compilation.

Compiler directives are never terminated with a period.

2.1. >>CALL-CONVENTION

CDF >>CALL-CONVENTION Syntax

 >>CALL-CONVENTION    { COBOL   }
 ~~~~~~~~~~~~~~~~~    { EXTERN  }
                      { STDCALL }
                      { STATIC  } 
  1. COBOL (the default) the program name is treated as a COBOL word that maps to the externalised name program to be called, cancelled or referenced in the program-address-identifier, applying the same mapping rules as for a program name for which no AS phrase is specified.
  2. EXTERN the program name is treated as an external reference.
  3. STDCALL. < more info needed >
  4. STATIC the program name is called as a included element and not dynamically which is the normal default.

2.2. COPY

CDF COPY Statement Syntax

 COPY copybook-name
 ~~~~
 [ IN|OF library-name ]
   ~~ ~~
 [ SUPPRESS PRINTING ]
   ~~~~~~~~
 [ REPLACING { Phrase-Clause | String-Clause }... ] .
   ~~~~~~~~~

CDF COPY Phrase-Clause Syntax

 { ==pseudo-text-1== } BY { ==pseudo-text-2== }
 { identifier-1      } ~~ { identifier-2      }
 { literal-1         }    { literal-2         }
 { word-1            }    { word-2            }

CDF COPY String-Clause Syntax

 [ LEADING|TRAILING ] ==partial-word-1== BY ==partial-word-2==
   ~~~~~~~ ~~~~~~~~                      ~~
  1. COPYstatements are used to import copybooks (see Copybooks) into a program.
  2. COPYstatements may be used anywhere within a COBOL program where the code contained within the copybook would be syntactically valid.
  3. The optionalSUPPRESS
  4. There is no difference between the use of the wordINand the wordOF— use the one you prefer.
  5. A period is absolutely mandatory at the end of everyCOPYstatement, even if the statement occurs within the scope of another one where a period might appear disruptive, such as within the scope of anIF(see IF) statement. This mandatory period at the end of the statement will not, however, affect the statement scope in which theCOPYoccurs.
  6. Both <pseudo-text-2> and <partial-word-2> may be null.
  7. AllCOPYstatements are located and the contents of the corresponding copybooks inserted into the program source code before the actual compilation process begins. If a copybook contains aCOPYstatement, the copybook insertion process will be repeated to resolve the embeddedCOPY This will continue until no unresolvedCOPYstatements remain. At that point, actual program compilation will begin.
  8. See Locating Copybooks, for the specific rules on how copybooks are located by the compiler.
  9. The optionalREPLACING
    <<Phrase-Clause>>

    Replacement of one or more complete reserved words, user-defined identifiers or literals; the following points apply to this option:

    • This option cannot be used to replace part of a word, identifier or literal.
    • Whatever precedes theBYwill be referred to here as the search string.
    • Single-item search strings can be specified by coding the<identifier-1><literal-1>or<word-1>being replaced.
    • Multiple-item search strings can be specified using the==<pseudo-text-1>==option. For example, to replace all occurrences ofUPON PRINTER you would specify==UPON PRINTER==
    • The replacement string, which follows theBY may be specified using any of the four options.
    • If the replacement string is a multiple-item phrase or is to be deleted altogether, you must use the==<pseudo-text-2>==option. If<pseudo-text-2>is null (in other words, the replacement text is specified as====, all encountered occurrences of the search string will be deleted.
    <<String-Clause>>

    Using this, you may replace character sequences that occur at the beginning LEADING

2.3. REPLACE

CDF REPLACE Statement (Format 1) Syntax

 REPLACE [ ALSO ] { Phrase-Clause | String-Clause }... .
 ~~~~~~~   ~~~~

CDF REPLACE Statement (Format 2) Syntax

 REPLACE [ LAST ] OFF .
 ~~~~~~~   ~~~~   ~~~

CDF REPLACE Phrase-Clause Syntax

 { ==pseudo-text-1== } BY { ==pseudo-text-2== }
                       ~~

CDF REPLACE String-Clause Syntax

 [ LEADING|TRAILING ] ==partial-word-1== BY ==partial-word-2==
   ~~~~~~~ ~~~~~~~~                      ~~
  1. TheREPLACEstatement provides a mechanism for changing all or part of one or more GnuCOBOL statements.
  2. A period is absolutely mandatory at the end of everyREPLACEstatement (either format), even if the statement occurs within the scope of another one where a period might appear disruptive (such as within the scope of anIF(see IF) statement; the period will not, however, affect the statement scope in which theREPLACEoccurs.
  3. The following points apply to Format 1 of theREPLACEstatement:
    1. Format 1 of theREPLACEstatement can be used to make changes to program source code in much the same way as theREPLACING
      <<Phrase-Clause>>

      Replace one or more complete reserved words, user-defined identifiers or literals; the following points apply to this option:

      • This option cannot be used to replace part of a word, identifier or literal.
      • Whatever precedes theBYwill be referred to here as the search string.
      • Search strings onREPLACEare always specified using the==<pseudo-text-1>==option. For example, to replace all occurrences ofUPON PRINTER you would specify==UPON PRINTER==
      • The replacement string, which follows theBY is specified using the==<pseudo-text-2>==option. If<pseudo-text-2>is null (in other words, the replacement text is specified as====, all encountered occurrences of the search string will be deleted.
      <<String-Clause>>

      Using this, you may replace character sequences that occur at the beginning LEADING

    2. Once a Format 1REPLACEstatement is encountered in the currently-compiling source file, Replace Mode becomes active, and the change(s) specified by that statement will be automatically made on all subsequent source statements the compiler reads from the file.
    3. Replace Mode remains in-effect — continuing to make source code changes — until another Format 1REPLACEis encountered, the end of currently compiling program source file is reached or a Format 2REPLACEstatement is encountered.
    4. When a Format 1REPLACEstatement with theALSO
    5. When a Format 1REPLACEwithout theALSOkeyword is encountered, any stacked change specification(s), if any, will be discarded and the currently in-effect change specification(s), if any, will be replaced by those of the new statement.
    6. When the end of the currently-compiling source file is reached, Replace Mode is deactivated and any stacked replace specifications will be discarded — compilation of the next source file (if any) will begin with Replace Mode inactive and no change specification(s) on the stack.
  4. The following points apply to Format 2 of theREPLACEstatement:
    1. If Replace Mode is currently inactive, the Format 2 REPLACE statement will be ignored.
    2. If Replace Mode is currently active, aREPLACE OFF.will deactivate Replace Mode and discard any replace specification(s) on the stack. The compiler will henceforth operate as if noREPLACEhad ever been encountered, until such time as another Format 1REPLACEis encountered.
    3. If Replace Mode is currently active, aREPLACE LAST OFF.will replace the current replace specification(s) with those popped off the top of the stack. If there were no replace specification(s) on the stack, the effect will be as if aREPLACE OFF.had been coded.

2.4. >>DEFINE

CDF >>DEFINE Directive Syntax

 >>DEFINE [ CONSTANT ] cdf-variable-1 AS { OFF                    }
 ~~~~~~~~   ~~~~~~~~                     { ~~~                    }
                                         { literal-1 [ OVERRIDE ] }
                                         {             ~~~~~~~~   }
                                         { PARAMETER [ OVERRIDE ] }
                                           ~~~~~~~~~   ~~~~~~~~
  1. The reserved wordASis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. CDF variables defined in this way become undefined once anEND PROGRAMorEND FUNCTIONdirective is encountered in the input source.
  3. The>>DEFINECDF directive is one way to create CDF variables that may be processed by other CDF statements such as>>IF(see >>IF). The>>SETCDF directive (see >>SET) provides another way to create them.
  4. CDF variable names follow the rules for standard GnuCOBOL user-defined names, and may not duplicate any CDF reserved word. CDF variable names may duplicate COBOL reserved words, provided theCONSTANT
  5. TheCONSTANToption is valid only in conjunction with <literal-1>. WhenCONSTANTis specified, the CDF variable that is created may be used within your regular COBOL code as if it were a literal value. Without this option, the CDF variable may only be referenced on other CDF statements. TheOFF
  6. ThePARAMETER
  7. In the absence of theOVERRIDE

2.5. >>IF

CDF >>IF Directive Syntax

 >>IF CDF-Conditional-Expression-1
 ~~~~     [ Program-Source-Lines-1 ]

 [ >>ELIF CDF-Conditional-Expression-2
   ~~~~~~ [ Program-Source-Lines-2 ] ]...

 [ >>ELSE
   ~~~~~~ [ Program-Source-Lines-3 ] ]

 >>END-IF
 ~~~~~~~~

CDF-Conditional-Expression Syntax

 { cdf-variable-1 } IS [ NOT ] { DEFINED                      }
 { literal-1      }      ~~~   { ~~~~~~~                      }
                               { SET                          }
                               { ~~~                          }
                               { CDF-RelOp { cdf-variable-2 } }
                               {           { literal-2      } }

CDF-RelOp Syntax

 >=    or    GREATER THAN OR EQUAL TO
             ~~~~~~~      ~~ ~~~~~
 >     or    GREATER THAN
             ~~~~~~~
 <=    or    LESS THAN OR EQUAL TO
             ~~~~      ~~ ~~~~~
 <     or    LESS THAN
             ~~~~
 =     or    EQUAL TO
             ~~~~~
 <>    or    EQUAL TO (with "NOT")
             ~~~~~
  1. The reserved wordsISTHANandTOare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. Each>>IFdirective must be terminated by an>>END-IF
  3. There may be any number of>>ELIF
  4. There may no more than one>>ELSE
  5. Only one of the <<Program-Source-Lines-n>> block of statements that lie within the scope of the>>IF>>END-IFmay be processed by the compiler. Which one (if any) that gets processed will be decided as follows:
    1. Each <<CDF-Conditional-Expression-n>> will be evaluated, in turn, in the sequence in which they are coded in the >>IF statement and any>>ELIFclauses that may be present until one evaluates to TRUE. Once one of them evaluates to TRUE, the <<Program-Source-Lines-n>> block of code that corresponds to the TRUE <<CDF-Conditional-Expression-n>> will be one that is processed. All others within the>>IF>>END-IFscope will be ignored.
    2. If no <<CDF-Conditional-Expression>> evaluates to TRUE, and there is an>>ELSEclause, the <<Program-Source-Lines-3>> block of statements following the>>ELSEclause will be processed by the compiler and all others within the>>IF>>END-IFscope will be ignored.
    3. If no <<CDF-Conditional-Expression-n>> evaluates to TRUE and there is no>>ELSEclause, then none of the <<Program-Source-Lines-n>> block of statements within the>>IF>>END-IFscope will be processed by the compiler.
    4. If the <Program-Source-Lines-n>> statement block selected for processing is empty, no error results — there will just be no code generated from the>>IF>>END-IFstructure.
  6. A <<Program-Source-Lines-n>> block may contain any valid COBOL or CDF code.
  7. The following points pertain to any <<CDF-Conditional-Expression-n>>:
    1. TheDEFINED
    2. TheSET
    3. Two CDF variables, two literals or a single CDF variable and a single literal may be compared against each other using a relational operator. Unlike the standard GnuCOBOLIFstatement (see IF), multiple comparisons cannot be "AND"ed or "OR"ed together; you may nest a second>>IFinside the first, however, to simulate an "AND" and an "OR" may be simulated via the>>ELIFoption.
    4. The<>symbol stands forNOT EQUAL TO

2.6. >>SET

CDF >>SET Directive Syntax

 >>SET { [ CONSTANT ] cdf-variable-1 [ AS literal-1 ] }
 ~~~~~ {   ~~~~~~~~                    ~~             }
       { SOURCEFORMAT AS FIXED|FREE                   }
       { ~~~~~~~~~~~~    ~~~~~ ~~~~                   }
       { NOFOLDCOPYNAME                               }
       { ~~~~~~~~~~~~~~                               }
       { FOLDCOPYNAME AS UPPER|LOWER                  }
         ~~~~~~~~~~~~    ~~~~~ ~~~~~
  1. The reserved wordASis optional (only on theSOURCEFORMATandFOLDCOPYNAMEclauses) and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. CDF variables defined in this way become undefined once anEND PROGRAMorEND FUNCTIONdirective is encountered in the input source.
  3. TheFOLDCOPYNAME
  4. TheNOFOLDCOPYNAME
  5. If theCONSTANT
  6. The remaining options of the>>SETCDF directive provide equivalent functionality to the>>DEFINEand>>SOURCEdirectives, as follows:
    1. >>SET <cdf-variable-1>>>DEFINE <cdf-variable-1> AS OFF
    2. >>SET <cdf-variable-1> AS <literal-1>>>DEFINE <cdf-variable-1> AS <literal-1>
    3. >>SET CONSTANT <cdf-variable-1> AS <literal-1>>>DEFINE CONSTANT <cdf-variable-1> AS <literal-1>
    4. >>SET SOURCEFORMAT AS FIXED>>SOURCE FORMAT IS FIXED
    5. >>SET SOURCEFORMAT AS FREE>>SOURCE FORMAT IS FREE

2.7. >>SOURCE

CDF >>SOURCE Directive Syntax

 >>SOURCE FORMAT IS FIXED|FREE|VARIABLE
 ~~~~~~~~           ~~~~~ ~~~~ ~~~~~~~~
  1. The reserved wordsFORMATandISare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. You may switch betweenFIXEDandFREEmode as desired.
  3. You may also use the>>SETCDF directive to perform this function.
  4. If the compiler is already in the specified mode, this statement will have no effect.

2.8. >>TURN

CDF >>TURN Directive Syntax

 >>TURN { exception-name-1 [ file-name-1 ]... }...
 ~~~~~~
    { OFF                           }
    { ~~~                           }
    { CHECKING ON [ WITH LOCATION ] }
      ~~~~~~~~ ~~        ~~~~~~~~

2.9. >>D

CDF >>D Directive Syntax

 >>D
 ~~~

2.10. >>DISPLAY

CDF >>DISPLAY Directive Syntax

 >>DISPLAY source-text [ VCS = version-string ]
 ~~~~~~~~~               ~~~

2.11. >>PAGE

CDF >>PAGE Directive Syntax

 >>PAGE
 ~~~~~~

2.12. >>LISTING

CDF >>LISTING Directive Syntax

 >>LISTING  {ON}
 ~~~~~~~~~  {OFF}

2.13. >>LEAP-SECONDS

CDF >>LEAP-SECONDS Directive Syntax

 >>LEAP-SECONDS
 ~~~~~~~~~~~~~~

The>>LEAP-SECONDSCDF directive is syntactically recognized but is otherwise non-functional.

2.14. * Directives

CDF * Directive Syntax

 $ (Dollar) Directives - Active.

 These directives are active and have the same function as ones starting with >>:

 $DISPLAY ON|OFF
 $SET
 $IF
 $ELIF
 $ELSE-IF
 $END

 $ (Dollar) Directives - Not Active.
 These are NOT active and will produce a warning message:

 $DISPLAY VCS ...
 

3. IDENTIFICATION DIVISION

IDENTIFICATION DIVISION Syntax

[{ IDENTIFICATION } DIVISION. ]
 { ~~~~~~~~~~~~~~ } ~~~~~~~~
 { ID             }
    ~~  
 { PROGRAM-ID.  } program-id [ AS {literal-1    }] [ Type-Clause ] .
 { ~~~~~~~~~~   }                 {program name }]
 { FUNCTION-ID. } { literal-1 }   [ AS literal-2 ].
   ~~~~~~~~~~~    { function-name }
 { OPTIONS. }
   ~~~~~~~
 [ DEFAULT ROUNDED MODE IS {AWAY-FROM-ZERO         }
   ~~~~~~~ ~~~~~~~         {NEAREST-AWAY-FROM-ZERO } 
                           {NEAREST-EVEN           }
                           {NEAREST-TOWARDS-ZERO   }
                           {PROHIBITED             }
                           {TOWARDS-GREATER        }
                           {TOWARDS-LESSER         }
                           {TRUNCATION             }]
 [ ENTRY-CONVENTION IS {COBOL   }
   ~~~~~~~~~~~~~~~~    {EXTERN  }
                       {STDCALL }]                       
 [ AUTHOR.        comment-1. ]
   ~~~~~~
 [ DATE-COMPILED. comment-2. ]
   ~~~~~~~~~~~~~
 [ DATE-MODIFIED. comment-3. ]
   ~~~~~~~~~~~~~
 [ DATE-WRITTEN.  comment-4. ]
   ~~~~~~~~~~~~
 [ INSTALLATION.  comment-5. ]
   ~~~~~~~~~~~~
 [ REMARKS.       comment-6. ]
   ~~~~~~~
 [ SECURITY.      comment-7. ]
   ~~~~~~~~

TheAUTHOR

PROGRAM-ID Type Clause Syntax

 IS [ COMMON ] [ INITIAL|RECURSIVE PROGRAM ]
      ~~~~~~     ~~~~~~~ ~~~~~~~~~

The identification division provides basic identification of the program by giving it a name and optionally defining some high-level characteristics via the eight pre-defined paragraphs that may be specified.

  1. The paragraphs shown above may be coded in any sequence.
  2. The reserved wordsASISandPROGRAMare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  3. A Type Clause may be coded only whenPROGRAM-ID
  4. While the actualIDENTIFICATION DIVISIONorID DIVISIONheader is optional, thePROGRAM-ID/FUNCTION-ID
  5. The compiler’s-Wobsoleteswitch
  6. If specified, <literal-1> must be an actual alphanumeric literal and may not be a figurative constant.
  7. ThePROGRAM-IDandFUNCTION-IDparagraphs serve to identify the program to the external (i.e. operating system) environment. If there is noASclause present, the <program-id> will serve as that external identification. If there is anASclause specified, that specified literal will serve as the external identification. For the remainder of this document, that "external identification" will be referred to as the primary entry-point name.
  8. TheINITIALCOMMONandRECURSIVEwords are used only within subprograms serving as subroutines. Their purposes are as follows:
    1. COMMON
    2. TheRECURSIVE

      User-defined functions (i.e.FUNCTION-ID are always recursive.

    3. TheINITIAL

4. ENVIRONMENT DIVISION

ENVIRONMENT DIVISION Syntax

   ENVIRONMENT DIVISION.
   ~~~~~~~~~~~ ~~~~~~~~
 [ CONFIGURATION SECTION. ]
   ~~~~~~~~~~~~~ ~~~~~~~~
 [ SOURCE-COMPUTER.         Compilation-Computer-Specification . ]
   ~~~~~~~~~~~~~~~
 [ OBJECT-COMPUTER.         Execution-Computer-Specification . ]
   ~~~~~~~~~~~~~~~
 [ SPECIAL-NAMES.           Program-Configuration-Specification . ]
   ~~~~~~~~~~~~~
 [ REPOSITORY.              Function-Specification... . ]
   ~~~~~~~~~~
 [ INPUT-OUTPUT SECTION. ]
   ~~~~~~~~~~~~ ~~~~~~~
 [ FILE-CONTROL.            General-File-Description... . ]
   ~~~~~~~~~~~~
 [ I-O-CONTROL.             File-Buffering Specification... . ]
   ~~~~~~~~~~~
  • If both optional sections of this division are coded, they must be coded in the sequence shown.
  • The paragraphs within the sections may be coded in any order.
  • These sections consist of a series of specific, pre-defined, paragraphs SOURCE-COMPUTERandOBJECT-COMPUTER for example), each of which serves a specific purpose. If no code is required for the purpose one of the paragraphs serves, the entire paragraph may be omitted.
  • If any of the paragraphs within one of the sections are coded, the section header itself must be coded.
  • If none of the paragraphs within one of the sections are coded, the section header itself may be omitted.
  • If none of the sections within the environment division are coded, theENVIRONMENT DIVISION.header itself may be omitted.

4.1. CONFIGURATION SECTION

CONFIGURATION SECTION Syntax

   CONFIGURATION SECTION.
   ~~~~~~~~~~~~~ ~~~~~~~
 [ SOURCE-COMPUTER. Compilation-Computer-Specification . ]
   ~~~~~~~~~~~~~~~
 [ OBJECT-COMPUTER. Execution-Computer-Specification . ]
   ~~~~~~~~~~~~~~~
 [ SPECIAL-NAMES.   Program-Configuration-Specification . ]
   ~~~~~~~~~~~~~
 [ REPOSITORY.      Function-Specification... . ]
   ~~~~~~~~~~
  1. The four paragraphs in this section may be specified in any order but if not in this order, a warning will be issued.
  2. The configuration section is not allowed in a nested subprogram — nested programs will inherit the configuration section settings of their parent program.
  3. If none of the features provided by the configuration section are required by a program, the entireCONFIGURATION SECTION.header may be omitted from the program.

4.1.1. SOURCE-COMPUTER

SOURCE-COMPUTER Syntax

 SOURCE-COMPUTER. computer-name [ WITH DEBUGGING MODE ] .
 ~~~~~~~~~~~~~~~                       ~~~~~~~~~ ~~~~
  1. The reserved wordWITHis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. This paragraph is not allowed in a nested subprogram — nested programs will inherit theSOURCE-COMPUTERsettings of their parent program.
  3. The value specified for <computer-name> is irrelevant, provided it is a valid COBOL word that does not match any GnuCOBOL reserved word. The <computer-name> value may include spaces. This need not match the <computer-name> used with theOBJECT-COMPUTERparagraph, if any.
  4. TheDEBUGGING MODE
  5. Even without theDEBUGGING MODEclause, it is still possible to compile debugging lines. Debugging lines may also be compiled by specifying the-fdebugging-lineswitch

4.1.2. OBJECT-COMPUTER

OBJECT-COMPUTER Syntax

 OBJECT-COMPUTER.  [ computer-name ]
 ~~~~~~~~~~~~~~~
 [ MEMORY SIZE IS integer-1 WORDS|CHARACTERS ]
   ~~~~~~ ~~~~              ~~~~~ ~~~~~~~~~~
 [ PROGRAM COLLATING SEQUENCE IS alphabet-name-1 ]
           ~~~~~~~~~
 [ SEGMENT-LIMIT IS integer-2 ]
   ~~~~~~~~~~~~~
 [ CHARACTER CLASSIFICATION IS { locale-name-1  } ]
             ~~~~~~~~~~~~~~    { LOCALE         }
                               { ~~~~~~         }
                               { USER-DEFAULT   }
                               { ~~~~~~~~~~~~   }
                               { SYSTEM-DEFAULT }
                                 ~~~~~~~~~~~~~~
 .

TheMEMORY SIZE

  1. The <computer-name>, if specified, must immediately follow theOBJECT-COMPUTERparagraph name. The remaining clauses may be coded in any sequence.
  2. The reserved wordsCHARACTERISPROGRAMandSEQUENCEare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  3. The value specified for <computer-name>, if any, is irrelevant provided it is a valid COBOL word that does not match any GnuCOBOL reserved word. The <computer-name> may include spaces. This need not match the <computer-name> used with theSOURCE-COMPUTERparagraph, if any.
  4. TheOBJECT-COMPUTERparagraph is not allowed in a nested subprogram — nested programs will inherit theOBJECT-COMPUTERsettings of their parent program.
  5. TheCOLLATING SEQUENCE
  6. If noCOLLATING SEQUENCEclause is specified, the collating sequence implied by the character set native to the computer (usually ASCII) will be used.
  7. The optionalCLASSIFICATION

    The meanings of the four locale specifications are as follows:

    1. <locale-name-1> references aLOCALE(see SPECIAL-NAMES) definition.
    2. The keywordLOCALErefers to the current locale (in effect at the time the program is executed)
    3. The keywordUSER-DEFAULTreferences the default locale specified for the user currently executing this program.
    4. The keywordSYSTEM-DEFAULTdenotes the default locale specified for the computer upon which the program is executing.
  8. Absence of aCLASSIFICATIONclause will cause character classification to occur according to the rules for the computer’s native character set (ASCII, EBCDIC, …).

4.1.3. SPECIAL-NAMES

SPECIAL-NAMES Syntax

 SPECIAL-NAMES.
 ~~~~~~~~~~~~~
  [ CALL-CONVENTION integer-1 IS mnemonic-name-1 ]
    ~~~~~~~~~~~~~~~
  [ CONSOLE IS CRT ]
    ~~~~~~~    ~~~
  [ CRT STATUS IS identifier-1 ]
    ~~~ ~~~~~~
  [ CURRENCY SIGN IS literal-1 ]
    ~~~~~~~~ ~~~~
  [ CURSOR IS identifier-2 ]
    ~~~~~~
  [ DECIMAL-POINT IS COMMA ]
    ~~~~~~~~~~~~~    ~~~~~
  [ EVENT STATUS IS identifier-3 ]
    ~~~~~ ~~~~~~
  [ LOCALE locale-name-1 IS literal-2 ]...
    ~~~~~~
  [ NUMERIC SIGN IS TRAILING SEPARATE ]
    ~~~~~~~ ~~~~    ~~~~~~~~ ~~~~~~~~
  [ SCREEN CONTROL IS identifier-4 ]
    ~~~~~~ ~~~~~~~
  [ device-name-1 IS mnemonic-name-2 ]...

  [ feature-name-1 IS mnemonic-name-3 ]...

  [ Alphabet-Clause ]...

  [ Class-Definition-Clause ]...

  [ Switch-Definition-Clause ]...

  [ Symbolic-Characters-Clause ]...
  .

TheEVENT STATUS

<<Alphabet-Name-Clause>>, <<Class-Definition-Clause>>,
<<Switch-Definition-Clause>> and <<Symbolic-Characters-Clause>>
are discussed in detail in the next four sections.

TheSPECIAL-NAMESparagraph provides a means for specifying various program and operating environment configuration options.

  1. The various clauses that may be specified within theSPECIAL-NAMESparagraph may be coded in any order.
  2. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  3. TheSPECIAL-NAMESparagraph is not allowed in a nested subprogram — nested programs will inherit theSPECIAL-NAMESsettings of their parent program.
  4. Only the final clause specified within this paragraph should be terminated with a period.
  5. TheCALL-CONVENTION
  6. TheCONSOLE IS CRT
  7. If theCRT STATUS
  8. TheCURRENCY SIGN
  9. TheCURSOR IS
  10. TheDECIMAL POINT IS COMMA
  11. TheLOCALE
  12. The following is the list of possible locale codes, for example, that would be available on a Windows computer running a GnuCOBOL version that was built utilizing the MinGW Unix-emulator and the GNU C compiler (gcc):
    A

    af_ZA, am_ET, ar_AE, ar_BH, ar_DZ, ar_EG, ar_IQ, ar_JO, ar_KW, ar_LB, ar_LY, ar_MA, ar_OM, ar_QA, ar_SA, ar_SY, ar_TN, ar_YE, arn_CL, as_IN, az_Cyrl_AZ, az_Latn_AZ

    B

    ba_R, be_BY, bg_BG, bn_IN bo_BT, bo_CN, br_FR, bs_Cyrl_BA, bs_Latn_BA

    C

    ca_ES, cs_CZ, cy_GB

    D

    da_DK, de_AT, de_CH, de_DE, de_LI, de_LU, dsb_DE, dv_MV

    E

    el_GR, en_029, en_AU, en_BZ, en_CA, en_GB, en_IE, en_IN, en_JM, en_MY en_NZ, en_PH, en_SG, en_TT, en_US, en_ZA, en_ZW, es_AR, es_BO, es_CL, es_CO, es_CR, es_DO, es_EC, es_ES, es_GT, es_HN, es_MX, es_NI, es_PA, es_PE, es_PR, es_PY, es_SV, es_US, es_UY es_VE, et_EE, eu_ES

    F

    fa_IR, fi_FI, fil_PH, fo_FO, fr_BE, fr_CA, fr_CH, fr_FR, fr_LU, fr_MC, fy_NL

    G

    ga_IE, gbz_AF, gl_ES, gsw_FR, gu_IN

    H

    ha_Latn_NG, he_IL, hi_IN, hr_BA, hr_HR, hu_HU, hy_AM

    I

    id_ID, ig_NG, ii_CN, is_IS, it_CH, it_IT, iu_Cans_CA, iu_Latn_CA

    J

    ja_JP

    K

    ka_GE, kh_KH, kk_KZ, kl_GL, kn_IN, ko_KR, kok_IN, ky_KG

    L

    lb_LU, lo_LA, lt_LT, lv_LV

    M

    mi_NZ, mk_MK, ml_IN, mn_Cyrl_MN, mn_Mong_CN moh_CA, mr_IN, ms_BN, ms_MY, mt_MT

    N

    nb_NO, ne_NP, nl_BE, nl_NL, nn_NO, ns_ZA

    O

    oc_FR, or_IN

    P

    pa_IN, pl_PL, ps_AF, pt_BR, pt_PT

    Q

    qut_GT, quz_BO, quz_EC, quz_PE

    R

    rm_CH, ro_RO, ru_RU, rw_RW

    S

    sa_IN, sah_RU, se_FI, se_NO se_SE, si_LK, sk_SK, sl_SI, sma_NO, sma_SE, smj_NO, smj_SE, smn_FI, sms_FI, sq_AL, sr_Cyrl_BA, sr_Cyrl_CS, sr_Latn_BA, sr_Latn_CS, sv_FI, sv_SE, sw_KE syr_SY

    T

    ta_IN, te_IN, tg_Cyrl_TJ, th_TH tk_TM, tmz_Latn_DZ, tn_ZA, tr_IN, tr_TR, tt_RU

    U

    ug_CN, uk_UA, ur_PK, uz_Cyrl_UZ, uz_Latn_UZ

    V

    vi_VN

    W

    wen_DE, wo_SN

    X

    xh_ZA

    Y

    yo_NG

    Z

    zh_CN, zh_HK, zh_MO, zh_SG, zh_TW, zu_ZA

  13. TheNUMERIC SIGN TRAILING SEPARATE
  14. The<device-name-1> IS <mnemonic-name-2>clause allows you to specify an alternate name (<device-name-1>) for one of the built-in GnuCOBOL device name <mnemonic-name-2>. The list of device names built-into GnuCOBOL, and the physical device associated with that name, are as follows:
    CONSOLE

    This is the (screen-mode) display of the PC or Unix system.

    STDIN
    SYSIN
    SYSIPT

    These devices (they are all synonymous) represent standard system input (pipe 0). On a PC or UNIX system, this is typically the keyboard. The contents of a file may be delivered to a GnuCOBOL program for access via one of these device names by adding the sequence "0< filename" to the end of the programs execution command.

    PRINTER
    STDOUT
    SYSLIST
    SYSLST
    SYSOUT

    These devices (they are all synonymous) represent standard system output (pipe 1). On a PC or UNIX system, this is typically the display. Output sent to one of these devices by a GnuCOBOL program can be sent to a file by adding the sequence "1> filename" to the end of the programs execution command.

    STDERR
    SYSERR

    These devices (they are synonymous) represent standard system error output (pipe 2). On a PC or UNIX system, this is typically the display. Output sent to one of these devices by a GnuCOBOL program can be sent to a file by adding the sequence "2> filename" to the end of the programs execution command.

  15. The<feature-name-1> IS <mnemonic-name-3>clause allow for mnemonic names to be assigned to up to the 13 printer channel (i.e. vertical page positioning) position feature namesCnn(nn=01-12) andCSP Once a channel position has been assigned a mnemonic name, statements of the formWRITE <record-name> AFTER ADVANCING <mnemonic-name-3>may be coded to write the specified print record at the channel position assigned to <mnemonic-name-3>.

    Printers supporting channel positioning are generally mainframe-type line printers. When writing to printers that do not support channel positioning, a formfeed will be issued to the printer.

    TheCSPpositioning option stands for "No Spacing". Testing on a MinGW build of GnuCOBOL shows that this too results in a formfeed being issued.

4.1.3.1. Alphabet-Name-Clause

SPECIAL-NAMES Alphabet-Clause Syntax

 ALPHABET alphabet-name-1 IS { ASCII             }
 ~~~~~~~~                    { ~~~~~             }
                             { EBCDIC            }
                             { ~~~~~~            }
                             { NATIVE            }
                             { ~~~~~~            }
                             { STANDARD-1        }
                             { ~~~~~~~~~~        }
                             { STANDARD-2        }
                             { ~~~~~~~~~~        }
                             { Literal-Clause... }

SPECIAL-NAMES ALPHABET Literal-Clause Syntax

 literal-1 [ { THRU|THROUGH literal-2 } ]
             { ~~~~ ~~~~~~~           }
             { {ALSO literal-3}...    }
                ~~~~
  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The reserved wordsTHRUandTHROUGHare interchangeable.
  3. GnuCOBOL considersASCII
  4. NATIVE
  5. The following points apply to using the <literal-n> specifications to compose a custom character set:
    1. The <literal-n> values are either integers or alphanumeric quoted characters. These represent a single character in theNATIVEcharacter set, either by it’s actual text value (alphanumeric quoted character) or by ordinal position in theNATIVEcharacter set (integer),
    2. The sequence in which characters are defined in this clause specifies the relative order those characters should have when comparisons are made using this alphabet.
    3. Character positions in this list do not affect the actual binary storage values used for the characters — binary values will still be those of theNATIVEcharacter set.
    4. You may specify any of the figurative constantsSPACESPACESZEROZEROSZEROESQUOTEQUOTESHIGH-VALUEHIGH-VALUESLOW-VALUEorLOW-VALUESfor any of the <literal-1>, <literal-2> or <literal-3> specifications.
  6. Once you have defined an alphabet name, that alphabet name may be used on specifications inCODE-SETCOLLATING SEQUENCE orSYMBOLIC CHARACTERSclauses elsewhere in the program.

4.1.3.2. Class-Definition-Clause

SPECIAL-NAMES Class-Definition-Clause Syntax

 CLASS class-name-1 IS { literal-1 [ THRU|THROUGH literal-2 ] }...
 ~~~~~                               ~~~~ ~~~~~~~
  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The reserved wordsTHRUandTHROUGHare interchangeable.
  3. Both <literal-1> and <literal-2> must be alphanumeric literals of length 1.
  4. The literal(s) specified on this clause define the possible characters that may be found in a data item’s value in order to be considered part of the class.
  5. For example, the following defines a class called "Hexadecimal", the definition of which specifies the only characters that may be present in an alphanumeric data item if that data item is to be part of the "Hexadecimal" class:
    CLASS Hexadecimal IS '0' THRU '9'
                         'A' THRU 'F'
                         'a' THRU 'f'
    
  6. Once class "Hexadecimal" has been defined, program code could then use a statement such asIF input-item IS Hexadecimalto determine if the value of characters in a data item are valid according to that class.

4.1.3.3. Switch-Definition-Clause

SPECIAL-NAMES Switch-Definition-Clause Syntax

 switch-name-1 [ IS mnemonic-name-1 ]

   [ ON STATUS IS condition-name-1 ]
     ~~
   [ OFF STATUS IS condition-name-2 ]
     ~~~
  1. The reserved wordsISandSTATUSare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The valid <switch-name-1> names areSWITCH-n
  3. If the program is compiled with the-fsyntax-extensionswitch
  4. At execution time, each switch will be associated with a
  5. Each specified switch must have at least one of aIS <mnemonic-name-1>ON STATUSor anOFF STATUSoption defined for it, otherwise there will be no way to reference the switch from within a GnuCOBOL program.
  6. TheIS <mnemonic-name-1>syntax provides a means for setting the switch to either an ON or OFF value via theSETstatement (see SET).
  7. TheON STATUS

4.1.3.4. Symbolic-Characters-Clause

SPECIAL-NAMES-Symbolic-Characters-Clause Syntax

 SYMBOLIC CHARACTERS
 ~~~~~~~~
   { symbolic-character-1... IS|ARE integer-1... }...

   [ IN alphabet-name-1 ]
     ~~
  1. The reserved wordsARECHARACTERSandISare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. There must be exactly as many <integer-1> values specified as there are <symbolic-character-1> names.
  3. Each symbolic character name will be associated with the corresponding <integer-1>th character in the alphabet named in theINclause. The integer values are selecting characters from the alphabet by their ordinal position and not by their numeric value; thus, an integer of 15 will select the 15th character in the specified alphabet, regardless of the actual numeric value of the bit pattern that constitutes that character.
  4. If no <alphabet-name-1> is specified, the systems native character set will be assumed.
  5. The following two code examples define the same set of figurative constant names for five ASCII control characters (assuming that ASCII is the system’s native character set). The two examples are identical in their effects, even though the manner in which the figurative constants are defined is different.
    SYMBOLIC CHARACTERS NUL IS 1    SYMBOLIC CHARACTERS NUL SOH BEL DC1 DC2
                        SOH IS 2                    ARE   1   2   8  18  19
                        BEL IS 8
                        DC1 IS 18
                        DC2 IS 19
    

4.1.4. REPOSITORY

REPOSITORY Syntax

 REPOSITORY.
 ~~~~~~~~~~
    FUNCTION { function-prototype-name-1 [ AS literal-1 ] }...
    ~~~~~~~~ {                             ~~             }
             { intrinsic-function-name-1 [ AS literal-2 ] }
             {                             ~~             }
             { intrinsic-function-name-2 INTRINSIC        }
             { ALL INTRINSIC             ~~~~~~~~~        }
               ~~~ ~~~~~~~~~
  1. TheREPOSITORYparagraph is not allowed in a nested subprogram — nested programs will inherit theREPOSITORYsettings of their parent program.
  2. TheINTRINSIC
  3. As an alternative to using theALL INTRINSIC
  4. The <function-prototype-name-1> option is required to specify the name of a user-defined function your program will be using. Optionally, should you desire, you may specify an alias name by which you will reference that user-defined function. Should you wish, you may also use theASclause to provide an alias name for a built-in intrinsic function.
  5. The following example enables all intrinsic functions to be specified without the use of theFUNCTIONkeyword, (2) names two user-defined functions named "MY-FUNCTION-1" and "MY-FUNCTION-2" that will be used by the program and (3) specifies the alias names "SIGMA" for the intrinsic function "STANDARD-DEVIATION" and "MF2" for "MY-FUNCTION-2".
    REPOSITORY.
        FUNCTION ALL INTRINSIC.
        FUNCTION MY-FUNCTION-1.
        FUNCTION MY-FUNCTION-2 AS "MF2".
        FUNCTION STANDARD-DEVIATION AS "SIGMA".
    

A special note about user-defined functions — because you must name a user-defined function that your program will be using in theREPOSITORYparagraph, you may always reference that function from your program’s procedure division without needing to use theFUNCTIONkeyword.

4.2. INPUT-OUTPUT SECTION

INPUT-OUTPUT SECTION Syntax

 [ INPUT-OUTPUT SECTION. ]
   ~~~~~~~~~~~~ ~~~~~~~
 [ FILE-CONTROL. ]
   ~~~~~~~~~~~~
     [ SELECT-Statement... ]

 [ I-O-CONTROL. ]
   ~~~~~~~~~~~
     [ MULTIPLE-FILE-Statement ]

     [ SAME-RECORD-Statement ]
  1. As the diagram shows, there are three types of statements that may occur in the two paragraphs of this section. If none of the statements are coded in a particular paragraph, the paragraph itself may be omitted, otherwise it is required.
  2. If neither paragraph is coded, theINPUT-OUTPUT SECTION.header itself may be omitted, otherwise it is normally required.
  3. If the compiler "config" file you are using has "relaxed-syntax-check" set to "yes", theFILE-CONTROLandI-O-CONTROLparagraphs may be specified without theINPUT-OUTPUT SECTION.header having been coded.
  4. If both statement types are coded in theI-O-CONTROLparagraph, the order in which those statements are coded is irrelevant.

4.2.1. SELECT

SELECT Statement Syntax

 SELECT [ [ NOT ] OPTIONAL ] file-name-1
 ~~~~~~     ~~~   ~~~~~~~~
 [ ASSIGN { TO    } [{ EXTERNAL }] [{ DISC|DISK      }] [{ identifier-1 }] ]
   ~~~~~~ { USING }  { ~~~~~~~~ }   { ~~~~ ~~~~      }   { word-1       }
                     { DYNAMIC  }   { DISPLAY        }   { literal-1    }
                       ~~~~~~~      { ~~~~~~~        }
                                    { KEYBOARD       }
                                    { ~~~~~~~~       }
                                    { LINE ADVANCING }
                                    { ~~~~ ~~~~~~~~~ }
                                    { PRINTER        }
                                    { ~~~~~~~        }
                                    { RANDOM         }
                                    { ~~~~~~         }
                                    { TAPE           }
                                      ~~~~
 [ COLLATING SEQUENCE IS alphabet-name-1 ]
   ~~~~~~~~~
 [ FILE|SORT ] STATUS IS identifier-2 [ identifier-3 ] ]
   ~~~~ ~~~~   ~~~~~~
 [ LOCK MODE IS { MANUAL|AUTOMATIC                                } ]
   ~~~~         { ~~~~~~ ~~~~~~~~~                                }
                { EXCLUSIVE [ WITH { LOCK ON MULTIPLE RECORDS } ] }
                  ~~~~~~~~~        { ~~~~ ~~ ~~~~~~~~ ~~~~~~~ }
                                   { LOCK ON RECORD           }
 [ ORGANIZATION-Clause ]           { ~~~~ ~~ ~~~~~~           }
                                   { ROLLBACK                 }
 [ RECORD DELIMITER IS STANDARD-1 ]  ~~~~~~~~
   ~~~~~~ ~~~~~~~~~    ~~~~~~~~~~
 [ RESERVE integer-1 AREAS ]
   ~~~~~~~
 [ SHARING WITH { ALL OTHER } ]
   ~~~~~~~      { ~~~       }
                { NO OTHER  }
                { ~~        }
                { READ ONLY }
                  ~~~~ ~~~~

TheCOLLATING SEQUENCE

TheSELECTstatement creates a definition of a file and links that COBOL definition to the external operating system environment.

  1. The reserved wordsAREASISMODEOTHERSEQUENCETOUSINGandWITHare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. After <file-name-1>, the various clauses may be coded in any sequence.
  3. A period must follow the last coded clause.
  4. TheOPTIONAL
  5. The <file-name-1> value that you specify will be the name by which you will reference the file within your program. This name should be formed according to the rules for user-defined names (see User-Defined Words).
  6. The optionalASSIGNclause specifies how — at runtime, when <file-name-1> is opened — either a logical device (STDIN, STDOUT) or a file anywhere in one of the currently-mounted file systems will be associated with <file-name-1>, as follows:
    1. There are three components to theASSIGNclause — a <<Type>> specification EXTERNALDYNAMICor neither), a <<Device>> (the list of device choices) and a <<Locator>> (shown as a choice between <identifier-1>, <word-1> and <literal-1>).
    2. ASSIGN TO DISC '<file-name-1>'will be assumed if there is noASSIGNclause on aSELECT
    3. If anASSIGNclause is coded without a <<Device>>, the deviceDISCwill be assumed.
    4. If a <<Locator>> clause is coded, the COBOL file <file-name-1> will be attached to a data file within any file system that is mounted and available to the executing program at the time <file-name-1> is opened. How that file is identified varies, depending upon the specified <<Locator>>, as follows:
      1. If <literal-1> is coded, the value of the literal will serve as the File Location String that will identify the data file.
      2. If <identifier-1> is coded, the value of the identifier will serve as the File Location String that will identify the data file.
      3. If <word-1> (a syntactically valid word not duplicating that of a reserved or user-defined word) is coded, and a <<Type>> ofEXTERNALis specified, <word-1> itself will serve as the File Location String that will identify the data file. If, however, a <<Type>> ofEXTERNALwas not specified, the compiler will create aPIC X(1024)data item named <word-1> within the program; the contents of that data item at the time the program opens <file-name-1> will then serve as the File Location String that will identify the data file.
      4. File Location Strings will be discussed shortly.
    5. If no <<Locator>> is coded, <file-name-1> will be attached to a logical device or a file based upon the specified (or implied) <<Device>>, as follows:
      1. DISCorDISKwill assume an attachment to a file named <file-name-1> in whatever directory is current at the time the file is opened.
      2. DISPLAYwill assume an attachment to theSTDOUTlogical device; these files should only be used for output.
      3. KEYBOARDwill assume an attachment to theSTDINlogical device; these files should only be used for input.
      4. PRINTERwill assume an attachment to theLPT1logical device/port; these files should only be used for output.
      5. RANDOMorTAPEwill behave exactly asDISCdoes. These two additional <<Device>>s are provided to facilitate the compilation of COBOL source from other COBOL implementations.
    6. TheLINE ADVANCINGdevice requires that a <<Locator>> be specified; these files should only be used for output. A COBOL Line Advancing file will allow carriage-control characters such as line-feeds and form-feeds to be written to the attached operating system file, via theADVANCINGclause of theWRITEstatement (see WRITE).
    7. File Location Strings are used (at runtime) to identify the path and filename to the data file that must be attached to <file-name-1> when that file is opened.
    8. If the compiler "config" file you used to compile the program with had a "filename-mapping" value of "yes", the GnuCOBOL runtime system will first attempt to identify a currently-defined environment variable whose value will serve as the data file’s path and filename, as follows:
      1. If the compiler "config" file (see Compiler Configuration Files) you used to compile the program specified "mf" as the "assign-clause" value, then the File Locator String will be interpreted according to Microfocus COBOL rules — namely, everything before the last "-" in the File Locator String will be ignored; the characters after the last "-" will be treated as the base of an environment variable name. If there is no "-" character in the File Locator String then the entire File Locator String will serve as the base of an environment variable name. This is the default behaviour for every config file except "ibm".
      2. If, on the other hand, the compiler "config" file you used to compile the program specified "mf" as the "assign-clause" value, then the File Locator String will be interpreted according to according to IBM COBOL rules — namely, the File Locator String is expected to be of the form "S-xxx" or "AS-xxx", in which case the "xxx" will be treated as the base of an environment variable name. If there is no "-" character in the File Locator String then the entire File Locator String will serve as the base of an environment variable name.
      3. Once an environment variable name base (let’s refer to it as "bbbb") has been determined, the runtime system will look for the first one of the following environment variables that exists, in this sequence:
        DD_bbbb
        dd_bbbb
        bbbb
        

        Windows systems are case-insensitive with regard to environment variables, so there is no difference between the first two when using a GnuCOBOL implementation built for either Windows/MinGW or native Windows.

        If an environment variable was found, it’s value will serve as the path and filename to the data file.

    9. If no environment variable was found, or the "config" file used to compile the program had a "filename-mapping" value of "no", then the File Locator String value will serve as the path and filename to the data file.
    10. Paths and file names may be specified on an absolute C:\Data\datafile.dat/Data/datafile.dat …) or relative-to-the-current-directory Data\datafile.datData/datafile.dat …) basis.

      There may not even be a path datafile.dat, in which case the file must be in the current directory.

  7. TheFILE STATUS
    Code Explanation
    00 Success
    02 Success (Duplicate Record Key Written)
    05 Success (Optional File Not Found)
    07 Success (No Unit)
    10 End of file reached if reading forward or beginning-of-file reached if reading backward
    14 Out of key range
    21 Key invalid
    22 Attempt to duplicate key value
    23 Key not found
    30 Permanent I/O error
    31 Inconsistent filename
    34 Boundary violation
    35 File not found
    37 Permission denied
    38 Closed with lock
    39 Conflicting attribute
    41 File already open
    42 File not open
    43 Read not done
    44 Record overflow
    46 Read error
    47 OPEN INPUTdenied (insufficient permissions to read file)
    48 OPEN OUTPUTdenied (insufficient permissions to write to file)
    49 OPEN I-Odenied (insufficient permissions to read and/or write file)
    51 Record locked
    52 End of page
    57 LINAGEspecifications invalid
    61 File sharing failure
    91 File not available
  8. TheSHARING
  9. TheLOCK
  10. ASELECTstatement without anORGANIZATIONexplicitly coded will be handled as if the following ORGANIZATION clause had been specified:
    ORGANIZATION IS SEQUENTIAL
        ACCESS MODE IS SEQUENTIAL
    

4.2.1.1. ORGANIZATION SEQUENTIAL

ORGANIZATION SEQUENTIAL Clause Syntax

 [ ORGANIZATION|ORGANISATION IS ] RECORD BINARY SEQUENTIAL
   ~~~~~~~~~~~~ ~~~~~~~~~~~~                    ~~~~~~~~~~
    [ ACCESS MODE IS SEQUENTIAL ]
      ~~~~~~         ~~~~~~~~~~
  1. The reserved wordsBINARYISMODEandRECORDare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsORGANIZATIONandORGANISATIONare interchangeable.
  3. The phraseORGANIZATION IS(and it’s internationalized alternative,ORGANISATION IS is optional to provide compatibility with those (few) COBOL implementations that considerORGANIZATIONto be optional. Most COBOL implementations do require the wordORGANIZATION so it should be used in new programs.
  4. These files cannot be prepared with any standard text-editing or word processing software as all such programs will embed delimiter characters at the end of records (useORGANIZATION IS LINE SEQUENTIALinstead).
  5. These files may contain eitherUSAGE DISPLAYorUSAGE COMPUTATIONAL(of any variety) data since no binary data sequence can be accidentally interpreted as an end-of-record delimiter.
  6. While records in aORGANIZATION SEQUENTIALfile may be defined as having variable-length records, the file will be structured in such a manner as to reserve space for each record equal to the size of the largest possible record, based on the file’s description in theFILE SECTION
  7. TheACCESS MODE SEQUENTIAL
  8. Sequential files are processed using the following statements:

4.2.1.2. ORGANIZATION LINE SEQUENTIAL

ORGANIZATION LINE SEQUENTIAL Clause Syntax

 [ ORGANIZATION|ORGANISATION IS ] LINE SEQUENTIAL
   ~~~~~~~~~~~~ ~~~~~~~~~~~~      ~~~~ ~~~~~~~~~~
    [ ACCESS MODE IS SEQUENTIAL ]
      ~~~~~~         ~~~~~~~~~~
    [ PADDING CHARACTER IS literal-1 | identifier-1 ]
      ~~~~~~~

ThePADDING CHARACTERclause is syntactically recognized but is otherwise non-functional.

  1. The reserved wordsCHARACTERISandMODEare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsORGANIZATIONandORGANISATIONare interchangeable.
  3. The phraseORGANIZATION IS(and it’s internationalized alternative,ORGANISATION IS is optional to provide compatibility with those (few) COBOL implementations that consider that word to be optional. Most COBOL implementations do require the wordORGANIZATION so it should be used in new programs.
  4. This is the onlyORGANIZATIONvalid for files that are assigned to thePRINTERdevice.
  5. These files may be created with any standard text-editing or word processing software capable of writing text files. Such files should not contain anyUSAGE COMPUTATIONALorBINARY(of any variety) data since such fields could accidentally contain byte sequences that could be interpreted as an end-of-record delimiter.
  6. Both fixed- and variable-length record formats are supported.
  7. The end-of-record delimiter sequence will be X’0A’ (an ASCII line-feed character) or a X’0D0A’ (an ASCII carriage-return + line-feed sequence). The former is used on Unix implementations of GnuCOBOL (including Windows/MinGW, Windows/Cygwin and OSX implementations) while the latter would be used with native Windows implementations.
  8. When reading aLINE SEQUENTIALfile, records in excess of the size implied by the file’s description in theFILE SECTIONwill be truncated while records shorter than that size will be padded to the right withSPACES
  9. TheACCESS MODE SEQUENTIAL
  10. Files assigned toPRINTERorCONSOLEshould be specified asORGANIZATION LINE SEQUENTIAL
  11. Line Sequential files are processed using the following statements:

4.2.1.3. ORGANIZATION RELATIVE

ORGANIZATION RELATIVE Clause Syntax

 [ ORGANIZATION|ORGANISATION IS ] RELATIVE
   ~~~~~~~~~~~~ ~~~~~~~~~~~~      ~~~~~~~~
    [ ACCESS MODE IS { SEQUENTIAL } ]
      ~~~~~~         { ~~~~~~~~~~ }
                     { DYNAMIC    }
                     { ~~~~~~~    }
                     { RANDOM     }
                       ~~~~~~
    [ RELATIVE KEY IS identifier-1 ]
      ~~~~~~~~
  1. The reserved wordsISKEYandMODEare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsORGANIZATIONandORGANISATIONare interchangeable.
  3. The phraseORGANIZATION IS(and it’s internationalized alternative,ORGANISATION IS is optional to provide compatibility with those (few) COBOL implementations that consider that word to be optional. Most COBOL implementations do require the wordORGANIZATION so it should be used in new programs.
  4. ORGANIZATION RELATIVEfiles cannot be assigned to theCONSOLEDISPLAYLINE ADVANCINGorPRINTERdevices.
  5. TheRELATIVE KEY
  6. While anORGANIZATION RELATIVEfile may be defined as having variable-length records, the file will be structured in such a manner as to reserve space for each record equal to the size of the largest possible record as defined by the file’s description in theFILE SECTION
  7. ACCESS MODE SEQUENTIAL the defaultACCESS MODEif none is specified, indicates that the records of the file will be processed in a sequential manner, according to their physical sequence in the file.
  8. ACCESS MODE RANDOM
  9. ACCESS MODE DYNAMIC
  10. TheRELATIVE KEY
  11. Relative files are processed using the following statements:

4.2.1.4. ORGANIZATION INDEXED

ORGANIZATION INDEXED Clause Syntax

 [ ORGANIZATION|ORGANISATION IS ] INDEXED
   ~~~~~~~~~~~~ ~~~~~~~~~~~~      ~~~~~~~
    [ ACCESS MODE IS { SEQUENTIAL } ]
      ~~~~~~         { ~~~~~~~~~  }
                     { DYNAMIC    }
                     { ~~~~~~~    }
                     { RANDOM     }
                       ~~~~~~
    [ RECORD KEY IS identifier-1
      ~~~~~~
          [ =|{SOURCE IS} identifier-2 ] ]
               ~~~~~~
    [ ALTERNATE RECORD KEY IS identifier-3
      ~~~~~~~~~ ~~~~~~
          [ =|{SOURCE IS} identifier-4 ]
               ~~~~~~
          [ WITH DUPLICATES ] ]...
                 ~~~~~~~~~~

TheSOURCEclause is syntactically recognized but is otherwise non-functional. It is supported to provide compatibility with COBOL source written for other COBOL implementations.

  1. The reserved wordsISKEYandMODEare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsORGANIZATIONandORGANISATIONare interchangeable.
  3. The phraseORGANIZATION IS(and it’s internationalized alternative,ORGANISATION IS is optional to provide compatibility with those (few) COBOL implementations that consider that word to be optional. Most COBOL implementations do require the wordORGANIZATION so it should be used in new programs.
  4. ORGANIZATION INDEXEDfiles cannot be assigned toCONSOLEDISPLAYKEYBOARDLINE ADVANCINGorPRINTER
  5. ACCESS MODE SEQUENTIAL
  6. ACCESS MODE RANDOM
  7. ACCESS MODE DYNAMIC
  8. ThePRIMARY KEY
  9. TheALTERNATE RECORD KEY
  10. There may be multipleALTERNATE RECORD KEYclauses, each defining an additional alternate key for the file.
  11. Indexed files are processed using the following statements:

4.2.2. SAME RECORD AREA

I-O-CONTROL SAME AREA Syntax

 SAME { SORT-MERGE } AREA FOR file-name-1... .
 ~~~~ { ~~~~~~~~~~ }
      { SORT       }
      { ~~~~       }
      { RECORD     }
        ~~~~~~

TheSAME SORT-MERGE

  1. The reserved wordsAREAandFORare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. This statement must be terminated with a period.
  3. While coding only a single file name (the repeated <file-name-1> item) is syntactically valid, this statement will have no effect upon the program unless at least two files are specified.
  4. The effect of this statement will be to cause the specified files to share the same I/O buffer in memory. These buffers can sometimes get quite large, and by having multiple files share the same buffer memory you may significantly cut down the amount of memory the program is using (thus making "room" for more procedural code or data). If you do use this feature, take care to ensure that no more than one of the specified files are ever OPEN simultaneously.

4.2.3. MULTIPLE FILE

I-O-CONTROL MULTIPLE FILE Syntax

 MULTIPLE FILE TAPE CONTAINS
 ~~~~~~~~
    { file-name-1 [ POSITION integer-1 ] }...
                    ~~~~~~~~
    .

TheMULTIPLE FILE TAPEclause is obsolete and is therefore recognized but not functional.

5. DATA DIVISION

DATA DIVISION Syntax

   DATA DIVISION.
   ~~~~ ~~~~~~~~
 [ FILE SECTION.
   ~~~~ ~~~~~~~
   { File/Sort-Description [ { FILE-SECTION-Data-Item } ]... }... ]
   {                         { 01-Level-Constant      }      }
   {                         { 78-Level-Constant      }      }
   { 01-Level-Constant                                       }
   { 78-Level-Constant                                       }
 [ WORKING-STORAGE SECTION.
   ~~~~~~~~~~~~~~~ ~~~~~~~
   [ { WORKING-STORAGE-SECTION-Data-Item } ]... ]
     { 01-Level-Constant                 }
     { 78-Level-Constant                 }
 [ LOCAL-STORAGE SECTION.
   ~~~~~~~~~~~~~ ~~~~~~~
   [ { LOCAL-STORAGE-SECTION-Data-Item } ]... ]
     { 01-Level-Constant               }
     { 78-Level-Constant               }
 [ LINKAGE SECTION.
   ~~~~~~~ ~~~~~~~
   [ { LINKAGE-SECTION-Data-Item } ]... ]
     { 01-Level-Constant         }
     { 78-Level-Constant         }
 [ REPORT SECTION.
   ~~~~~~ ~~~~~~~
   { Report-Description [ { Report-Group-Definition } ]... }... ]
   {                      { 01-Level-Constant       }      }
   {                      { 78-Level-Constant       }      }
   { 01-Level-Constant                                     }
   { 78-Level-Constant                                     }
 [ SCREEN SECTION.
   ~~~~~~ ~~~~~~~
   [ { SCREEN-SECTION-Data-Item } ]... ]
     { 01-Level-Constant        }
     { 78-Level-Constant        }
  1. If no data will be described in one of the data division sections, that section header may be omitted.
  2. If no data division sections are needed, theDATA DIVISION.header itself may be omitted.
  3. If more than one section is needed in the data division (a common situation), the sections must be coded in the sequence they are presented above.

5.1. Data Definition Principles

TheEmployeedata item consists of two subordinate data items — anEmployee-Nameand anEmployment-Datesdata item (presumably there would be a lot of others too, but we don’t care about them right now). As the diagram shows, each of those data items are, in turn, broken down into subordinate data items. This hierarchy of data items can get ratherdeep and GnuCOBOL, like other COBOL implementations, can handle up to 49 levels of such hierarchical structures.

As was presented earlier (see Structured Data), a data item that is broken down into other data items is referred to as a group item, while one that isn’t broken down is called an elementary item.

COBOL uses the concept of a "level number" to indicate the level at which a data item occurs in a data structure such as the example shown above. When these data items are defined, they are all defined together with a number in the range 1-49 specified in front of their names. Over the years, a convention has come to exist among COBOL programmers that level numbers are always coded as two-digit numbers — they don’t have to be specified as two-digit numbers, but every example you see in this document will take that approach!

The data item at the top, also referred to as a "record", always has a level number of 01. After that, you may assign level numbers as you wish (01–02–03–04…, 01–05–10–15…, etc.), as long as you follow these simple rules:

  1. Every data item at the samelevelof a hierarchy diagram such as the one you see here (if you were to make one, which you rarely — if ever — will, once you get used to this concept) must have the same level number.
  2. Every new level uses a level number that is strictly greater than the one used in the parent (next higher) level.
  3. When describing data hierarchies, you may never use a level number greater than 49 (except for 66, 77, 78 and 88 which have very special meanings — see see Special Data Items).

So, the definition of these data items in a GnuCOBOL program would go something like this:

    01  Employee
        05 Employee-Name
           10 Last-Name
           10 First-Name
           10 Middle-Initial
        05 Employment-Dates
           10 From-Date
              15 Year
              15 Month
              15 Day
           10 To-Date
              15 Year
              15 Month
              15 Day

The indentation is purely at the discretion of the programmer to make things easier for humans to read (the compiler couldn’t care less). Historically, COBOL implementations that required Fixed Format Mode source programs required that the01level number begin in Area A and that everything else begins in Area B. GnuCOBOL only requires that all data definition syntax occur in columns 8-72. In Free Format Mode, of course, there aren’t even those limitations.

Did you notice that there are two each ofYearMonthandDaydata names defined? That’s perfectly legal, provided that each can be uniquelyqualifiedso as to be distinct from the other. Take for example theYearitems. One is defined as part of theFrom-Datedata item while the other is defined as part of the "To-Date" data item. In COBOL, we would actually code references to these two data items as eitherYear OF From-DateandYear OF To-DateorYear IN From-DateandYear IN To-Date(COBOL allows eitherINorOFto be used). Since these references would clarify any confusion to us as to whichYearmight be referenced, the GnuCOBOL compiler won’t be confused either.

The coding example shown above is incomplete — it only describes the data item names and their hierarchical relationships to one other. In addition, any valid data item definitions will also need to describe what type of data is to be contained in a data item (Numeric? Alphanumeric? Alphabetic?), how much data can be held in the data item and a multitude of other characteristics.

When group items are being defined, subordinate items may be assigned anameofFILLER

5.2. FILE SECTION

FILE SECTION Syntax

 [ FILE SECTION.
   ~~~~ ~~~~~~~
   { File/Sort-Description [ { FILE-SECTION-Data-Item } ]... }... ]
   {                         { 01-Level-Constant      }      }
   {                         { 78-Level-Constant      }      }
   { 01-Level-Constant                                       }
   { 78-Level-Constant                                       }

Files destined for use as sort/merge work files must be described with a Sort/Merge File Description SD while every other file is described with a File Description FD. Each of these descriptions will almost always be followed with at least one record description.

5.2.1. File/Sort-Description

File/Sort-Description Syntax

 FD|SD file-name-1 [ IS EXTERNAL|GLOBAL ]
 ~~ ~~                  ~~~~~~~~ ~~~~~~
 [ BLOCK CONTAINS [ integer-1 TO ] integer-2 CHARACTERS|RECORDS ]
   ~~~~~                      ~~             ~~~~~~~~~~ ~~~~~~~
 [ CODE-SET IS alphabet-name-1 ]
   ~~~~~~~~
 [ DATA { RECORD IS   } identifier-1... ]
   ~~~~ { ~~~~~~      }
        { RECORDS ARE }
          ~~~~~~~
 [ LABEL { RECORD IS   } OMITTED|STANDARD ]
   ~~~~~ { ~~~~~~      } ~~~~~~~ ~~~~~~~~
         { RECORDS ARE }
           ~~~~~~~
 [ LINAGE IS integer-3 | identifier-2 LINES
   ~~~~~~
     [ LINES AT BOTTOM integer-4 | identifier-3 ]
                ~~~~~~
     [ LINES AT TOP integer-5 | identifier-4 ]
                ~~~
     [ WITH FOOTING AT integer-6 | identifier-5 ] ]
            ~~~~~~~
 [ RECORD { CONTAINS [ integer-7 TO ] integer-8 CHARACTERS   } ]
   ~~~~~~ {                      ~~                          }
          { IS VARYING IN SIZE                               }
          {    ~~~~~~~                                       }
          {     [ FROM [ integer-7 TO ] integer-8 CHARACTERS }
          {                        ~~                        }
          {         DEPENDING ON identifier-6 ]              }
                    ~~~~~~~~~
 [ RECORDING MODE IS recording-mode ]
   ~~~~~~~~~
 [ { REPORT IS   } report-name-1... ]
   { ~~~~~~      }
   { REPORTS ARE }
     ~~~~~~~
 [ VALUE OF implementor-name-1 IS literal-1 | identifier-7 ] .
   ~~~~~ ~~

TheBLOCK CONTAINS

  1. The reserved wordsAREATCHARACTERSRECORDclause only),CONTAINSFROMINISONandWITHare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The termsRECORD ISandRECORDS AREare interchangeable.
  3. The termsREPORT ISandREPORTS AREare interchangeable.
  4. Only files intended for use as work files for either theSORT(see SORT) orMERGE(see MERGE) statements should be coded with an SD — all others should be defined with a FD.
  5. The sequence in which files are defined viaFDorSD as compared to the sequence in which theirSELECTstatements were coded, is irrelevant.
  6. The name specified as <file-name-1> must exactly match the name specified on the file’sSELECTstatement.
  7. TheCODE-SET
  8. TheLINAGEclause may only be specified in theFDof a sequential or line sequential file. If used with a sequential file, the organization of that file will be implicitly changed to line sequential. The various components of theLINAGEclause define the layout of printed pages as follows:
    • LINES AT TOP
    • LINES AT BOTTOM
    • LINAGE IS n LINES
    • The sum of the previous three specifications should be the total number of possible lines available on one printed page.
    • FOOTING AT
  9. This page structure — once defined — can be automatically enforced by theWRITEstatement (see WRITE).
  10. Specifying aLINAGEclause in anFDwill cause theLINAGE-COUNTERspecial register to be created for the file. This automatically-created data item will always contain the current relative line number on the page being prepared which will serve as the starting point for aWRITEstatement.
  11. TheRECORD CONTAINS
  12. TheREPORT IS
    1. The clause may only be specified in theFDof a sequential or line sequential file. If used with a sequential file, the organization of that file will be implicitly changed to line sequential.
    2. TheFDcannot be followed by record descriptions — detailed descriptions of data to be printed to the file will be defined in theREPORT SECTION(see REPORT SECTION).
    3. If aLINAGEclause is also specified, Values specified forLINAGE ISandFOOTING ATwill be ignored. The values ofLINES AT BOTTOMandLINES AT TOP if any, will be honoured.
  13. The following special rules apply only to sort/merge work files:
    1. Sort/merge work files should be assigned toDISK(orDISC on theirSELECTstatements.
    2. Sorts and merges will be performed in memory, if the amount of data being sorted allows.
    3. Should actual disk work files be necessary due to the amount of data being sorted or merged, they will be automatically allocated to disk in a folder defined by:
      • The
      • The
      • The

      (in that order)

    4. These disk files will be automatically purged uponSORTorMERGEtermination. They will also be purged if the program terminates abnormally before theSORTorMERGEfinishes. Should you ever need to know, temporary sort/merge work files will be named "cob*.tmp".
    5. If you specify a specific filename in the sort/merge work file’sSELECT it will be ignored.
  14. See Data Description Clauses, for information on theEXTERNALandGLOBALoptions.

5.2.2. FILE-SECTION-Data-Item

FILE-SECTION-Data-Item Syntax

 level-number [ identifier-1 | FILLER ] [ IS GLOBAL|EXTERNAL ]
                               ~~~~~~        ~~~~~~ ~~~~~~~~
 [ BLANK WHEN ZERO ]
   ~~~~~      ~~~~
 [ JUSTIFIED RIGHT ]
   ~~~~
 [ OCCURS [ integer-1 TO ] integer-2 TIMES
   ~~~~~~             ~~
        [ DEPENDING ON identifier-2 ]
          ~~~~~~~~~
        [ ASCENDING|DESCENDING KEY IS identifier-3 ]
          ~~~~~~~~~ ~~~~~~~~~~
        [ INDEXED BY identifier-4 ] ]
          ~~~~~~~
 [ PICTURE IS picture-string ]
   ~~~
 [ REDEFINES identifier-5 ]
   ~~~~~~~~~
 [ SIGN IS LEADING|TRAILING [ SEPARATE [CHARACTER] ] ]
   ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
 [ SYNCRONIZED|SYNCHRONISED [ LEFT|RIGHT ] ]
   ~~~~        ~~~~           ~~~~ ~~~~~
 [ USAGE IS data-item-usage ] . [ FILE-SECTION-Data-Item ]...
   ~~~~~

TheLEFTandRIGHT(SYNCRONIZED) clauses are syntactically recognized but are otherwise non-functional.

  1. The reserved wordsBYISKEYONandWHENare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsSYNCRONIZEDandSYNCRONIZEDare interchangeable. Both may be abbreviated toSYNC
  3. The reserved wordPICTUREmay be abbreviated toPIC
  4. As the syntax diagram shows, the definition of a <<FILE-SECTION-Data-Item>> is a recursive one in that there may be any number of such specifications coded following a FD or SD. The first such specification must have a level number of 01, and will describe a specific format of data record within the file. Specifications that follow that one may have level numbers greater than 01, in which case they are defining a hierarchical breakdown of the record. The definition of a record is terminated when one of the following occurs:
    • Another 01-level item is found — this signifies the start of another record layout for the file.
    • AnotherFDorSDis found — this marks the completion of the detailed description of the file and begins another.
    • A division or section header is found — this also marks the completion of the detailed description of the file and signifies the end of the file section as well.
  5. Every <<FILE-SECTION-Data-Item>> description must be terminated with a period.
  6. If there are multiple record descriptions present for a givenFDorSD the one with the longest length will define the size of the record buffer into which aREADstatement (see READ) or aRETURNstatement (see RETURN) will deliver data read from the file and from which aWRITEstatement (see WRITE) orRELEASEstatement (see RELEASE) statement will obtain the data to be written to the file.
  7. The various 01-level record descriptions for a file description implicitly share that one common record buffer (thus, they provide different ways to view the structure of data that can exist within the file). Record buffers can be shared between files by using theSAME RECORD AREA(see SAME RECORD AREA) clause.
  8. The only valid level numbers are 01-49, 66, 77, 78 and 88. Level numbers 66, 77, 78 and 88 all have special uses — See Special Data Items, for details.
  9. Not specifying an <identifier-1> orFILLERimmediately after the level number has the same effect as ifFILLERwere specified. A data item namedFILLERcannot be referenced directly; these items are generally used to specify an unused portion of the total storage allocated to a group item or to describe a group item whose contents which will only be referenced using the names of those items that belong to it.
  10. EXTERNALcannot be combined withGLOBALorREDEFINES
  11. File section data buffers (and therefore all 01-level record layouts defined in the file section) are initialized to all binary zeros when the program is loaded into storage.
  12. See Data Description Clauses, for information on the usage of the various data description clauses.

5.3. WORKING-STORAGE SECTION

WORKING-STORAGE-SECTION-Data-Item Syntax

 level-number [ identifier-1 | FILLER ] [ IS GLOBAL | EXTERNAL ]
                               ~~~~~~        ~~~~~~   ~~~~~~~~
 [ BASED ]
   ~~~~~
 [ BLANK WHEN ZERO ]
   ~~~~~      ~~~~
 [ JUSTIFIED RIGHT ]
   ~~~~
 [ OCCURS [ integer-1 TO ] integer-2 TIMES
   ~~~~~~             ~~
       [ DEPENDING ON identifier-2 ]
         ~~~~~~~~~
       [ ASCENDING|DESCENDING KEY IS identifier-3 ]
         ~~~~~~~~~ ~~~~~~~~~~
       [ INDEXED BY identifier-4 ] ]
         ~~~~~~~
 [ PICTURE IS picture-string ]
   ~~~
 [ REDEFINES identifier-5 ]
   ~~~~~~~~~
 [ SIGN IS LEADING|TRAILING [ SEPARATE CHARACTER ] ]
   ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
 [ SYNCRONIZED|SYNCHRONISED [ LEFT|RIGHT ] ]
   ~~~~        ~~~~           ~~~~ ~~~~~
 [ USAGE IS data-item-usage ]
   ~~~~~
 [ VALUE IS [ ALL ] literal-1 ] . [ WORKING-STORAGE-SECTION-Data-Item ]...
   ~~~~~      ~~~

TheLEFTandRIGHT(SYNCRONIZED) clauses are syntactically recognized but are otherwise non-functional.

  1. The reserved wordsBYCHARACTERISKEYONRIGHT(JUSTIFIED),TIMESandWHENare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsSYNCRONIZEDandSYNCHRONISEDare interchangeable. Both may be abbreviated asSYNC
  3. The reserved wordPICTUREmay be abbreviated toPIC
  4. The reserved wordJUSTIFIEDmay be abbreviated toJUST
  5. As the syntax diagram shows, the definition of a <<WORKING-STORAGE-SECTION-Data-Item>> is a recursive one in that there may be any number of such specifications coded following one another. The first such specification must have a level number of 01. Specifications that follow that one may have level numbers greater than 01, in which case they are defining a hierarchical breakdown of a record. The definition of a record is terminated when one of the following occurs:
    • Another 01-level item is found — this signifies the end of the definition of one record and the start of a another.
    • A 77-level item is found — this signifies the end of the definition of the record and begins the definition of a special data item; See 77-Level Data Items, for more information.
    • A division or section header is found — this also marks the completion of a record and signifies the end of the working-storage section as well.
  6. Every <<WORKING-STORAGE-SECTION-Data-Item>> description must be terminated with a period.
  7. The only valid level numbers are 01-49, 66, 77, 78 and 88. Level numbers 01 through 49 are used to define data items that may be part of a hierarchical structure. Level number 01 can also be used to define a constant — an item with an unchangeable value specified at compilation time.
  8. Level numbers 66, 77, 78 and 88 all have special uses — See Special Data Items, for details.
  9. Not specifying an <identifier-1> orFILLERimmediately after the level number has the same effect as ifFILLERwere specified. A data item namedFILLERcannot be referenced directly; these items are generally used to specify an unused portion of the total storage allocated to a group item or to describe a group item whose contents which will only be referenced using the names of those items that belong to it.
  10. Data items defined within the working-storage section are automatically initialized once — as the program in which the data is defined is loaded into memory. Subprograms may be loaded into memory more than once (see theCANCELstatement (see CANCEL)), in which case initialization will happen each time they are loaded. See Data Initialization, for a discussion of the initialization rules.
  11. See Data Description Clauses, for information on the usage of the various data description clauses.

5.4. LOCAL-STORAGE SECTION

LOCAL-STORAGE-SECTION-Data-Item Syntax

 level-number [ identifier-1 | FILLER ] [ IS GLOBAL|EXTERNAL ]
                               ~~~~~~        ~~~~~~ ~~~~~~~~
 [ BASED ]
   ~~~~~
 [ BLANK WHEN ZERO ]
   ~~~~~      ~~~~
 [ JUSTIFIED RIGHT ]
   ~~~~
 [ OCCURS [ integer-1 TO ] integer-2 TIMES
   ~~~~~~             ~~
       [ DEPENDING ON identifier-2 ]
         ~~~~~~~~~
       [ ASCENDING|DESCENDING KEY IS identifier-3 ]
         ~~~~~~~~~ ~~~~~~~~~~
       [ INDEXED BY identifier-4 ] ]
         ~~~~~~~
 [ PICTURE IS picture-string ]
   ~~~
 [ REDEFINES identifier-5 ]
   ~~~~~~~~~
 [ SIGN IS LEADING|TRAILING [ SEPARATE CHARACTER ] ]
   ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
 [ SYNCRONIZED|SYNCHRONISED [ LEFT|RIGHT ] ]
   ~~~~        ~~~~           ~~~~ ~~~~~
 [ USAGE IS data-item-usage ]
   ~~~~~
 [ VALUE IS [ ALL ] literal-1 ] . [ LOCAL-STORAGE-SECTION-Data-Item ]...
   ~~~~~      ~~~

TheLEFTandRIGHT(SYNCRONIZED) clauses are syntactically recognized but are otherwise non-functional.

  1. The reserved wordsBYCHARACTERISKEYONRIGHT(JUSTIFIED),TIMESandWHENare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsSYNCRONIZEDandSYNCHRONISEDare interchangeable. Both may be abbreviated asSYNC
  3. The reserved wordPICTUREmay be abbreviated toPIC
  4. The reserved wordJUSTIFIEDmay be abbreviated toJUST
  5. As the syntax diagram shows, the definition of a <<LOCAL-STORAGE-SECTION-Data-Item>> is a recursive one in that there may be any number of such specifications coded following one another. The first such specification must have a level number of 01. Specifications that follow that one may have level numbers greater than 01, in which case they are defining a hierarchical breakdown of a record. The definition of a record is terminated when one of the following occurs:
    • Another 01-level item is found — this signifies the end of the definition of one record and the start of a another.
    • A division or section header is found — this also marks the completion of a record and signifies the end of the local-storage section as well.
  6. Every <<LOCAL-STORAGE-SECTION-Data-Item>> description must be terminated with a period.
  7. The only valid level numbers are 01-49, 66, 77, 78 and 88. Level numbers 01 through 49 are used to define data items that may be part of a hierarchical structure. Level number 01 can also be used to define a constant — an item with an unchangeable value specified at compilation time.
  8. Level numbers 66, 77, 78 and 88 all have special uses — See Special Data Items, for details.
  9. Not specifying an <identifier-1> orFILLERimmediately after the level number has the same effect as ifFILLERwere specified. A data item namedFILLERcannot be referenced directly; these items are generally used to specify an unused portion of the total storage allocated to a group item or to describe a group item whose contents which will only be referenced using the names of those items that belong to it.
  10. Local-storage cannot be used in nested subprograms.
  11. See Data Description Clauses, for information on the usage of the various data description clauses.

5.5. LINKAGE SECTION

LINKAGE-SECTION-Data-Item Syntax

 level-number [ identifier-1 | FILLER ] [ IS GLOBAL|EXTERNAL ]
                               ~~~~~~        ~~~~~~ ~~~~~~~~
 [ ANY LENGTH ]
   ~~~ ~~~~~~
 [ BASED ]
   ~~~~~
 [ BLANK WHEN ZERO ]
   ~~~~~      ~~~~
 [ JUSTIFIED RIGHT ]
   ~~~~
 [ OCCURS [ integer-1 TO ] integer-2 TIMES
   ~~~~~~             ~~
       [ DEPENDING ON identifier-3 ]
         ~~~~~~~~~
       [ ASCENDING|DESCENDING KEY IS identifier-4 ]
         ~~~~~~~~~ ~~~~~~~~~~
       [ INDEXED BY identifier-5 ] ]
         ~~~~~~~
 [ PICTURE IS picture-string ]
   ~~~
 [ REDEFINES identifier-6 ]
   ~~~~~~~~~
 [ SIGN IS LEADING|TRAILING [ SEPARATE CHARACTER ] ]
   ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
 [ SYNCRONIZED|SYNCHRONISED [ LEFT|RIGHT ] ]
   ~~~~        ~~~~           ~~~~ ~~~~~
 [ USAGE IS data-item-usage ] . [ LINKAGE-SECTION-Data-Item ]...
   ~~~~~

TheLEFTandRIGHT(SYNCRONIZED) clauses are syntactically recognized but are otherwise non-functional.

  1. The reserved wordsBYCHARACTERISKEYONandWHENare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsSYNCRONIZEDand "SYNCHRONISED" are interchangeable. Both may be abbreviated asSYNC
  3. The reserved wordPICTUREmay be abbreviated toPIC
  4. The reserved wordJUSTIFIEDmay be abbreviated toJUST
  5. As the syntax diagram shows, the definition of a <<LINKAGE-SECTION-Data-Item>> is a recursive one in that there may be any number of such specifications coded following one another. The first such specification must have a level number of 01. Specifications that follow that one may have level numbers greater than 01, in which case they are defining a hierarchical breakdown of a record. The definition of a record is terminated when one of the following occurs:
    • Another 01-level item is found — this signifies the end of the definition of one record and the start of a another.
    • A division or section header is found — this also marks the completion of a record and signifies the end of the linkage section as well.
  6. Every <<LINKAGE-SECTION-Data-Item>> description must be terminated with a period.
  7. The only valid level numbers are 01-49, 66, 77, 78 and 88. Level numbers 01 through 49 are used to define data items that may be part of a hierarchical structure. Level number 01 can also be used to define a constant — an item with an unchangeable value specified at compilation time.
  8. Level numbers 66, 77, 78 and 88 all have special uses — See Special Data Items, for details.
  9. It is expected that:
    1. A linkage section should occur only within a subprogram. The compiler will not prevent its use in a main program, however.
    2. All 01-level data items described within a subprogram’s linkage section should appear in aPROCEDURE DIVISION USING(see PROCEDURE DIVISION USING) or as arguments on anENTRYstatement.
    3. Each 01-level data item described within a subprogram’s linkage section should correspond to an argument passed on aCALLstatement (see CALL) or an argument on a function call to the subprogram.
  10. Not specifying an <identifier-1> orFILLERimmediately after the level number has the same effect as ifFILLERwere specified. A data item namedFILLERcannot be referenced directly; these items are generally used to specify an unused portion of the total storage allocated to a group item or to describe a group item whose contents which will only be referenced using the names of those items that belong to it. In the linkage section, 01-level data items cannot be namedFILLER
  11. No storage is allocated for data defined in the linkage section; the data descriptions there are merely defining storage areas that will be passed to the subprogram by a calling program. Therefore, any discussion of the default initialization of such data is irrelevant. It is possible, however, to manually allocate linkage section data items that aren’t subprogram arguments via theALLOCATEstatement (see ALLOCATE) statement. In such cases, initialization will take place as per the documentation of that statement.
  12. See Data Description Clauses, for information on the usage of the various data description clauses.

5.6. REPORT SECTION

REPORT SECTION Syntax

 [ REPORT SECTION.
   ~~~~~~ ~~~~~~~
   { Report-Description [ { Report-Group-Definition } ]... }... ]
   {                      { 01-Level-Constant       }      }
   {                      { 78-Level-Constant       }      }
   { 01-Level-Constant                                     }
   { 78-Level-Constant                                     }

Report-Description (RD) Syntax

 RD report-name [ IS GLOBAL ]
 ~~                  ~~~~~~
 [ CODE IS literal-1 | identifier-1 ]
   ~~~~
 [ { CONTROL IS   } { FINAL        }... ]
   { ~~~~~~~      } { ~~~~~        }
   { CONTROLS ARE } { identifier-2 }
     ~~~~~~~~
 [ PAGE [ { LIMIT IS   } ] [ { literal-2    } LINES ]
   ~~~~   { ~~~~~      }     { identifier-3 } ~~~~
          { LIMITS ARE }
            ~~~~~~
       [ literal-3 | identifier-4 COLUMNS|COLS ]
                                  ~~~~~~~ ~~~~
       [ HEADING IS literal-4 | identifier-5 ]
         ~~~~~~~
       [ FIRST DE|DETAIL IS literal-5 | identifier-6 ]
         ~~~~~ ~~ ~~~~~~
       [ LAST CH|{CONTROL HEADING} IS literal-6 | identifier-7 ]
         ~~~~ ~~  ~~~~~~~ ~~~~~~~
       [ LAST DE|DETAIL IS literal-7 | identifier-8 ]
         ~~~~ ~~ ~~~~~~
       [ FOOTING IS literal-8 | identifier-9 ] ] .
         ~~~~~~~

TheCODE IS

  1. The reserved wordsAREandISare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The phrasesCONTROL ISandCONTROLS AREare interchangeable, as are thePAGE LIMITandPAGE LIMITSphrases.
  3. The reserved wordLINESmay be abbreviated asLINE
  4. The reserved wordCOLUMNSmay be abbreviated asCOLS
  5. Each report referenced on aREPORT ISclause (see File/Sort-Description) must be described with a report description RD.
  6. See GLOBAL, for information on theGLOBALoption.
  7. Please see Report Writer Features, if you have not read it already. This will familiarize you with the Report Writer terminology that will follow.
  8. The following rules pertain to thePAGE LIMITS
    1. If noPAGE LIMITSclause is specified, the entire report will be generated as if it consists of a single arbitrarily long page.
    2. All literals (<literal-2> through <literal-8>) must be numeric with non-zero positive integer values.
    3. All identifiers (<identifier-2> through <identifier-8>) must be numeric, unedited with non-zero positive integer values.
    4. Any value specified for <literal-2>|<identifier-2> will define the total number of available lines on any report page, not counting any unused margins at the top and/or bottom of the page (defined by theLINES AT TOPandLINES AT BOTTOMvalues specified on theLINAGEclause of theFDthisRDis linked to — see File/Sort-Description).
    5. Any value specified for <literal-3>|<identifier-3> will be ignored.
    6. TheHEADING
    7. TheFIRST DETAIL
    8. TheLAST CONTROL
    9. TheLAST DETAIL
    10. TheFOOTING
    11. The following rules establish default values for the variousPAGE LIMITclauses, assuming there is one:
      • HEADING— the default is one (1)
      • FIRST DETAIL— the HEADING value is used
      • LAST CONTROL HEADING— the value fromLAST DETAILor, if that is absent, the value fromFOOTINGor, if that too is absent, the value fromPAGE LIMIT
      • LAST DETAIL— the value fromFOOTINGor, if that is absent, the value fromPAGE LIMIT
      • FOOTING— the value fromLAST DETAILor, if that is absent, the value fromPAGE LIMIT
    12. For the values specified on aPAGE LIMITclause to be valid, all of the following must be true:
      • HEADINGnot >FIRST DETAIL
      • FIRST DETAILnot >LAST CONTROL HEADING
      • LAST CONTROL HEADINGnot >LAST DETAIL
      • LAST DETAILnot >FOOTING
  9. The following rules pertain to theCONTROL
    1. If there is noCONTROLclause, the report will contain no control breaks; this implies that there can be noCONTROL HEADINGorCONTROL FOOTINGreport groups defined for thisRD
    2. Include the reserved wordFINAL
    3. If you specifyFINAL it must be the first control break named in theRD
    4. Any <identifier-9> specifications included on theCONTROLclause are referencing data names defined in any data division section except for the report section.
    5. There must be aCONTROL HEADINGand/orCONTROL FOOTINGreport group defined in the report section for each <identifier-9>.
    6. At execution time:
      • Each time aGENERATEstatement (see GENERATE) is executed against a detail report group defined for thisRD the RWCS will check the contents of each <identifier-2> data item; whenever an <identifier-9>’s value has changed since the previous GENERATE, a control break condition will be in effect for that <identifier-2>.
      • Once the list of control breaks has been determined, theCONTROL FOOTINGfor each <identifier-2> having a control break (if any such report group is defined) will be presented.
      • Next, theCONTROL HEADINGfor each <identifier-2> having a control break (if any such report group is defined) will be presented.
      • TheCONTROL FOOTINGandCONTROL HEADINGreport groups will be presented in the sequence in which they are listed on theCONTROLclause.
      • Only after this processing has occurred will the detail report group specified on theGENERATEbe presented.
  10. EachRDwill have the following allocated for it:
    1. ThePAGE-COUNTERspecial register (see Special Registers), which will contain the current report page number.
      • This register will be set to a value of 1 when anINITIATEstatement (see INITIATE) is executed for the report and will be incremented by 1 each time the RWCS starts a new page of the report.
      • References toPAGE-COUNTERwithin the report section will be implicitly qualified with the name of the report to which the report group referencing the register belongs.
      • References toPAGE-COUNTERin the procedure division must be qualified with the appropriate report name if there are multipleRD defined.
    2. TheLINE-COUNTERspecial register , which will contain the current line number on the current page.
  11. TheRDmust be followed by at least one 01-level report group definition.

5.6.1. Report Group Definitions

Report-Group-Definition Syntax

 01 [ identifier-1 ]

 [ LINE NUMBER IS { integer-1 [ [ ON NEXT PAGE ] } ]
   ~~~~           {                  ~~~~ ~~~~   }
                  { +|PLUS integer-1             }
                  {   ~~~~                       }
                  { ON NEXT PAGE                 }
                       ~~~~ ~~~~
 [ NEXT GROUP IS { [ +|PLUS ] integer-2  } ]
   ~~~~ ~~~~~    {     ~~~~              }
                 { NEXT|{NEXT PAGE}|PAGE }
                   ~~~~  ~~~~ ~~~~  ~~~~
 [ TYPE IS { RH|{REPORT HEADING}                      } ]
   ~~~~    { ~~  ~~~~~~ ~~~~~~~                       }
           { PH|{PAGE HEADING}                        }
           { ~~  ~~~~ ~~~~~~~                         }
           { CH|{CONTROL HEADING} FINAL|identifier-2  }
           { ~~  ~~~~~~~ ~~~~~~~  ~~~~~               }
           { DE|DETAIL                                }
           { ~~ ~~~~~~                                }
           { CF|{CONTROL FOOTING} FINAL|identifier-2  }
           { ~~  ~~~~~~~ ~~~~~~~  ~~~~~               }
           { PF|{PAGE FOOTING}                        }
           {  ~~ ~~~~ ~~~~~~~                         }
           { RF|{REPORT FOOTING}                      }
             ~~  ~~~~~~ ~~~~~~~
 . [ REPORT-SECTION-Data-Item ]...
  1. The reserved wordsISNUMBERandONare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. TheRHandREPORT HEADINGterms are interchangeable, as arePHandPAGE HEADINGCHandCONTROL HEADINGDEandDETAILCFandCONTROL FOOTINGPFandPAGE FOOTINGas well asRFandREPORT FOOTING
  3. The report group being defined will be a part of the most-recently codedRD
  4. TheTYPE(see TYPE) clause specifies the type of report group being defined.
  5. The level number used for a report group definition must be 01.
  6. The optional <identifier-1> specification assigns a name to this report group so that the group may be referenced either by a GENERATE statement or on aUSE BEFORE REPORTING
  7. No two report groups in the same report RD may named with the same <identifier-1>. There may, however, be multiple <identifier-1> definitions in different reports. In such instances, references to <identifier-1> must be qualified by the report name.
  8. There may only be one report heading, report footing, final control heading, final control footing, page heading and page footing defined per report.
  9. Report group declarations must be followed by at least one <<REPORT-SECTION-Data-Item>> with a level number in the range 02-49.
  10. See Data Description Clauses, for information on the usage of the various data description clauses.

5.6.2. REPORT SECTION Data Items

REPORT-SECTION-Data-Item Syntax

 level-number [ identifier-1 ]

 [ BLANK WHEN ZERO ]
   ~~~~~      ~~~~
 [ COLUMN [ { NUMBER IS   } ] [ +|PLUS ] integer-1 ]
   ~~~      { ~~~~~~      }       ~~~~
            { NUMBERS ARE }
              ~~~~~~~
 [ GROUP INDICATE ]
   ~~~~~ ~~~~~~~~
 [ JUSTIFIED RIGHT ]
   ~~~~
 [ LINE NUMBER IS { integer-2 [ [ ON NEXT PAGE ] } ]
   ~~~~           { +|PLUS integer-2 ~~~~ ~~~~   }
                  {   ~~~~                       }
                  { ON NEXT PAGE                 }
                       ~~~~ ~~~~
 [ OCCURS [ integer-3 TO ] integer-4 TIMES
   ~~~~~~             ~~
     [ DEPENDING ON identifier-2 ]
       ~~~~~~~~~
     [ STEP integer-5 ]
       ~~~~
     [ VARYING identifier-3 FROM { identifier-4 } BY { identifier-5 } ]
       ~~~~~~~              ~~~~ { integer-6    } ~~ { integer-7    }
 [ PICTURE IS picture-string ]
   ~~~
 [ PRESENT WHEN condition-name ]
   ~~~~~~~ ~~~~
 [ SIGN IS LEADING|TRAILING [ SEPARATE CHARACTER ] ]
   ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
 [ { SOURCE IS literal-1|identifier-6 [ ROUNDED ]                   } ]
   { ~~~~~~                             ~~~~~~~                     }
   { SUM OF { identifier-7 }... [ { RESET ON FINAL|identifier-8 } ] }
   { ~~~    { literal-2    }      { ~~~~~    ~~~~~              }   }
   { VALUE IS [ ALL ] literal-3   { UPON identifier-9           }   }
     ~~~~~      ~~~                 ~~~~
 . [ REPORT-SECTION-Data-Item ]...
  1. The reserved wordsISNUMBEROFONRIGHTTIMESandWHEN(BLANK) are optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordCOLUMNmay be abbreviated asCOL
  3. The reserved wordJUSTIFIEDmay be abbreviated asJUST
  4. The reserved wordPICTUREmay be abbreviated asPIC
  5. TheSOURCE(see SOURCE),SUM(see SUM) andVALUE(see VALUE) clauses, valid only on an elementary item, are mutually-exclusive of each other.
  6. Group items (those withoutPICTURE
  7. See Data Description Clauses, for information on the usage of the various data description clauses.

5.7. SCREEN SECTION

SCREEN-SECTION-Data-Item Syntax

 level-number [ identifier-1 | FILLER ]
                               ~~~~~~
 [ AUTO | AUTO-SKIP | AUTOTERMINATE ] [ BELL | BEEP ]
   ~~~~   ~~~~~~~~~   ~~~~~~~~~~~~~     ~~~~   ~~~~
 [ BACKGROUND-COLOR|BACKGROUND-COLOUR IS integer-1 | identifier-2 ]
   ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
 [ BLANK LINE|SCREEN ] [ ERASE EOL|EOS ]
   ~~~~~ ~~~~ ~~~~~~     ~~~~~ ~~~ ~~~
 [ BLANK WHEN ZERO ] [ JUSTIFIED RIGHT ]
   ~~~~~      ~~~~     ~~~~
 [ BLINK ] [ HIGHLIGHT | LOWLIGHT ] [ REVERSE-VIDEO ]
   ~~~~~     ~~~~~~~~~   ~~~~~~~~     ~~~~~~~~~~~~~
 [ COLUMN NUMBER IS [ +|PLUS ] integer-2 | identifier-3 ]
   ~~~                  ~~~~
 [ FOREGROUND-COLOR|FOREGROUND-COLOUR IS integer-3 | identifier-4 ]
   ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
 [ { FROM literal-1 | identifier-5 } ]
   { ~~~~                          }
   { TO identifier-5               }
   { ~~                            }
   { USING identifier-5            }
   { ~~~~~                         }
   { VALUE IS [ ALL ] literal-1    }
     ~~~~~      ~~~
 [ FULL | LENGTH-CHECK ] [ REQUIRED | EMPTY-CHECK ] [ SECURE | NO-ECHO ]
   ~~~~   ~~~~~~~~~~~~     ~~~~~~~~   ~~~~~~~~~~~     ~~~~~~   ~~~~~~~
 [ LEFTLINE ] [ OVERLINE ] [ UNDERLINE ]
   ~~~~~~~~     ~~~~~~~~     ~~~~~~~~~
 [ LINE NUMBER IS [ +|PLUS ] integer-4 | identifier-6 ]
   ~~~~               ~~~~
 [ OCCURS integer-5 TIMES ]
   ~~~~~~
 [ PICTURE IS picture-string ]
   ~~~
 [ PROMPT [ CHARACTER IS literal-2 | identifier-7 ]
   ~~~~~~   ~~~~~~~~~
 [ SIGN IS LEADING|TRAILING [ SEPARATE CHARACTER ] ]
   ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
 . [ SCREEN-SECTION-Data-Item ]...
  1. The reserved wordsCHARACTERSEPARATEclause),ISNUMBERRIGHTTIMESandWHENare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordCOLUMNmay be abbreviated asCOL
  3. The reserved wordPICTUREmay be abbreviated asPIC
  4. The following sets of reserved words are interchangeable:
    • AUTOAUTO-SKIPandAUTOTERMINATE
    • BACKGROUND-COLORandBACKGROUND-COLOUR
    • BELLandBEEP
    • FOREGROUND-COLORandFOREGROUND-COLOUR
    • FULLandLENGTH-CHECK
    • REQUIREDandEMPTY-CHECK
    • SECUREandNO-ECHO
  5. Data items defined in the screen section describe input, output or combination screen layouts to be used withACCEPT screen-data-itemstatement (see ACCEPT screen-data-item) orDISPLAY screen-data-itemstatement (see DISPLAY screen-data-item) statements. These screen layouts may define the entire available screen area or any subset of it.
  6. The term ’available screen area’ is a nebulous one in those environments where command-line shell sessions are invoked within a graphical user-interface environment, as will be the case on Windows, OSX and most Unix/Linux systems — these environments allow command-line session windows to exist with a variable number of available screen rows and columns. When you are designing GnuCOBOL screens, you need to do so with an awareness of the logical screen row/column geometry the program will be executing within.
  7. Data items with level numbers 01 (Constants), 66, 78 and 88 may be used in the screen section; they have the same syntax, rules and usage as they do in the other data division sections.
  8. WithoutLINE(see LINE) orCOLUMN(see COLUMN) clauses, screen section fields will display on the console window beginning at whatever line/column coordinate is stated or implied by theACCEPT screen-data-itemorDISPLAY screen-data-itemstatement that presents the screen item. After a field is presented to the console window, the next field will be presented immediately following that field.
  9. ALINEclause explicitly stated in the definition of a screen section data item will override anyLINEclause included on theACCEPT screen-data-itemorDISPLAY screen-data-itemstatement that presents that data item to the screen. The same is true ofCOLUMNclauses.
  10. The Tab and Back-Tab (Shift-Tab on most keyboards) keys will position the cursor from field to field in the line/column sequence in which the fields occur on the screen at execution time, regardless of the sequence in which they were defined in the screen section.
  11. See Data Description Clauses, for information on the usage of the various data description clauses.

5.8. Special Data Items

5.8.1. 01-Level Constants

01-Level-Constant Syntax

 01 constant-name-1 CONSTANT [ IS GLOBAL ]
                    ~~~~~~~~      ~~~~~~
   { AS { literal-1                           } } .
   {    { { BYTE-LENGTH } OF { identifier-1 } } }
   {    { { ~~~~~~~~~~~ }    { usage-name   } } }
   {    { { LENGTH      }                     } }
   {        ~~~~~~                              }
   { FROM CDF-variable-name-1                   }
     ~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, SCREEN

The 01-level constant is one of four types of compilation-time constants that can be declared within a program. The other three types are>>DEFINECDF directive (see >>DEFINE) constants,>>SETCDF directive (see >>SET) constants and 78-level constants (see 78-Level Data Items).

  1. The reserved wordsASISandOFare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. See GLOBAL, for information on theGLOBALoption.
  3. This particular type of constant declaration provides the ability to determine the length of a data item or the storage size associated with a particular numericUSAGE(see USAGE) type — something not possible with the other types of constants.
  4. Constants defined in this way become undefined once anEND PROGRAMorEND FUNCTIONis encountered in the input source.
  5. Data descriptions of this form do not actually allocate any storage — they merely define a name (<constant-name-1>) that may be used anywhere a numeric literal BYTE-LENGTH
  6. The <constant-name-1> name may not be referenced on a CDF directive.
  7. Care must be taken that <constant-name-1> does not duplicate any other data item name that has been defined in the program as references to that data item name will refer to the constant and not the data item. The GnuCOBOL compiler will not issue a warning about this condition.
  8. The value specified for <usage-name> may be anyUSAGEthat does not use aPICTURE(see PICTURE) clause. These would be any ofBINARY-C-LONGBINARY-CHARBINARY-DOUBLEBINARY-LONGBINARY-SHORTCOMP-1(orCOMPUTATIONAL-1,COMP-2(orCOMPUTATIONAL-2,FLOAT-DECIMAL-16FLOAT-DECIMAL-34FLOAT-LONGFLOAT-SHORTPOINTER orPROGRAM-POINTER
  9. TheBYTE-LENGTHclause will produce a numeric value for <constant-name-1> identical to that which would be returned by theBYTE-LENGTHintrinsic function executed against <identifier-1> or a data item declared with aUSAGEof <usage-name>.
  10. TheLENGTHclause will produce a numeric value for <constant-name-1> identical to that which would be returned by theLENGTHintrinsic function executed against <identifier-1> or a data item declared with aUSAGEof <usage-name>.

Here is the listing of a GnuCOBOL program that uses 01-level constants to display the length (in bytes) of the various picture-less usage types.

    IDENTIFICATION DIVISION.
    PROGRAM-ID. Usage Lengths.
    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01  Len-BINARY-C-LONG    CONSTANT AS LENGTH OF BINARY-C-LONG.
    01  Len-BINARY-CHAR      CONSTANT AS LENGTH OF BINARY-CHAR.
    01  Len-BINARY-DOUBLE    CONSTANT AS LENGTH OF BINARY-DOUBLE.
    01  Len-BINARY-LONG      CONSTANT AS LENGTH OF BINARY-LONG.
    01  Len-BINARY-SHORT     CONSTANT AS LENGTH OF BINARY-SHORT.
    01  Len-COMP-1           CONSTANT AS LENGTH OF COMP-1.
    01  Len-COMP-2           CONSTANT AS LENGTH OF COMP-2.
    01  Len-FLOAT-DECIMAL-16 CONSTANT AS LENGTH OF FLOAT-DECIMAL-16.
    01  Len-FLOAT-DECIMAL-34 CONSTANT AS LENGTH OF FLOAT-DECIMAL-34.
    01  Len-FLOAT-LONG       CONSTANT AS LENGTH OF FLOAT-LONG.
    01  Len-FLOAT-SHORT      CONSTANT AS LENGTH OF FLOAT-SHORT.
    01  Len-POINTER          CONSTANT AS LENGTH OF POINTER.
    01  Len-PROGRAM-POINTER  CONSTANT AS LENGTH OF PROGRAM-POINTER.
    PROCEDURE DIVISION.
    000-Main.
        DISPLAY "On this system, with this build of GnuCOBOL, the"
        DISPLAY "PICTURE-less USAGE's have these lengths (in bytes):"
        DISPLAY " "
        DISPLAY "BINARY-C-LONG:    " Len-BINARY-C-LONG
        DISPLAY "BINARY-CHAR:      " Len-BINARY-CHAR
        DISPLAY "BINARY-DOUBLE:    " Len-BINARY-DOUBLE
        DISPLAY "BINARY-LONG:      " Len-BINARY-LONG
        DISPLAY "BINARY-SHORT:     " Len-BINARY-SHORT
        DISPLAY "COMP-1:           " Len-COMP-1
        DISPLAY "COMP-2:           " Len-COMP-2
        DISPLAY "FLOAT-DECIMAL-16: " Len-FLOAT-DECIMAL-16
        DISPLAY "FLOAT-DECIMAL-34: " Len-FLOAT-DECIMAL-34
        DISPLAY "FLOAT-LONG:       " Len-FLOAT-LONG
        DISPLAY "FLOAT-SHORT:      " Len-FLOAT-SHORT
        DISPLAY "POINTER:          " Len-POINTER
        DISPLAY "PROGRAM-POINTER:  " Len-PROGRAM-POINTER
        STOP RUN
        .

The output of this program, on a Windows 7 system with a 32-bit MinGW build of GnuCOBOL is:

    On this system, with this build of GnuCOBOL, the
    PICTURE-less USAGE's have these lengths (in bytes):

    BINARY-C-LONG:    4
    BINARY-CHAR:      1
    BINARY-DOUBLE:    8
    BINARY-LONG:      4
    BINARY-SHORT:     2
    COMP-1:           4
    COMP-2:           8
    FLOAT-DECIMAL-16: 8
    FLOAT-DECIMAL-34: 16
    FLOAT-LONG:       8
    FLOAT-SHORT:      4
    POINTER:          4
    PROGRAM-POINTER:  4

5.8.2. 66-Level Data Items

66-Level-Data-Item Syntax

 66 identifier-1 RENAMES identifier-2 [ THRU|THROUGH identifier-3 ] .
                 ~~~~~~~                ~~~~ ~~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE

A 66-level data item regroups previously defined items by specifying alternative, possibly overlapping, groupings of elementary data items.

  1. The reserved wordsTHRUandTHROUGHare interchangeable.
  2. A level-66 data item cannot rename a level-66, level-01, level-77, or level-88 data item.
  3. There may be multiple level-66 data items that rename data items contained within the same 01-level record description.
  4. AllRENAMESentries associated with one logical record must immediately follow that record’s last data description entry.

5.8.3. 77-Level Data Items

77-Level-Data-Item Syntax

 77 identifier-1 [ IS GLOBAL|EXTERNAL ]
                      ~~~~~~ ~~~~~~~~
 [ BASED ]
   ~~~~~
 [ BLANK WHEN ZERO ]
   ~~~~~      ~~~~
 [ JUSTIFIED RIGHT ]
   ~~~~
 [ PICTURE IS picture-string ]
   ~~~
 [ REDEFINES identifier-5 ]
   ~~~~~~~~~
 [ SIGN IS LEADING|TRAILING [ SEPARATE CHARACTER ] ]
   ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
 [ SYNCRONIZED|SYNCHRONISED [ LEFT|RIGHT ] ]
   ~~~~        ~~~~           ~~~~ ~~~~~
 [ USAGE IS data-item-usage ]
   ~~~~~
 [ VALUE IS [ ALL ] literal-1 ] .
   ~~~~~      ~~~

TheLEFTandRIGHT(SYNCRONIZED) clauses are syntactically recognized but are otherwise non-functional.

This syntax is valid in the following sections:
WORKING-STORAGE, LOCAL-STORAGE, LINKAGE

The intent of a 77-level item is to be able to create a stand-alone elementary data item.

  1. The reserved wordsCHARACTERISRIGHT(JUSTIFIED) andWHENare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordJUSTIFIEDmay be abbreviated asJUST the reserved wordPICTUREmay be abbreviated asPICand the reserved wordsSYNCRONIZEDandSYNCHRONISEDmay be abbreviated asSYNC
  3. New programs requiring a stand-alone elementary item should be coded to use a level number of 01 rather than 77.
  4. See Data Description Clauses, for information on the usage of the various data description clauses.

5.8.4. 78-Level Data Items

78-Level-Constant Syntax

 78 constant-name-1 VALUE IS literal-1 .
                    ~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, SCREEN

The 78-level constant is one of four types of compilation-time constants that can be declared within a program. The other three types are>>DEFINECDF directive (see >>DEFINE) constants,>>SETCDF directive (see >>SET) constants and 01-level constants (see 01-Level Constants).

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. Constants defined in this way become undefined once anEND PROGRAMorEND FUNCTIONis encountered in the input source.
  3. Data descriptions of this form do not actually allocate any storage — they merely define a name (<constant-name-1>) that may be used anywhere a literal of the same type as <literal-1> may be used.
  4. The <constant-name-1> name may not be referenced on a CDF directive.
  5. Care must be taken that <constant-name-1> does not duplicate any other data item name that has been defined in the program as references to that data item name will refer to the constant and not the data item. The GnuCOBOL compiler will not issue a warning about this condition.

5.8.5. 88-Level Data Items

88-Level-Data-Item Syntax

 88 condition-name-1 { VALUE IS   } {literal-1 [ THRU|THROUGH literal-2 ]}...
                     { ~~~~~      }              ~~~~ ~~~~~~~
                     { VALUES ARE }
                       ~~~~~~

   [ WHEN SET TO FALSE IS literal-3 ] .
                 ~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

Condition names are Boolean (i.e. TRUE / FALSE) data items that receive their TRUE and FALSE values based upon the values of the non 88-level data item whose definition they immediately follow.

  1. The reserved wordsAREISSETandTOare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsTHRUandTHROUGHare interchangeable.
  3. Condition names are always defined subordinate to another (non 88-level) data item. That data item must be an elementary item. Whenever the parent data item assumes one of the values specified on the 88-level item’sVALUE(see VALUE) clause, <condition-name-1> will take on the value of TRUE.
  4. Condition names do not occupy any storage.
  5. The optionalTHROUGHclause allows a range of possible TRUE values to be specified.
  6. Whenever the parent data item assumes any value except one of the values specified on <condition-name-1>’sVALUEclause, <condition-name-1> will take on the value of FALSE.
  7. Executing the statementSET <condition-name-1> TO TRUEwill cause <condition-name-1>’s parent data item to take on the first value specified on <condition-name-1>’sVALUEclause.
  8. Executing the statementSET <condition-name-1> TO FALSEwill cause <condition-name-1>’s parent data item to take on the value specified on <condition-name-1>’sFALSEclause. If <condition-name-1> does not have aFALSEclause, theSET(see SET) statement will generate an error message at compilation time.
  9. See Condition Names, for more information.

5.9. Data Description Clauses

5.9.1. ANY LENGTH

ANY LENGTH Attribute Syntax

 ANY LENGTH
 ~~~ ~~~~~~
This syntax is valid in the following sections:
LINKAGE

Data items declared with theANY LENGTHattribute have no fixed compile-time length. Such items may only be defined in the linkage section of a subprogram as they may only serve as subroutine argument descriptions. These items must have aPICTURE(see PICTURE) clause that specifies exactly one A, X or 9 symbol.

  1. TheANY LENGTHandBASED(see BASED) clauses cannot be used together in the same data item description.

5.9.2. AUTO

AUTO Attribute Syntax

 AUTO
 ~~~~
This syntax is valid in the following sections:
SCREEN

A field whose description includes this attribute will cause the cursor to automatically advance to the next input-enabled field of a screen if the field is completely filled with input data.

  1. TheAUTOAUTO-SKIP(see AUTO-SKIP) andAUTOTERMINATE(see AUTOTERMINATE) clauses are interchangeable, and may not be used together in the same data item description.

5.9.3. AUTO-SKIP

AUTO-SKIP Attribute Syntax

 AUTO-SKIP
 ~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

A field whose description includes this attribute will cause the cursor to automatically advance to the next input-enabled field of a screen if the field is completely filled with input data.

  1. TheAUTO(see AUTO),AUTO-SKIPandAUTOTERMINATE(see AUTOTERMINATE) clauses are interchangeable, and may not be used together in the same data item description.

5.9.4. AUTOTERMINATE

AUTOTERMINATE Attribute Syntax

 AUTOTERMINATE
 ~~~~~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

A field whose description includes this attribute will cause the cursor to automatically advance to the next input-enabled field of a screen if the field is completely filled with input data.

  1. TheAUTO(see AUTO),AUTO-SKIP(see AUTO-SKIP) andAUTOTERMINATEclauses are interchangeable, and may not be used together in the same data item description.

5.9.5. BACKGROUND-COLOR

BACKGROUND-COLOR Attribute Syntax

 BACKGROUND-COLOR|BACKGROUND-COLOUR IS integer-1 | identifier-1
 ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

This clause is used to specify the screen background color of the screen data item or the default screen background color of subordinate items if used on a group item.

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The reserved wordsBACKGROUND-COLORandBACKGROUND-COLOURare interchangeable.
  3. You specify colors by number (0-7), or by using the constant names provided in the "screenio.cpy" copybook (which is provided with all GnuCOBOL source distributions).
  4. Colors may also be specified using a numeric non-edited identifier whose value is in the range 0-7.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.6. BASED

BASED Attribute Syntax

 BASED
 ~~~~~
This syntax is valid in the following sections:
WORKING-STORAGE, LOCAL-STORAGE, LINKAGE

Data items declared withBASEDare allocated no storage at compilation time. At run-time, theALLOCATE(see ALLOCATE) orSET ADDRESS(see SET ADDRESS) statements are used to allocate space for and (optionally) initialize such items.

  1. TheBASEDandANY LENGTH(see ANY LENGTH) clauses cannot be used together in the same data item description.
  2. TheBASEDclause may only be used on level 01 and level 77 data items.

5.9.7. BEEP

BEEP Attribute Syntax

 BEEP
 ~~~~
This syntax is valid in the following sections:
SCREEN
  1. TheBEEPandBELL(see BELL) clauses are interchangeable, and may not be used together in the same data item description.
  2. Use this clause to cause an audible tone to occur when the screen item is DISPLAYed.

5.9.8. BELL

BELL Attribute Syntax

 BELL
 ~~~~
This syntax is valid in the following sections:
SCREEN
  1. TheBEEP(see BEEP) andBELLclauses are interchangeable, and may not be used together in the same data item description.
  2. Use this clause to cause an audible tone to occur when the screen item is DISPLAYed.

5.9.9. BLANK

BLANK Attribute Syntax

 BLANK LINE|SCREEN
 ~~~~~ ~~~~ ~~~~~~
This syntax is valid in the following sections:
SCREEN

This clause will blank out either the entire screen (BLANK SCREEN) or just the line upon which data is about to be displayed (BLANK LINE).

  1. Blanked-out areas will have their foreground and background colors set to the attributes of the field containing theBLANKclause.
  2. This clause is useful when one screen section item is being displayed over the top of a previously-displayed one.

5.9.10. BLANK WHEN ZERO

BLANK-WHEN-ZERO Attribute Syntax

 BLANK WHEN ZERO
 ~~~~~      ~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

This clause will cause that item’s value to be automatically transformed into spaces if a value of 0 is ever MOVEd to the item.

  1. The reserved wordWHENis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. This clause may only be used on a PIC 9 data item with aUSAGE(see USAGE) ofDISPLAY

BLINK Attribute Syntax

 BLINK
 ~~~~~
This syntax is valid in the following sections:
SCREEN

TheBLINKclause modifies the visual appearance of the displayed field by making the field contents blink.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.12. COLUMN

COLUMN (REPORT SECTION) Clause Syntax

 COLUMN [ { NUMBER IS   } ] [ +|PLUS ] integer-1 ]
 ~~~      { NUMBERS ARE }       ~~~~

COLUMN (SCREEN SECTION) Clause Syntax

 COLUMN NUMBER IS [ +|PLUS ] integer-2 | identifier-3 ]
 ~~~                  ~~~~
This syntax is valid in the following sections:
REPORT, SCREEN

TheCOLUMNclause provides the means of stating in which column a field should be presented on the console window (screen section) or a report (report section).

  1. The reserved wordsAREISNUMBERandNUMBERSare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordCOLUMNmay be abbreviated asCOL
  3. The line location of a report section or screen section field will be determined by theLINE(see LINE) clause.
  4. The value of <integer-1> must be 1 or greater.
  5. If <identifier-1> is used to specify either an absolute or relative column position, <identifier-1> must be defined as a numeric item of anyUSAGE(see USAGE) other thanCOMPUTATIONAL-1orCOMPUTATIONAL-2 without editing symbols. The value of <identifier-1> at the time the screen data item is presented must be 1 or greater. Note that aCOMPUTATIONAL-1orCOMPUTATIONAL-2identifier will be accepted by the compiler, but will produce unpredictable results at run-time.
  6. The column coordinate of a field may be stated on an absolute basis (i.e.COLUMN 5 or on a relative basis based upon the end of the previously-presented field (i.e.COLUMN PLUS 1.
  7. The symbol+may be used in lieu of the wordPLUS if desired; if symbol+is used, however, there must be at least one space separating it from <integer-1>. Failure to include this space will cause the symbol+sign to be simply treated as part of <integer-1> and will treat theCOLUMNclause as an absolute column specification rather than a relative one.
  8. Using relative column positioning COLUMN PLUS has slightly different behaviour depending upon the section in which the clause is used, as follows:
    1. When used on a report section data item,COLUMN PLUSwill position the start of the new field’s value such that there are <integer-1> blank columns between the end of the previous field and the beginning of this field.

      If a report data item’s description includes theSOURCE(see SOURCE),SUM(see SUM) orVALUE(see VALUE) clause but has noCOLUMNclause,COLUMN PLUS 1will be assumed.

    2. When used on a screen section data item,COLUMN PLUSwill position the new field so that it begins exactly <integer-1> or <identifier-1> characters past the last character of the previous field. Thus,COLUMN PLUS 1will leave no blank positions between the end of the previous field and the start of this one.

      If a screen data item’s description includes theFROM(see FROM),TO(see TO),USING(see USING) orVALUE(see VALUE) clause but has noCOLUMNclause, the new screen field will begin at the column coordinate of the last character of the previous field.

5.9.13. CONSTANT

CONSTANT Attribute Syntax

 CONSTANT
 ~~~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, SCREEN

This option signifies that the 01-level data item in whose declarationCONSTANTis specified will be treated as a symbolic name for a literal value, usable wherever a literal of the appropriate type could be used.

  1. The value of a data item defined as a constant cannot be changed at run-time. In fact, it is not syntactically acceptable to use such a data item as the destination field of any procedure division statement that stores a value.
  2. See 01-Level Constants, for additional information.

5.9.14. EMPTY-CHECK

EMPTY-CHECK Attribute Syntax

 EMPTY-CHECK
 ~~~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

This clause forces the user to enter data into the field it is specified on (or into all subordinate input-capable fields ifEMPTY-CHECKis specified on a group item).

  1. TheEMPTY-CHECKandREQUIRED(see REQUIRED) clauses are interchangeable, and may not be used together in the same data item description.
  2. In order to take effect, the user must first move the cursor into the field having this clause in its definition.
  3. TheACCEPT screen-data-itemstatement (see ACCEPT screen-data-item) will ignore the Enter key and any other cursor-moving keystrokes that would cause the cursor to move to another screen item unless data has been entered into the field. Function keys will still be allowed to terminate theACCEPT
  4. In order to be functional, this attribute must be supported by the underlying ’curses’ package your GnuCOBOL implementation was built with. As of this time, the ’PDCurses’ package (used for native Windows or MinGW builds) does not supportEMPTY-CHECK

5.9.15. ERASE

ERASE Clause Syntax

 ERASE EOL|EOS
 ~~~~~ ~~~ ~~~
This syntax is valid in the following sections:
SCREEN

ERASEwill blank-out screen contents from the location where the screen data item whose description contains this clause will be displayed, forward until the end of the screen ERASE EOS

  1. Erased areas will have their foreground and background colors set to the attributes of the field containing theERASEclause.
  2. This clause is useful when one screen section item is being displayed over the top of a previously-displayed one.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.16. EXTERNAL

EXTERNAL Attribute Syntax

 EXTERNAL
 ~~~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE

This clause marks a data item description,FDorSDsee File/Sort-Description as being shareable with other programs executed from the same execution thread.

  1. By specifying theEXTERNALclause on either an FD or an SD, the file description is capable of being shared between all programs executed from the same execution thread, provided anEXTERNALclause is coded with the file’s description in each program requiring it. This sharing allows the file to be opened, read and/or written and closed in different programs. This sharing applies to the record descriptions subordinate to the file description too.
  2. By specifying theEXTERNALclause on the description of a data item, the data item is capable of being shared between all programs executed from the same execution thread, provided the data item is coded (with anEXTERNALclause) in each program requiring it.
  3. The following points apply to the specification ofEXTERNALin a data item’s definition:
    1. TheEXTERNALclause may only be specified at the 77 or 01 level.
    2. AnEXTERNALitem must have a data name and that name cannot beFILLER
    3. EXTERNALcannot be combined withBASED(see BASED),GLOBAL(see GLOBAL) orREDEFINES(see REDEFINES).

5.9.17. FALSE

FALSE Clause Syntax

 WHEN SET TO FALSE IS literal-1
             ~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

This clause, which may only appear on the definition of a level-88 condition name, is used to specify the value of the data item that serves as the parent of the level-88 condition name that will force the condition name to assume a value of FALSE.

  1. The reserved wordsISSETTOandWHENare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. See 88-Level Data Items, or See Condition Names, for more information.

5.9.18. FOREGROUND-COLOR

FOREGROUND-COLOR Attribute Syntax

 FOREGROUND-COLOR|FOREGROUND-COLOUR IS integer-1 | identifier-1
 ~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

This clause is used to specify the color of text within a screen data item or the default text color of subordinate items if used on a group item.

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The reserved wordsFOREGROUND-COLORandFOREGROUND-COLOURare interchangeable.
  3. You specify colors by number (0-7), or by using the constant names provided in the "screenio.cpy" copybook (which is provided with all GnuCOBOL source distributions).
  4. Colors may also be specified using a numeric non-edited identifier whose value is in the range 0-7.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.19. FROM

FROM Clause Syntax

 FROM literal-1 | identifier-5
 ~~~~
This syntax is valid in the following sections:
SCREEN

This clause is used to specify either the data item a screen section field is to obtain it’s value from when the screen is displayed, or a literal that will specify the value of that same field.

  1. TheFROMTO(see TO),USING(see USING) andVALUE(see VALUE) clauses are mutually-exclusive in any screen section data item’s definition.

5.9.20. FULL

FULL Attribute Syntax

 FULL
 ~~~~
This syntax is valid in the following sections:
SCREEN

TheFULLclause forces the user to enter data into the field it is specified on (or into all subordinate input-capable fields if specified on a group item) sufficient to fill every character position of the field.

  1. TheFULLandLENGTH-CHECK(see LENGTH-CHECK) clauses are interchangeable, and may not be used together in the same data item description.
  2. In order for this clause to take effect at execution time, the user must move the cursor into the field having this clause in its definition.
  3. TheACCEPT screen-data-itemstatement (see ACCEPT screen-data-item) will ignore the Enter key and any other cursor-moving keystrokes that would cause the cursor to move to another screen item unless the proper amount of data has been entered into the field. Function keys will still be allowed to terminate theACCEPT however.
  4. In order to be functional, this attribute must be supported by the underlying ’curses’ package your GnuCOBOL implementation was built with. As of this time, the ’PDCurses’ package (used for native Windows or MinGW builds) does not supportFULL

5.9.21. GLOBAL

GLOBAL Attribute Syntax

 GLOBAL
 ~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, REPORT

This clause marks a data item, 01-level constant,FD(see File/Sort-Description),SD(see File/Sort-Description) or anRD(see REPORT SECTION) as being shareable with any nested subprograms.

  1. By specifying theGLOBALclause on the description of a file or a report, that description is capable of being shared between a program and any nested subprograms within it, provided theFDSDorRDis coded (with aGLOBALclause) in each nested subprogram requiring it. This sharing allows the file to be opened, read and/or written and closed or the report to be initiated or terminated in those programs. Separately compiled programs may not share aGLOBALfile description, but they may share anEXTERNAL(see EXTERNAL) file description. This sharing applies to the record descriptions subordinate to the file description and the report groups subordinate to theRDalso.
  2. By specifying theGLOBALclause on the description of a data item, the data item is capable of being shared between a program and any nested subprograms within it, provided the data item is coded (with aGLOBALclause) in each program requiring it.
  3. The following points apply to the specification ofGLOBALin a data item’s definition:
    1. TheGLOBALclause may only be specified at the 77 or 01 level.
    2. AGLOBALitem must have a data name and that name cannot beFILLER
    3. GLOBALcannot be combined withEXTERNAL(see EXTERNAL),REDEFINES(see REDEFINES) orBASED(see BASED).

5.9.22. GROUP INDICATE

GROUP-INDICATE Attribute Syntax

 GROUP INDICATE
 ~~~~~ ~~~~~~~~
This syntax is valid in the following sections:
REPORT

TheGROUP INDICATEclause specifies that the data item in whose definition the clause appears will be presented only in very limited circumstances.

  1. This clause may only appear within aDETAILreport group (see TYPE).
  2. When this clause is present, the data item in question will be presented only under the following circumstances:
    1. On the first presentation of the detail group following theINITIATE(see INITIATE) of the report.
    2. On the first presentation of the detail group after every new page is started.
    3. On the first presentation of the detail group after any control break occurs.

5.9.23. HIGHLIGHT

HIGHLIGHT Attribute Syntax

 HIGHLIGHT
 ~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

This clause controls the intensity of text FOREGROUND-COLOR(see FOREGROUND-COLOR)) by setting that intensity to its highest of three possible settings.

  1. This clause, along withLOWLIGHT(see LOWLIGHT), are intended to provide a three-level intensity scheme LOWLIGHT… nothing (Normal) …HIGHLIGHT.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.24. JUSTIFIED

JUSTIFIED Attribute Syntax

 JUSTIFIED RIGHT
 ~~~~

This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

The presence of aJUSTIFIED RIGHTclause in a data item’s definition alters the manner in which data is stored into the field from the default ’left-justified, space filled’ behaviour to ’right justified, space filled’.

  1. The reserved wordRIGHTis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The reserved wordJUSTIFIEDmay be abbreviated asJUST
  3. This clause is valid only on alphabetic (PIC A) or alphanumeric (PIC X) data items.
  4. The presence or absence of this clause influences the behaviour of theMOVE(see MOVE) statement as well as theFROM(see FROM),SOURCE(see SOURCE) andUSING(see USING) data item description clauses.
  5. If the value being stored into the field is the same length as the receiving field, the presence or absence of theJUSTIFIED RIGHTclause on that field’s description is irrelevant.
  6. The following examples illustrate the behaviour of the presence and absence of theJUSTIFIED RIGHTclause when the field size is different than that of the value being stored. In these examples, the symbol b represents a space.
    When the value is shorter than the field size...
    Without JUSTIFIED With JUSTIFIED
    01 A PIC X(6). 01 A PIC X(6) JUSTIFIED RIGHT.
    MOVEABCTO A MOVEABCTO A
    Result is ’ABCbbb Result is ’bbbABC’
    When the value is longer than the field size...
    Without JUSTIFIED With JUSTIFIED
    01 A PIC X(6). 01 A PIC X(6) JUSTIFIED RIGHT.
    MOVEABCDEFGHITO A MOVEABCDEFGHITO A
    Result is ’ABCDEF’ Result is ’DEFGHI’

5.9.25. LEFTLINE

LEFTLINE Attribute Syntax

 LEFTLINE
 ~~~~~~~~
This syntax is valid in the following sections:
SCREEN

TheLEFTLINEclause will introduce a vertical line at the left edge of a screen field.

  1. TheLEFTLINEOVERLINE(see OVERLINE) andUNDERLINE(see UNDERLINE) clauses may be used in any combination in a single field’s description.
  2. This clause is essentially non-functional when used within Windows command shell (cmd.exe) environments and running programs compiled using a GnuCOBOL implementation built using ’PDCurses’ (such as Windows/MinGW builds).
  3. Whether or not this clause operates on Cygwin or UNIX/Linux/OSX systems will depend upon the video attribute capabilities of the terminal output drivers and ’curses’ software being used.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.26. LENGTH-CHECK

LENGTH-CHECK Attribute Syntax

 LENGTH-CHECK
 ~~~~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

TheLENGTH-CHECKclause forces the user to enter data into the field it is specified on (or into all subordinate input-capable fields if specified on a group item) sufficient to fill every character position of the field.

  1. TheFULL(see FULL) andLENGTH-CHECKclauses are interchangeable, and may not be used together in the same data item description.
  2. In order for this clause to take effect at execution time, the user must move the cursor into the field having this clause in its definition.
  3. TheACCEPT screen-data-itemstatement (see ACCEPT screen-data-item) will ignore the Enter key and any other cursor-moving keystrokes that would cause the cursor to move to another screen item unless the proper amount of data has been entered into the field. Function keys will still be allowed to terminate theACCEPT however.
  4. In order to be functional, this attribute must be supported by the underlying ’curses’ package your GnuCOBOL implementation was built with. As of this time, the ’PDCurses’ package (used for native Windows or MinGW builds) does not supportLENGTH-CHECK

5.9.27. LINE

LINE (REPORT SECTION) Clause Syntax

 LINE NUMBER IS { integer-2 [ [ ON NEXT PAGE ] }
 ~~~~           {                  ~~~~ ~~~~   }
                { +|PLUS integer-2             }
                {   ~~~~                       }
                { ON NEXT PAGE                 }
                     ~~~~ ~~~~

LINE (SCREEN SECTION) Clause Syntax

 [ LINE NUMBER IS [ +|PLUS ] integer-4 | identifier-6 ]
   ~~~~               ~~~~
This syntax is valid in the following sections:
REPORT, SCREEN

This clause provides a means of explicitly stating on which line a field should be presented on the console window (screen section) or on a report (report section).

  1. The reserved wordsISNUMBERandONare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The following points document the use of format 1 of theLINEclause:
    1. The column location of a report item will be determined by theCOLUMN(see COLUMN) clause.
    2. The value of <integer-1> must be 1 or greater.
    3. The report line number upon which the data item containing this clause along with any subordinate data items will be presented may be stated on an absolute basis (i.e.LINE 5 or on a relative basis based upon the previously-displayed line (i.e.LINE PLUS 1.
    4. The symbol+may be used in lieu of the wordPLUS if desired; if+is used, however, there must be at least one space separating it from <integer-1>. Failure to include this space will cause the+to be simply treated as part of <integer-1> and will treat the LINE clause as an absolute line specification rather than a relative one.
    5. The optionalNEXT PAGE
  3. The following points document the use for format 2 of theLINEclause:
    1. The column location of a screen section field is determined by theCOLUMN(see COLUMN) clause.
    2. The value of <integer-1> must be 1 or greater.
    3. If <identifier-1> is used to specify either an absolute or relative column position, <identifier-1> must be defined as a numeric item of anyUSAGE(see USAGE) other thanCOMPUTATIONAL-1orCOMPUTATIONAL-2 without editing symbols. The value of <identifier-1> at the time the screen data item is presented must be 1 or greater. Note that aCOMPUTATIONAL-1orCOMPUTATIONAL-2identifier will be accepted by the compiler, but will produce unpredictable results at run-time.
    4. The screen line number upon which the data item containing this clause along with any subordinate data items will be displayed may be stated on an absolute basis (i.e.LINE 5 or on a relative basis based upon the previously-displayed line (i.e.LINE PLUS 1.
    5. The symbol+may be used in lieu of the wordPLUS if desired; if+is used, however, there must be at least one space separating it from <integer-1>. Failure to include this space will cause the+to be simply treated as part of <integer-1> and will treat theLINEclause as an absolute line specification rather than a relative one.
    6. If a screen data item’s description includes theFROM(see FROM),TO(see TO),USING(see USING) orVALUE(see VALUE) clause but has no LINE clause, the "current screen line" will be assumed.

5.9.28. LOWLIGHT

LOWLIGHT Attribute Syntax

 LOWLIGHT
 ~~~~~~~~
This syntax is valid in the following sections:
SCREEN

TheLOWLIGHTclause controls the intensity of text FOREGROUND-COLOR by setting that intensity to its lowest of three possible settings.

  1. This clause, along withHIGHLIGHT(see HIGHLIGHT), are intended to provide a three-level intensity scheme LOWLIGHT… nothing (Normal) …HIGHLIGHT. In environments such as a Windows console where only two levels of intensity are supported,LOWLIGHTis the same as leaving this clause off altogether.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.29. NEXT GROUP

NEXT-GROUP Clause Syntax

 NEXT GROUP IS { [ +|PLUS ] integer-2  }
 ~~~~ ~~~~~    {     ~~~~              }
               { NEXT|{NEXT PAGE}|PAGE }
                 ~~~~  ~~~~ ~~~~  ~~~~

This syntax is valid in the following sections:
REPORT

This clause defines any rules for where the next group to be presented on a report will begin, line-wise, with respect to the last line of the group in which this clause appears.

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The termsNEXT
  3. A report group must contain at least oneLINE NUMBERclause in order to also contain aNEXT GROUPclause.
  4. If theRD(see REPORT SECTION) in which the report group containing aNEXT GROUPclause does not contain aPAGE LIMITSclause, only thePLUS integer-1option may be specified.
  5. TheNEXT PAGEoption cannot be used in aPAGE FOOTING
  6. TheNEXT GROUPoption cannot be specified in either aREPORT HEADINGor aPAGE HEADING
  7. The effects ofNEXT GROUPwill be in addition to any line spacing defined by the next-presented group’sLINE NUMBERclause.

5.9.30. NO-ECHO

NO-ECHO Attribute Syntax

 NO-ECHO
 ~~~~~~~

This syntax is valid in the following sections:
SCREEN

TheNO-ECHOclause will cause all data entered into the field to appear on the screen as asterisks.

  1. TheNO-ECHOandSECURE(see SECURE) clauses are interchangeable, and may not be used together in the same data item description.
  2. This clause may only be used on a field allowing data entry (a field containing either theUSING(see USING) orTO(see TO) clause).

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.31. OCCURS

OCCURS (REPORT SECTION) Clause Syntax

 OCCURS [ integer-1 TO ] integer-2 TIMES
 ~~~~~~             ~~
   [ DEPENDING ON identifier-1 ]
     ~~~~~~~~~
   [ STEP integer-3 ]
     ~~~~
   [ VARYING identifier-2 FROM { identifier-3 } BY { identifier-4 } ]
     ~~~~~~~              ~~~~ { integer-4    } ~~ { integer-5    }

OCCURS (SCREEN SECTION) Clause Syntax

 OCCURS integer-2 TIMES
 ~~~~~~

OCCURS (All Other Sections Clause Syntax

 OCCURS [ integer-1 TO ] integer-2 TIMES
 ~~~~~~             ~~
      [ DEPENDING ON identifier-1 ]
        ~~~~~~~~~
      [ ASCENDING|DESCENDING KEY IS identifier-5... ]...
        ~~~~~~~~~ ~~~~~~~~~~
      [ INDEXED BY identifier-6 ]
        ~~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

TheOCCURSclause is used to create a data structure called a table, where entries in that structure repeat multiple times.

  1. The reserved wordsBY(INDEXED),ISKEYONandTIMESare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The value of <integer-2> specifies how many entries will be allocated in the table.
  3. The following is an example of how a table might be defined:
    05 QUARTERLY-REVENUE OCCURS 4 TIMES PIC 9(7)V99.
    

    This will allocate the following:

    QUARTERLY-REVENUE(1)
    QUARTERLY-REVENUE(2)
    QUARTERLY-REVENUE(3)
    QUARTERLY-REVENUE(4)
    

    Each occurrence is referenced using the subscript syntax (a numeric literal, arithmetic expression or numeric identifier enclosed within parenthesis) shown above.

  4. TheOCCURSclause may be used at the group level too, in which case the entire group structure repeats, as follows:
    05 GRP OCCURS 3 TIMES.
        10 A     PIC X(1).
        10 B     PIC X(1).
        10 C     PIC X(1).
    

    This would allow references to any of the following:

    GRP(1) - includes A(1), B(1) and C(1)
    GRP(2) - includes A(2), B(2) and C(2)
    GRP(3) - includes A(3), B(3) and C(3)
    

    or each A,B,C item could be referenced as follows:

    A(1) - Character #1 of GRP(1)
    B(1) - Character #2 of GRP(1)
    C(1) - Character #3 of GRP(1)
    A(2) - Character #1 of GRP(2)
    B(2) - Character #2 of GRP(2)
    C(2) - Character #3 of GRP(2)
    A(3) - Character #1 of GRP(3)
    B(3) - Character #2 of GRP(3)
    C(3) - Character #3 of GRP(3)
    
  5. The optionalDEPENDING ON
  6. See the documentation of theSEARCH(see SEARCH),SEARCH ALL(see SEARCH ALL) andSORT(see SORT) statements for explanations of theKEY
  7. TheOCCURSclause cannot be specified in a data description entry that has a level number of 01, 66, 77, or 88, although it is valid in data items described subordinate to an 01-level data item.
  8. The following points apply to anOCCURSused in the report section:
    1. The optionalSTEP
    2. The optionalVARYING
    3. The following two examples illustrate two different ways a report could include four quarters worth of sales figures in it’s detail lines — one doing things ’the hard way’ and one using the advancedOCCURScapabilities ofSTEPandVARYING Both assume the definition of the following table exists in working-storage:
      05 SALES OCCURS 4 TIMES PIC 9(7)V99.

      First, the "Hard Way":

      10 COL 7  PIC $(7)9.99 SOURCE SALES(1).
      10 COL 17 PIC $(7)9.99 SOURCE SALES(2).
      10 COL 27 PIC $(7)9.99 SOURCE SALES(3).
      10 COL 37 PIC $(7)9.99 SOURCE SALES(4).
      

      And then usingSTEPandVARYING

      10 COL 7  OCCURS 4 TIMES STEP 10 VARYING QTR FROM 1 BY 1
                PIC $(7)9.99 SOURCE SALES(QTR).
      

5.9.32. OVERLINE

OVERLINE Attribute Syntax

 OVERLINE
 ~~~~~~~~
This syntax is valid in the following sections:
SCREEN

TheOVERLINEclause will introduce a horizontal line at the top edge of a screen field.

  1. TheLEFTLINE(see LEFTLINE),OVERLINEandUNDERLINE(see UNDERLINE) clauses may be used in any combination in a single field’s description.
  2. This clause is essentially non-functional when used within Windows command shell (cmd.exe) environments and running programs compiled using a GnuCOBOL implementation built using ’PDCurses’ (such as Windows/MinGW builds).
  3. Whether or not this clause operates on Cygwin or UNIX/Linux/OSX systems will depend upon the video attribute capabilities of the terminal output drivers and ’curses’ software being used.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.33. PICTURE

PICTURE Clause Syntax

 PICTURE IS picture-string
 ~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

The picture clause defines the class (numeric, alphabetic or alphanumeric), size and format of the data that may be contained by the data item being defined. Sometimes this role is assisted by theUSAGE(see USAGE) clause, and in a few instances will be assumed entirely by that clause.

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The reserved wordPICTUREmay be abbreviated asPIC Most programmers prefer to use the latter.
  3. A picture clause may only be specified on an elementary item.
  4. A <picture-string> is a sequence of the special symbols$*+,-./0(zero),9ABCRDBSVXandZ
  5. In general, each picture symbol represents either a single character in storage or a single decimal digit. There are a few exceptions, and they will be discussed as needed.
  6. When a <picture-string> contains a repeated sequence of symbols —PIC 9999/99/99— for example, the repetition can be specified using a parenthetic repeat count, as inPIC 9(4)/9(2)/9(2) Using repeat counts is optional and their use (or not) is entirely at the discretion of the programmer. Many programmers use repetition for small sequences PIC XXX and repeat counts for larger ones PIC 9(9)
  7. This first set of picture symbols defines the basic data type of a data item. Each symbol represents a single character’s worth of storage.
    A

    Defines storage reserved for a single alphabetic character AZaz.

    N

    Defines storage reserved for a single character in the computer’s ’National Character set

    X

    Defines storage reserved for a single alphanumeric character (any character).

    9

    Defines storage reserved for a single numeric digit character 09.

    Typically, only one kind of each of those symbols is used in the same picture clause, but that isn’t a requirement. Data items that, of the three symbols above, use nothing butApicture symbols are known as ’Alphabetic Data Items

    If you need to allocate space for a data item whose format is two letters followed by five digits followed by three letters, you could use the <picture-string>AA99999AAAA(2)9(5)A(3)XXXXXXXXXXorX(10) There is absolutely no functional difference whatsoever between the four — none of them provide any functionality the others do not. The first two probably make for better documentation of the expected field contents, but they don’t provide any run-time enforcement capabilities.

    As far as enforcement goes, however, both alphabetic and numeric picture strings do provide for both compile-time and run-time enforcement capabilities. In the case of compilation enforcement, the compiler can issue warning messages if you attempt to specify a non-numeric value for a numeric data item or if you attempt toMOVE(see MOVE) a non-numeric data item to one that is numeric. Similar capabilities exist for alphabetic data items. At run-time, you may use a special class test (see Class Conditions) to determine if the contents of a data item are entirely numeric or entirely alphabetic.

  8. The following picture symbols may be used with numeric data items.
    P

    Defines an implied digit position that will be considered to be a zero when the data item is referenced at run-time. This symbol is used to allow data items that will contain very large values to be allocated using less storage by assuming a certain number of trailing zeros (one perP to exist at the end of values.

    ThePsymbol is not allowed in conjunction withN

    ThePsymbol may only be used at the beginning or end of a picture clause.

    Pis a repeatable symbol.

    All computations andMOVE(see MOVE) operations involving such a data item will behave as if the zeros were actually there.

    For example, let’s say you need to allocate a data item that contains however many millions of dollars of revenue your company has in gross revenues this year:

    01 Gross-Revenue PIC 9(9).

    In which case 9 characters of storage will be reserved. The values 000000000 through 999999999 will represent the gross-revenues. But, if only the millions are tracked (meaning the last six digits are always going to be 0), you could define the field as:

    01 Gross-Revenue PIC 9(3)P(6).

    Whenever Gross-Revenue is referenced in calculations, or whenever its value is moved to another data item, the value of Gross-Revenue will be treated as if it is nnn000000, where ’nnn’ is the actual value in storage.

    If you wanted to store the value 128 million into that field, you would do so as if theP were9:

    MOVE 128000000 TO Gross-Revenue

    ADISPLAY(see DISPLAY) of a data item containingPsymbols is a little strange. The value displayed will be what is actually in storage, but the total size of the displayed value will be as if thePsymbols had been9. Thus, after the above statement established a value for Gross-Revenue, aDISPLAY Gross-Revenuewould produce output of ’000000128’.

    S

    This symbol, if used, must be the very first symbol in thePICTUREvalue. ASindicates that the data item isSigned meaning that negative values are possible for this data item. Without anS any negative values stored into this data item via aMOVEor arithmetic statement will have the negative sign stripped from it (in effect becoming the absolute value).

    TheSsymbol is not allowed in conjunction withN

    TheSsymbol may only occur once in a picture string. See SIGN IS, for further discussion of how negative values may be stored in a numeric data item.

    V

    This symbol is used to define where an implied decimal-point (if any) is located in a numeric item. Just as there may only be a single decimal point in a number so may there be no more than oneVin aPICTURE Implied decimal points occupy no space in storage — they just specify how values are used. For example, if the value1234is in storage in a field defined as PIC 999V9, that value would be treated as 123.4 in any statements that referenced it.

    TheVsymbol is not allowed in conjunction withN

    TheVsymbol may only occur once in a picture string.

  9. Any editing symbols introduced past this point will, if coded in the picture clause of an otherwise numeric data item, transform that data item from a numeric to a ’Numeric Edited
  10. The following are the fixed insertion editing symbols that may be specified in a picture string. Each of these editing symbols will insert a special character into the field value at the position it is specified in the picture string. These editing symbols will each introduce one extra character into the total field size for each occurrence of the symbol in the picture string.
    B

    TheBediting symbol introduces a blank into the field value for each occurrence.

    MultipleBsymbols may be coded.

    The following example will format a ten digit number (presumably a telephone number) into a### ### ####layout:

        ...
            05 Phone-Number       PIC 9(3)B9(3)B9(4).
        ...
            MOVE 5185551212 TO Phone-Number
            DISPLAY Phone-Number
    

    This code will display518 555 1212

    0

    The0(zero) editing symbol introduces one "0" character into the field value for each occurrence in the picture string.

    Multiple0symbols may be coded.

    Here’s an example:

        ...
            05  Output-Item     PIC 909090909.
        ...
            MOVE 12345 TO Output-Item
            DISPLAY Output-Item
    

    The above will display102030405

    /

    The/editing symbol inserts one "/" character into the field value for each occurrence in the picture string.

    Multiple/symbols may be coded.

    This editing symbol is most-frequently used to format dates, as follows:

        ...
            05  Year-Month-Day   PIC 9(4)/9(2)/9(2).
        ...
            MOVE 20140207 TO Year-Month-Day
            DISPLAY Year-Month-Day
    

    This example displays2014/02/07

  11. The following are the numeric formatting symbols that may be specified in a picture string. Each of these editing symbols will insert special characters into the field value to present numbers in a "friendly" format. These editing symbols will each introduce one extra character into the total field size for each occurrence of the symbol in the picture string. Numeric fields whose picture clause contains these characters may neither be used as source fields in any calculation nor may they serve as source fields for the transfer of data values to any data item other than an alphanumeric field.
    .

    The.symbol inserts a decimal point into a numeric field value. When the contents of a numeric data item sending field are moved into a receiving data item whose picture clause contains the.editing symbol, implied V or actual decimal point in the sending data item or literal, respectively, will be aligned with the.symbol in the receiving field. Digits are then transferred from the sending to the receiving field outward from the sending field’s "V" or ".", truncating sending digits if there aren’t enough positions in the receiving field. Any digit positions in the receiving field that don’t receive digits from the sending field, if any, will be set to 0.

    The.symbol is not allowed in conjunction withN

    An example will probably help:

        ...
        05  Source-Field   PIC 9(2)V9 VALUE 7.2.
        05  Dest-Field     PIC 9(5).9(2).
        ...
        MOVE 1234567.89 TO Dest-Field
        DISPLAY Dest-Field
        MOVE 19 TO Dest-Field
        DISPLAY Dest-Field
        MOVE Source-Field TO Dest-Field
        DISPLAY Dest-Field
    

    The example will display three results —34567.8900019.00and00007.20

    Both data item definitions appear to have two decimal points in their picture clauses. They actually don’t, because the last character of every data item definition is always a period — the period that ends the definition.

    ,

    The,symbol serves as a thousands separator. Many times, you’ll see large numbers formatted with these symbols — for example, 123,456,789. This can be accomplished easily by adding thousands separator symbols to a picture string. Thousands separator symbols that aren’t needed will behave as if they were9.

    The,symbol is not allowed in conjunction withN

    Here’s an example:

        ...
        05  My-Lottery-Winnings   PIC 9(3),9(3),9(3).
        ...
        MOVE 12345 TO My-Lottery-Winnings
        DISPLAY My-Lottery-Winnings
    

    The value0000012,345(a very disappointing one for my retirement plans, but a good thousands separator demo) will be displayed. Notice how, since the first comma wasn’t needed due to the meagre amount I won, it behaved like another "9".

    If desired, you may reverse the roles of the.and,editing symbols by specifyingDECIMAL POINT IS COMMAin theSPECIAL-NAMES(see SPECIAL-NAMES) paragraph.

  12. The following are insertion symbols. They are used to insert an extra character (two in the case of "CR" and "DB") to signify the sign (positive or negative) of the numeric value that is moved into the field whose picture string contains one of these symbols, or the fact that the data item represents a currency (money) amount. Only one of the+-CRorDBsymbols may be used in a picture clause. In this context, when any of these symbols are used in a <picture-string>, they must be at the end. The+-and/or currency symbols may also be used as floating editing symbols at the beginning of the <picture-string> — a subject that will be covered in the next numbered paragraph.
    +

    If the value of the numeric value moved into the field is positive (0 or greater), a "+" character will be inserted. If the value is negative (less than 0), a "-" character is inserted.

    The+symbol is not allowed in conjunction withN

    -

    If the value of the numeric value moved into the field is positive (0 or greater), a space will be inserted. If the value is negative (less than 0), a "-" character is inserted.

    The-symbol is not allowed in conjunction withN

    CR

    This symbol is coded as the two characters "C" and "R". If the value of the numeric value moved into the field is positive (0 or greater), two spaces will be inserted. If the value is negative (less than 0), the characters "CR" (credit) are inserted.

    TheCRsymbol is not allowed in conjunction withN

    DB

    This symbol is coded as the two characters "D" and "B". If the value of the numeric value moved into the field is positive (0 or greater), two spaces will be inserted. If the value is negative (less than 0), the characters "DB" (debit) are inserted.

    TheDBsymbol is not allowed in conjunction withN

    $

    Regardless of the value moved into the field, this symbol will insert the currency symbol into the data item’s value in the position where it occurs in the <picture-string> (see SPECIAL-NAMES).

    The$symbol is not allowed in conjunction withN

  13. These editing symbols are known as floating replacement symbols. These symbols may occur in sequences before any9editing symbols in the <picture-string> of a numeric data item. Using these symbols transforms that numeric data item into a numerid edited data item, which can no longer be used in calculations or subscripts.
  14. Each of the following symbols behave like a9 until such point as all digits in the numeric value are exhausted and leading zeros are about to be inserted. In effect, these editing symbols define what should happen to those leading zero.
    $

    Of those currency symbols that correspond to character positions in which leading zeros reside, the right-most will have its "0" value replaced by the currency symbol in-effect for the program (see SPECIAL-NAMES). Any remaining leading zero values occupying positions described by this symbol will be replaced by spaces.

    The$symbol is not allowed in conjunction withN

    Any currency symbol coded to the right of a.will be treated exactly like a9

    *

    This symbol is referred to as a check protection symbol. All check-protection symbols that correspond to character positions in which leading zeros reside will have their "0" values replaced by "*".

    The*symbol is not allowed in conjunction withN

    Any check-suppression symbol coded to the right of a.will be treated exactly like a9

    +

    Of those+symbols that correspond to character positions in which leading zeros reside, the right-most will have its "0" value replaced by a "+" if the value in the data item is zero or greater or a "-" otherwise. Any remaining leading zero values occupying positions described by this symbol will be replaced by spaces. You cannot use both+and-in the same <picture-string>.

    The+symbol is not allowed in conjunction withN

    Any+symbol coded to the right of a.will be treated exactly like a9

    -

    Of those-symbols that correspond to character positions in which leading zeros reside, the right-most will have its "0" value replaced by a space if the value in the data item is zero or greater or a "-" otherwise. Any remaining leading zero values occupying positions described by this symbol will be replaced by spaces. You cannot use both+and-in the same <picture-string>.

    The-symbol is not allowed in conjunction withN

    Any-symbol coded to the right of a.will be treated exactly like a9

    Z

    AllZsymbols that correspond to character positions in which leading zeros reside will have their "0" values replaced by spaces.

    Any zero-suppression symbol coded to the right of a.will be treated exactly like a9

    Zand*should not be coded in the same <picture-string>

    +and-should not be coded in the same <picture-string>

    When multiple floating symbols are coded, even if there is only one of them used they will all be considered floating and will all be able to assume each other’s properties. For example, if a data item has aPIC +$ZZZZ9.99<picture-string>, and a value of 1 is moved to that field at run-time, the resulting value will be (the b symbol represents a space)bbbb+$1.00 This is not consistent with many other COBOL implementations, where the result would have been+$bbbb1.00

    Most other COBOL implementations reject the use of multiple occurrences of multiple floating editing symbols. For example, they would reject <picture-string>s such as+++$$$9.99$$$ZZZ9.99and so on. GnuCOBOL accepts these. Programmers creating GnuCOBOL programs should avoid such <picture-string>s if there is any likelihood that those programs may be used with other COBOL implementations.

5.9.34. PRESENT WHEN

PRESENT-WHEN Clause Syntax

 PRESENT WHEN condition-name
 ~~~~~~~ ~~~~
This syntax is valid in the following sections:
REPORT

This clause names an existingCondition Name(see Condition Names) that will serve as a switch controlling the presentation or suppression of a report group.

  1. If the specified condition-name has a value of FALSE when aGENERATEstatement (see GENERATE) causes a report group to be presented, the presentation of that group will be suppressed.
  2. If the condition-name has a value of TRUE, the group will be presented.
  3. See Condition Names, for more information.

5.9.35. PROMPT

PROMPT Clause Syntax

 PROMPT [ CHARACTER IS literal-1 | identifier-1 ]
 ~~~~~~   ~~~~~~~~~

This syntax is valid in the following sections:
SCREEN

This clause defines the character that will be used as the fill-character for any input fields on the screen.

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The default prompt character, should noCHARACTERspecification be coded, or should thePROMPTclause be absent altogether, is an underscore ("_").
  3. Prompt characters will be automatically transformed into spaces upon input.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.36. PROTECTED

PROTECTED Attribute Syntax

 PROTECTED SIZE IS { identifier }
 ~~~~~~~~  ~~~~    { integer    }
This syntax is valid in the following sections:
SCREEN
  1. ThePROTECTEDextended clause will effect the specified field to be limited in size, regardless of the picture size. OR DOES IT?
  2. The SIZE phrase specifies the size (length) of the field. After the ACCEPT or DISPLAY is finished, the cursor is placed immediately after the field defined by this clause, unless this would place the cursor outside of the current terminal window. In this case, the cursor is wrapped around to the beginning of the next line (scrolling the window if necessary).
  3. If the SIZE phrase is not used, then the field length defaults to the size of the item being accepted or displayed. If the CONVERT phrase is used, however, then the size of the field depends on the data type of the item and the verb being used.
    1. If the DISPLAY verb is executing, then the size is the same as if the CONVERT phrase were not specified except for numeric items. For numeric items, the size is the number of digits in the item, plus one if it is not an integer, plus one if it is signed. The remaining cases cover the size when an ACCEPT statement is used.
    2. If the item is numeric or numeric edited, then the size is the number of digits in the item, plus one if it is not an integer, plus one if it is signed.
    3. If the item is alphanumeric edited, then the size is set to the number of "A" or "X" positions specified in its PICTURE clause.
    4. For all other data types, the field size is set to the size of the item (same as if CONVERT were not specified).
  4. Note that the OUTPUT phrase changes the way in which the default field size is computed. See that heading above for details. Also note that the OUTPUT phrase affects only the way items are displayed on the screen; the internal format of accepted data is not affected.
  5. Note that you cannot supply the CONVERT phrase in the Screen Section. Thus the size of a Screen Section field is always the size of its screen entry unless the SIZE phrase is specified.

5.9.37. REDEFINES

REDEFINES Clause Syntax

 REDEFINES identifier-1
 ~~~~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE

TheREDEFINESclause causes the data item in who’s definition theREDEFINESclause is specified (hereafter referred to as the redefines object) to occupy the same physical storage space as <identifier-1> (hereafter referred to as the redefines subject).

  1. The following rules must all be followed in order to use REDEFINES:
    1. The level number of both the subject and object data items must be the same.
    2. The level numbers of both the subject and object data items cannot be 66, 78 or 88.
    3. Ifnrepresents the level number of the object, then no other data items with level numbernmay be defined between the subject and object data items unless they too areREDEFINESof the subject.
    4. Ifnrepresents the level number of the object, then no other data items with a level number numerically less thannmay be defined between the subject and object data items.
    5. The total allocated size of the subject data item must be the same as the total allocated size of the object data item.
    6. NoOCCURS(see OCCURS) clause may be part of the definition of either the subject or object data items. Either or both, however, may be group items that contain data items withOCCURSclauses.
    7. NoVALUE(see VALUE) clause may be defined on the object data item, and no data items subordinate to the object data item may haveVALUEclauses, with the exception of level-88 condition names.

5.9.38. RENAMES

RENAMES Clause Syntax

 RENAMES identifier-1 [ THRU|THROUGH identifier-2
 ~~~~~~~                ~~~~ ~~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE

TheRENAMESclause regroups previously defined items by specifying alternative, possibly overlapping, groupings of elementary data items.

  1. The reserved wordsTHRUandTHROUGHare interchangeable.
  2. You must use the level number 66 for data description entries that contain theRENAMESclause.
  3. The <identifier-1> and <identifier-2> data items, along with all data items defined between those two data items in the program source, must all be contained within the same 01-level record description.
  4. See 66-Level Data Items, for additional information on the RENAMES clause.

5.9.39. REQUIRED

REQUIRED Attribute Syntax

 REQUIRED
 ~~~~~~~~
This syntax is valid in the following sections:
SCREEN

This clause forces the user to enter data into the field it is specified on (or into all subordinate input-capable fields ifREQUIREDis specified on a group item).

  1. TheEMPTY-CHECK(see EMPTY-CHECK) andREQUIREDclauses are interchangeable, and may not be used together in the same data item description.
  2. In order to take effect, the user must first move the cursor into the field having this clause in its definition.
  3. TheACCEPT screen-data-itemstatement (see ACCEPT screen-data-item) will ignore the Enter key and any other cursor-moving keystrokes that would cause the cursor to move to another screen item unless data has been entered into the field. Function keys will still be allowed to terminate theACCEPT
  4. In order to be functional, this attribute must be supported by the underlying ’curses’ package your GnuCOBOL implementation was built with. As of this time, the ’PDCurses’ package (used for native Windows or MinGW builds) does not supportREQUIRED

5.9.40. REVERSE-VIDEO

REVERSE-VIDEO Attribute Syntax

 REVERSE-VIDEO
 ~~~~~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

TheREVERSE-VIDEOattribute swaps the specified or impliedFOREGROUND-COLOR(see FOREGROUND-COLOR) andBACKGROUND-COLOR(see BACKGROUND-COLOR) attributes for the field whose definition contains this clause (or all subordinate fields if used on a group item).

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.41. SECURE

SECURE Attribute Syntax

 SECURE
 ~~~~~~
This syntax is valid in the following sections:
SCREEN

This clause will cause all data entered into the field to appear on the screen as asterisks.

  1. TheNO-ECHO(see NO-ECHO) andSECUREclauses are interchangeable, and may not be used together in the same data item description.
  2. This clause may only be used on a field allowing data entry (a field containing either theUSING(see USING) orTO(see TO) clause).

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.42. SIGN IS

SIGN-IS Clause Syntax

 SIGN IS LEADING|TRAILING [ SEPARATE CHARACTER ]
 ~~~~    ~~~~~~~ ~~~~~~~~   ~~~~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

This clause, allowable only forUSAGE DISPLAYnumeric data items, specifies how anSsymbol will be interpreted in a data item’s picture clause.

  1. The reserved wordsCHARACTERandISare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. Without theSEPARATE CHARACTER
    First/Last Digit Value For Positive Value for Negative
    0 0 p
    1 1 q
    2 2 r
    3 3 s
    4 4 t
    5 5 u
    6 6 v
    7 7 w
    8 8 x
    9 9 y
  3. If theSEPARATE CHARACTERclause is used, then an actual+or-character will be inserted into the field’s value as the first LEADING or last TRAILING character. Note that having this character embedded within the data item’s storage does not prevent the data item from being used as a source field in arithmetic operations.
  4. WhenSEPARATE CHARACTERis specified, theSsymbol in the data item’sPICTUREmust be counted when determining the data item’s size.
  5. Neither the presence of an encoded digit (see above) nor an actual+or-character embedded within the data item’s storage prevents the data item from being used as a source field in arithmetic operations.

5.9.43. SOURCE

SOURCE Clause Syntax

 SOURCE IS literal-1 | identifier-1 [ ROUNDED ]
 ~~~~~~                               ~~~~~~~
This syntax is valid in the following sections:
REPORT

This clause logically attaches a report section data item to another data item defined elsewhere in the data division.

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. When the report group containing this clause is presented, the value of the specified numeric literal or identifier will be automatically moved to the report data item prior to presentation.
  3. The specified identifier may be defined anywhere in the data division, but if it is defined in the report section it may only bePAGE-COUNTER
  4. ThePICTURE(see PICTURE) of the report data item must be such that it would be legal toMOVE(see MOVE) the specified literal or identifier to a data item with thatPICTURE
  5. TheROUNDEDoption comes into play should the number of digits to the right of an actual or assumed decimal point be different between the specified literal or identifier value (the "source value") and thePICTUREspecified for the field in whose definition theSOURCEclause appears (the "target field"). WithoutROUNDED excess digits in the source value will simply be truncated to fit the target field. WithROUNDED the source value will be arithmetically rounded to fit the target field. See ROUNDED, for information on theNEAREST-AWAY-FROM-ZEROrounding rule, which is the one that will apply.

5.9.44. SUM OF

SUM-OF Clause Syntax

 SUM OF { identifier-7 }... [ { RESET ON FINAL|identifier-8 } ]
 ~~~    { literal-2    }      { ~~~~~    ~~~~~              }
                              { UPON identifier-9           }
                                ~~~~
This syntax is valid in the following sections:
REPORT

TheSUMclause establishes a summation counter whose value will be arithmetically calculated whenever the field is presented.

  1. The reserved wordsOFandONare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. TheSUMclause may only appear in aCONTROL FOOTINGreport group.
  3. If the data item in which theSUMclause appears has been assigned it’s own identifier name, and that name is notFILLER then that data item is referred to as a sum counter.
  4. All <identifier-7> data items must be non-edited numeric in nature.
  5. If any <identifier-7> data item is defined in the report section, it must be a sum counter.
  6. Any <identifier-7> data items that are sum counters must either be defined in the same report group as the data item in which thisSUMclause appears or they must be defined in a report data item that exists at a lower level in this report’s control hierarchy. See Control Hierarchy, for additional information.
  7. ThePICTUREof the report data item in who’s description thisSUMclause appears in must be such that it would be legal toMOVE(see MOVE) the specified <identifier-7> or <literal-2> value to a data item with thatPICTURE
  8. The following points apply to theUPON
    1. The data item <identifier-9> must be the name of a detail group specified in the same report as the control footing group in which thisSUMclause appears.
    2. The presence of anUPONclause limits theSUMclause to adding the specified numeric literal or identifier value into the sum counter only when aGENERATE <identifier-9>statement is executed.
    3. If there is noUPONclause specified, the value of <identifier-7> or <literal-2> will be added into the sum counter whenever aGENERATE(see GENERATE) of any detail report group in the report is executed.
    4. If there is only a single detail group in the report’s definition, theUPONclause is meaningless.
  9. The following points apply to theRESET
    1. If theRESEToption is coded,FINALor <identifier-8> (whichever is coded on theRESET must be one of the report’s control breaks specified on theCONTROLSclause.
    2. If there is noRESEToption coded, the sum counter will be reset back to zero after each time the control footing containing theSUMclause is presented. This is the typical behaviour that would be expected.
    3. If, however, you want to reset theSUMcounter only when the control footing for a control break higher in the control hierarchy is presented, specify that higher control break on theRESEToption.

5.9.45. SYNCRONIZED

SYNCRONIZED Syntax

 SYNCRONIZED|SYNCHRONISED [ LEFT|RIGHT ]
 ~~~~        ~~~~           ~~~~ ~~~~~

TheLEFTandRIGHT(SYNCRONIZED) clauses are syntactically recognized but are otherwise non-functional.

This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE

This optional clause optimizes the storage of binary numeric items to store them in such a manner as to make it as fast as possible for the CPU to fetch them.

  1. The reserved wordsSYNCRONIZEDandSYNCHRONISEDare interchangeable, and may be abbreviated asSYNC
  2. If theSYNCRONIZEDclause is coded on anything but a numeric data item with aUSAGE(see USAGE) that specifies storage of data in a binary form, theSYNCRONIZEDclause will be ignored.
  3. Synchronization is performed (by the compiler) as follows:
    1. If the binary item occupies one byte of storage, no synchronization is performed.
    2. If the binary item occupies two bytes of storage, the binary item is allocated at the next half-word boundary.
    3. If the binary item occupies four bytes of storage, the binary item is allocated at the next word boundary.
    4. If the binary item occupies four bytes of storage, the binary item is allocated at the next word boundary.

5.9.46. TO

TO Clause Syntax

 TO identifier-5
 ~~
This syntax is valid in the following sections:
SCREEN

This clause logically attaches a screen section data item to another data item defined elsewhere in the data division.

  1. TheTOclause is used to define a data-entry field with no initial value; when a value is entered, it will be saved to the specified identifier.
  2. TheFROM(see FROM),TOUSING(see USING) andVALUE(see VALUE) clauses are mutually-exclusive in any screen section data item’s definition.

5.9.47. TYPE

TYPE Clause Syntax

 [ TYPE IS { RH|{REPORT HEADING}                      } ]
   ~~~~    { ~~  ~~~~~~ ~~~~~~~                       }
           { PH|{PAGE HEADING}                        }
           { ~~  ~~~~ ~~~~~~~                         }
           { CH|{CONTROL HEADING} FINAL|identifier-2  }
           { ~~  ~~~~~~~ ~~~~~~~  ~~~~~               }
           { DE|DETAIL                                }
           { ~~ ~~~~~~                                }
           { CF|{CONTROL FOOTING} FINAL|identifier-2  }
           { ~~  ~~~~~~~ ~~~~~~~  ~~~~~               }
           { PF|{PAGE FOOTING}                        }
           {  ~~ ~~~~ ~~~~~~~                         }
           { RF|{REPORT FOOTING}                      }
             ~~  ~~~~~~ ~~~~~~~
This syntax is valid in the following sections:
REPORT

This clause defines the type of report group that is being defined for a report.

  1. This clause is required on any 01-level data item definitions (other than 01-level constants) in the report section. This clause is invalid on any other report section data item definitions.
  2. There may be a maximum of one (1) report group perRDdefined with aTYPEofREPORT HEADINGPAGE HEADINGPAGE FOOTINGandREPORT FOOTING
  3. There must be either aCONTROL HEADINGor aCONTROL FOOTINGor both specified for each entry specified on theCONTROLS AREclause of theRD
  4. The various report groups that constitute a report may be defined in any order.
  5. See RWCS Lexicon, for a description of the seven different types of report groups.

5.9.48. UNDERLINE

UNDERLINE Attribute Syntax

 UNDERLINE
 ~~~~~~~~~
This syntax is valid in the following sections:
SCREEN

TheUNDERLINEclause will introduce a horizontal line at the bottom edge of a screen field.

  1. TheLEFTLINE(see LEFTLINE),OVERLINE(see OVERLINE) andUNDERLINEclauses may be used in any combination in a single field’s description.
  2. This clause is essentially non-functional when used within Windows command shell (cmd.exe) environments and running programs compiled using a GnuCOBOL implementation built using ’PDCurses’ (such as Windows/MinGW builds).
  3. Whether or not this clause operates on Cygwin or UNIX/Linux/OSX systems will depend upon the video attribute capabilities of the terminal output drivers and ’curses’ software being used.

See Color Palette and Video Attributes, for more information on screen colors and video attributes.

5.9.49. USAGE

USAGE Clause Syntax

 USAGE IS data-item-usage
 ~~~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT

TheUSAGEclause defines the format that will be used to store the value of a data item.

  1. The reserved wordISis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. The following table summarizes the various USAGE specifications available in GnuCOBOL.

    BINARY~~~~~~

    Range of Values: Defined by the quantity of9 and the presence or absence of anSin thePICTURE
    Storage Format: Compatible Binary Integer
    Negative Values Allowed?: IfPICTUREcontainsS
    PICTUREUsed?: Yes

    BINARY-C-LONG [ SIGNED ]~~~~~~~~~~~~~

    Same asBINARY-DOUBLE SIGNED

    BINARY-C-LONG UNSIGNED~~~~~~~~~~~~~ ~~~~~~~~

    Range of Values: Typically 0 to 4,294,967,295
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    BINARY-CHAR [ SIGNED ]~~~~~~~~~~~

    Range of Values: -128 to 127
    Storage Format: Native Binary Integer
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    BINARY-CHAR UNSIGNED~~~~~~~~~~~ ~~~~~~~~

    Range of Values: 0 to 255
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    BINARY-DOUBLE [ SIGNED ]~~~~~~~~~~~~~

    Range of Values: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    Storage Format: Native Binary Integer
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    BINARY-DOUBLE UNSIGNED~~~~~~~~~~~~~ ~~~~~~~~

    Range of Values: 0 to 18,446,744,073,709,551,615
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    BINARY-INT~~~~~~~~~~

    Same asBINARY-LONG SIGNED

    BINARY-LONG [ SIGNED ]~~~~~~~~~~~

    Range of Values: -2,147,483,648 – 2,147,483,647
    Storage Format: Native Binary Integer
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    BINARY-LONG UNSIGNED~~~~~~~~~~~ ~~~~~~~~

    Range of Values: 0 to 4,294,967,295
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    BINARY-LONG-LONG~~~~~~~~~~~~~~~~

    Same asBINARY-DOUBLE SIGNED

    BINARY-SHORT [ SIGNED ]~~~~~~~~~~~~

    Range of Values: -32,768 to 32,767
    Storage Format: Native Binary Integer
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    BINARY-SHORT UNSIGNED~~~~~~~~~~~~ ~~~~~~~~

    Range of Values: 0 to 65,535
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    COMPUTATIONAL~~~~

    Same asBINARY

    COMP[UTATIONAL]-1~~~~ ~~

    Same asFLOAT-SHORT

    COMP[UTATIONAL]-2~~~~ ~~

    Same asFLOAT-LONG

    COMP[UTATIONAL]-3~~~~ ~~

    Same asPACKED-DECIMAL

    COMP[UTATIONAL]-4~~~~ ~~

    Same asBINARY

    COMP[UTATIONAL]-5~~~~ ~~

    Range of Values: Depends on number of9 in thePICTUREand thebinary-sizesetting of the configuration file used to compile the program
    Storage Format: Native Binary Integer
    Negative Values Allowed?: IfPICTUREcontainsS
    PICTUREUsed?: Yes

    COMP[UTATIONAL]-6~~~~ ~~

    Range of Values: Defined by the quantity of9 and the presence or absence of anSin thePICTURE
    Storage Format: Unsigned Packed Decimal
    Negative Values Allowed?: No
    PICTUREUsed?: Yes

    COMP[UTATIONAL]-X~~~~ ~~

    Range of Values: If used withPIC X allocates one byte of storage perX range of values is 0 to max storable in that many bytes. If used withPIC 9 range of values depends on number of9 in PICTURE
    Storage Format: Native unsigned (X) or signed (9) Binary
    Negative Values Allowed?: IfPICTURE9 and containsS
    PICTUREUsed?: Yes

    DISPLAY~~~~~~~

    Range of Values: Depends onPICTURE– One character per X, A, 9, period, $, Z, 0, *, S (ifSEPARATE CHARACTERspecified), +, - or B symbol inPICTURE Add 2 more bytes if theDBorCRediting symbol is used
    Storage Format: Characters
    Negative Values Allowed?: IfPICTUREcontainsS
    PICTUREUsed?: Yes

    FLOAT-DECIMAL-16~~~~~~~~~~~~~~~~

    Range of Values: 9.999999999999999×10^384 to 9.999999999999999×10^384
    Storage Format: Native IEEE 754 Decimal64 Floating-point
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    FLOAT-DECIMAL-34~~~~~~~~~~~~~~~~

    Range of Values: -9.99999...×10^6144 to 9.99999...×10^6144
    Storage Format: Native IEEE 754 Decimal128 Floating-point
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    FLOAT-LONG~~~~~~~~~~

    Range of Values: Approximately -1.797693134862316×10^308 to 1.797693134862316×10^308
    Storage Format: Native IEEE 754 Binary64 Floating-point
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    FLOAT-SHORT~~~~~~~~~~~

    Range of Values: Approximately -3.4028235×10^38 to 3.4028235×10^38
    Storage Format: Native IEEE 754 Binary32
    Negative Values Allowed?: Yes
    PICTUREUsed?: No

    INDEX~~~~~

    Range of Values: 0 to maximum address possible (32 or 64 bits)
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    NATIONAL~~~~~~~~

    USAGE NATIONAL while syntactically recognized, is not supported by GnuCOBOL

    PACKED-DECIMAL~~~~~~~~~~~~~~

    Range of Values: Defined by the quantity of9 and the presence or absence of anSin the PICTURE
    Storage Format: Signed Packed Decimal
    Negative Values Allowed?: IfPICTUREcontainsS
    PICTUREUsed?: No

    POINTER~~~~~~~

    Range of Values: 0 to maximum address possible (32 or 64 bits)
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    PROCEDURE-POINTER~~~~~~~~~~~~~~~~~

    Same asPROGRAM-POINTER

    PROGRAM-POINTER~~~~~~~~~~~~~~~

    Range of Values: 0 to maximum address possible (32 or 64 bits)
    Storage Format: Native Binary Integer
    Negative Values Allowed?: No
    PICTUREUsed?: No

    SIGNED-INT~~~~~~~~~~

    Same asBINARY-LONG SIGNED

    SIGNED-LONG~~~~~~~~~~~

    Same asBINARY-DOUBLE SIGNED

    SIGNED-SHORT~~~~~~~~~~~~

    Same asBINARY-SHORT SIGNED

    UNSIGNED-INT~~~~~~~~~~~~

    Same asBINARY-LONG UNSIGNED

    UNSIGNED-LONG~~~~~~~~~~~~~

    Same asBINARY-DOUBLE UNSIGNED

    UNSIGNED-SHORT~~~~~~~~~~~~~~

    Same asBINARY-SHORT UNSIGNED
  3. Binary data (integer or floating-point) can be stored in either a Big-Endian or Little-Endian form.

    Big-endian data allocation calls for the bytes that comprise a binary item to be allocated such that the least-significant byte is the right-most byte. For example, a four-byte binary item having a value of decimal 20 would be big-endian allocated as 00000014 (shown in hexadecimal notation).

    Little-endian data allocation calls for the bytes that comprise a binary item to be allocated such that the least-significant byte is the left-most byte. For example, a four-byte binary item having a value of decimal 20 would be little-endian allocated as 14000000 (shown in hexadecimal notation).

    All CPUs are capable ofunderstandingbig-endian format, which makes it themost-compatibleform of binary storage across computer systems.

    Some CPUs – such as the Intel/AMD i386/x64 architecture processors used in most Windows PCs – prefer to process binary data stored in a little-endian format. Since that format is more efficient on those systems, it is referred to as thenativebinary format.

    On a system supporting only one format of binary storage (generally, that would be big-endian), the terms ’most-efficient’ and ’native format’ are synonymous.

  4. Data items that have theUNSIGNED
  5. Packed-decimal (i.e.USAGE PACKED-DECIMALUSAGE COMP-3orUSAGE COMP-6 data is stored as a series of bytes such that each byte contains two 4-bit fields, referred to as ’nibbles’ (since they comprise half a "byte", they’re just "nibbles" — don’t groan, I don’t just make this stuff up!). Each nibble represents a9in thePICTUREand each holds a single decimal digit encoded as its binary value (0 = 0000, 1 = 0001, … , 9 = 1001).

    The last byte of aPACKED-DECIMALorCOMP-3data item will always have its left nibble corresponding to the last9in thePICTUREand its right nibble reserved as a sign indicator. This sign indicator is always present regardless of whether or not thePICTUREincluded anSsymbol.

    The first byte of the data item will contain an unused left nibble if thePICTUREhad an even number of9symbols in it.

    The sign indicator will have a value of a hexadecimal A through F. Traditional packed decimal encoding rules call for hexadecimal values of F, A, C or E ("FACE") in the sign nibble to indicate a positive value and B or D to represent a negative value (hexadecimal digits 0-9 are undefined). Testing with a Windows MinGW/GnuCOBOL implementation shows that –– in fact –– hex digit D represents a negative number and any other hexadecimal digit denotes a positive number. Therefore, aPIC S9(3) COMP-3packed-decimal field with a value of -15 would be stored internally as a hexadecimal 015D in GnuCOBOL.

    If you attempt to store a negative number into a packed decimal field that has noSin itsPICTURE the absolute value of the negative number will actually be stored.

    USAGE COMP-6does not allow for negative values, therefore no sign nibble will be allocated. AUSAGE COMP-6data item containing an odd number of9symbols in itsPICTUREwill leave its leftmost nibble unused.

  6. TheUSAGEspecificationsFLOAT-DECIMAL-16andFLOAT-DECIMAL-34will encode data using IEEE 754Decimal64andDecimal128format, respectively. The former allows for up to 16 digits of exact precision while the latter offers 34. The phrase "exact precision" is used because the traditional binary renderings of decimal real numbers in a floating-point format FLOAT-LONGandFLOAT-SHORT for example) only yield an approximation of the actual value because many decimal fractions cannot be precisely rendered in binary. The Decimal64 and Decimal128 renderings, however, render decimal real numbers in encoded decimal form in much the same way thatPACKED-DECIMALrenders a decimal integer in digit-by-digit decimal form. The exact manner in which this rendering is performed is complex (Wikipedia has an excellent article on the subject – just search forDecimal64.
  7. GnuCOBOL storesFLOAT-DECIMAL-16andFLOAT-DECIMAL-34data items using either Big-Endian or Little-Endian form, whichever is native to the system.
  8. TheUSAGEspecificationsFLOAT-LONGandFLOAT-SHORTuse the IEEE 754Binary64andBinary32formats, respectively. These are binary encodings of real decimal numbers, and as such cannot represent every possible value between the minimum and maximum values in the range for those usages. Wikipedia has an excellent article on the Binary64 and Binary32 encoding schemes – just search onBinary32orBinary64

    GnuCOBOL storesFLOAT-LONGandFLOAT-SHORTdata items using either Big-Endian or Little-Endian form, whichever is native to the system.

  9. AUSAGEclause specified at the group item level will apply thatUSAGEto all subordinate data items, except those that themselves have aUSAGEclause.
  10. The onlyUSAGEthat is allowed in the report section isUSAGE DISPLAY

5.9.50. USING

USING Clause Syntax

 USING identifier-1
 ~~~~~
This syntax is valid in the following sections:
SCREEN

This clause logically attaches a screen section data item to another data item defined elsewhere in the data division.

  1. When the screen item whose definition this clause is part of is displayed, the value currently in <identifier-1> will be automatically moved into the screen item first.
  2. When the screen item whose definition this clause is part of (or its parent) is accepted, the current contents of the screen item will be saved back to <identifier-1> at the conclusion of theACCEPT
  3. TheFROM(see FROM),TO(see TO),USINGandVALUE(see VALUE) clauses are mutually-exclusive in any screen section data item’s definition.

5.9.51. VALUE

VALUE (Condition Names) Clause Syntax

 { VALUE IS   } {literal-1 [ THRU|THROUGH literal-2 ]}...
 { ~~~~~      }              ~~~~ ~~~~~~~
 { VALUES ARE }
   ~~~~~~

VALUE (Other Data Items) Syntax

 VALUE IS [ ALL ] literal-1
 ~~~~~      ~~~
This syntax is valid in the following sections:
FILE, WORKING-STORAGE, LOCAL-STORAGE, LINKAGE, REPORT, SCREEN

TheVALUEclause is used to define condition names or to assign values (at compilation time) to data items.

  1. The reserved wordsAREandISare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. This clause cannot be specified on the same data item as aFROM(see FROM),TO(see TO) orUSING(see USING) clause.
  3. The following points apply to using theVALUEclause in the definition of a condition name:
    1. The clausesVALUE ISandVALUES AREare interchangeable.
    2. The reserved wordsTHRUandTHROUGHare interchangeable.
    3. See 88-Level Data Items, for a discussion of how this format ofVALUEis used to create condition names.
    4. See Condition Names, for a discussion of how condition names are used.
  4. The following points apply to using theVALUEclause in the definition of any other data item:
    1. In this context,VALUEspecifies an initial compilation-time value that will be assigned to the storage occupied by the data item in the program object code generated by the compiler.
    2. TheVALUEclause is ignored onEXTERNAL(see EXTERNAL) data items or on any data items defines as subordinate to anEXTERNALdata item.
    3. This format of theVALUEclause may not be used anywhere in the description of an 01 item (or any of it’s subordinate items) serving as anFDorSDrecord description.
    4. If the optionalALL
      PIC X(5) VALUE "A"      *> Abbbb
      PIC X(5) VALUE ALL "A"  *> AAAAA
      PIC 9(3) VALUE 1        *> 001
      PIC 9(3) VALUE ALL "1"  *> 111
      
    5. When used in the definition of a screen data item:
      1. A figurative constant may not be supplied as <literal-1>.
      2. AnyFROM(see FROM),TO(see TO) orUSING(see USING) clause in the same data item’s definition will be ignored.
      3. If there is no picture clause specified, the size of the screen data item will be the length of the <literal-1> value.
      4. If there is no picture clause and theALLoption is specified, theALLoption will be ignored.
    6. Giving a table an initial, compile-time value is one of the trickier aspects of COBOL data definition. There are basically three standard techniques and a fourth that people familiar with other COBOL implementations but new to GnuCOBOL may find interesting. So, here are the three standard approaches:
      1. Don’t bother worrying about it at compile-time. Use theINITIALIZE(see INITIALIZE) to initialize all data item occurrences in a table (at run-time) to their data-type-specific default values (numerics: 0, alphabetic and alphanumerics: spaces).
      2. Initialize small tables at compile time by including aVALUEclause on the group item that serves as a parent to the table, as follows:
        05  SHIRT-SIZES          VALUE "S 14M 15L 16XL17".
            10 SHIRT-SIZE-TBL    OCCURS 4 TIMES.
               15 SST-SIZE       PIC X(2).
               15 SST-NECK       PIC 9(2).
        
      3. Initialize tables of almost any size at compilation time by utilizing theREDEFINES(see REDEFINES) clause:
        05  SHIRT-SIZE-VALUES.
            10 PIC X(4)          VALUE "S 14".
            10 PIC X(4)          VALUE "M 15".
            10 PIC X(4)          VALUE "L 16".
            10 PIC X(4)          VALUEXL17
        05  SHIRT-SIZES          REDEFINES SHIRT-SIZE-VALUES.
            10 SHIRT-SIZE-TBL    OCCURS 4 TIMES.
               15 SST-SIZE       PIC X(2).
               15 SST-NECK       PIC 9(2).
        

        Admittedly, this table is much more verbose than the one shown with a groupVALUE What is good about this initialization technique, however, is that you can have as manyFILLERandVALUEitems as you need for a larger table, and those values can be as long as necessary!

    7. Many COBOL compilers do not allow the use ofVALUEandOCCURS(see OCCURS) on the same data item; additionally, they don’t allow aVALUEclause on a data item subordinate to anOCCURS GnuCOBOL, however, has neither of these restrictions!

      Observe the following example, which illustrates a fourth manner in which tables may be initialized in GnuCOBOL:

      05  X           OCCURS 6 TIMES.
          10 A        PIC X(1) VALUE '?'.
          10 B        PIC X(1) VALUE '%'.
          10 N        PIC 9(2) VALUE 10.
      

      In this example, all sixAitems will be initialized to "?", all sixBitems will be initialized to "%" and all sixNitems will be initialized to 10. It’s not clear exactly how many times this sort of initialization will be useful, but it’s there if you need it.

  5. TheFROM(see FROM),TO(see TO),USING(see USING) andVALUEclauses are mutually-exclusive in any screen section data item’s definition.

6. PROCEDURE DIVISION

PROCEDURE DIVISION Syntax

   PROCEDURE DIVISION [ { USING Subprogram-Argument...     } ]
   ~~~~~~~~~ ~~~~~~~~   { ~~~~~                            }
                        { CHAINING Main-Program-Argument...}
                          ~~~~~~~~
                      [ RETURNING identifier-1 ] .
 [ DECLARATIVES. ]      ~~~~~~~~~
   ~~~~~~~~~~~~
 [ Event-Handler-Routine... . ]

 [ END DECLARATIVES. ]
   ~~~ ~~~~~~~~~~~~
   General-Program-Logic

 [ Nested-Subprogram... ]

 [ END PROGRAM|FUNCTION name-1 ]
   ~~~ ~~~~~~~ ~~~~~~~~

The PROCEDURE DIVISION of any GnuCOBOL program marks the point where all executable code is written.

6.1. PROCEDURE DIVISION USING

PROCEDURE DIVISION Subprogram-Argument Syntax

 [ BY { REFERENCE [ OPTIONAL ]                       } ] identifier-1
      { ~~~~~~~~~   ~~~~~~~~                         }
      { VALUE [ [ UNSIGNED ] SIZE IS { AUTO      } ] }
        ~~~~~     ~~~~~~~~   ~~~~    { ~~~~      }
                                     { DEFAULT   }
                                     { ~~~~~~~   }
                                     { integer-1 }
  1. The reserved wordsBYandISare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words have no effect upon the program.
  2. TheUSING
  3. The calling program will pass zero or more data items, known as arguments, to this subprogram — there must be exactly as many <identifier-1> data items specified on the USING clause as the maximum number of arguments the subprogram will ever be passed.
  4. If a subprogram does not expect any arguments, it should not have aUSINGclause specified on it’s procedure division header.
  5. The order in which arguments are defined on theUSINGclause must correspond to the order in which those arguments will be passed to the subprogram by the calling program.
  6. The identifiers specified on theUSINGclause must be defined in the linkage section of the subprogram. No storage is actually allocated for those identifiers in the subprogram as the actual storage for them will exist in the calling program.
  7. A GnuCOBOL subprogram expects that all arguments to it will be one of two things:
    • The memory address of the actual data item (allocated in the calling program) that is being passed to the subprogram.
    • A numeric, full-word, binary value (i.e.USAGE BINARY-LONG(see USAGE)) which is the actual argument being passed to the subprogram.

    In the case of the former, theUSINGclause on the procedure division header should describe the argument via theBY REFERENCE

  8. BY REFERENCEis the assumed default for the firstUSINGargument should noBYclause be specified for it. Subsequent arguments will assume theBYspecification of the argument prior to them should they lack aBYclause of their own.
  9. Changes made by a subprogram to the value of an argument specified on theUSINGclause will "be visible" to the calling program only ifBY REFERENCEwas explicitly specified or implicitly assumed for the argument on the subprogram’s procedure division header and the argument was passed to the subprogramBY REFERENCEby the calling program. See Subprogram Arguments, for additional information on the mechanics of how arguments are passed to subprograms.
  10. The optionalSIZEclause allows you to specify the number of bytes aBY VALUEargument will occupy, withSIZE DEFAULTspecifying 4 bytes (this is the default if noSIZEclause is used),SIZE AUTOspecifying the size of the argument in the calling program andSIZE <integer-1>specifying a specific byte count.
  11. The optionalUNSIGNEDkeyword, legal only ifSIZE AUTOorSIZE <integer-1>are coded, will add the "unsigned" attribute to the argument’s specification in the C-language function header code generated for the subprogram. While not of any benefit when the calling program is a GnuCOBOL program, this can improve compatibility with a C-language calling program.
  12. TheOPTIONAL

6.2. PROCEDURE DIVISION CHAINING

PROCEDURE DIVISION Main-Program-Argument Syntax

 [ BY REFERENCE ] [ OPTIONAL ] identifier-1
      ~~~~~~~~~     ~~~~~~~~
  1. PROCEDURE DIVISION CHAININGmay only be coded in a main program (that is, the first program executed when a compiled GnuCOBOL compilation unit is executed). It cannot be used in any form of subprogram.
  2. TheCHAININGclause defines arguments that will be passed to a main program from the operating system. The argument identifiers specified on the CHAINING clause will be populated by character strings comprised of the parameters specified to the program on the command line that executed it, as follows:
    1. When a GnuCOBOL program is executed from a command-line, the complete command line text will be broken into a series of "tokens", where each token is identified as being a word separated from the others in the command text by at least one space. For example, if the command line was /usr/local/myprog THIS IS A TEST, there will be five tokens identified by the operating system — "/usr/local/myprog", "THIS", "IS", "A" and "TEST".
    2. Multiple space-delimited tokens may be treated as a single token by enclosing them in quotes. For example, there are only three tokens generated from the command line C:\Pgms\myprog.exe "THIS IS A" TEST — "C:\Pgms\myprog.exe", "THIS IS A" and "TEST". When quote characters are used to create multi-word tokens, the quote characters themselves are stripped from the token’s value.
    3. Once tokens have been identified, the first (the command) will be discarded; the rest will be stored into the "CHAINING" arguments when the program begins execution, with the 2nd token going to the 1st argument, the 3rd token going to the 2nd argument and so forth.
    4. If there are more tokens than there are arguments, the excess tokens will be discarded.
    5. If there are fewer tokens than there are arguments, the excess arguments will be initialized as if theINITIALIZE <identifier-1>(see INITIALIZE) statement were executed.
    6. All identifiers specified on the CHAINING clause should be defined as PIC X, PIC A, group items (which are treated implicitly as PIC X) or as PIC 9 USAGE DISPLAY. The use of USAGE BINARY (or the like) data items as CHAINING arguments is not recommended as all command-line tokens will be retained in their original character form as they are moved into the argument data items.
    7. If an argument identifier is smaller in storage size than the token value to be stored in it, the right-most excess characters of the token value will be truncated as the value is moved in. Any JUSTIFIED RIGHT clause on such an argument identifier will be ignored.
    8. If an argument is larger in storage size than the token value to be stored in it, the token value will be moved into the argument identifier in a left-justified manner. unmodified-modified byte positions in the identifier will be space filled, unless the argument identifier is defined as PIC 9 USAGE DISPLAY, in which case unmodified bytes will be filled with "0" characters from the systems native character set.

      This behaviour when the argument is defined asPIC 9may be unacceptable, as an argument defined asPIC 9(3)but passed in a value of "1" from the command line will receive a value of "100", not "001". Consider defining "numeric" command line arguments asPIC Xand then using theNUMVALintrinsic function (see NUMVAL) function to determine the proper numeric value.

6.3. PROCEDURE DIVISION RETURNING

PROCEDURE DIVISION RETURNING Syntax

 RETURNING identifier-1
 ~~~~~~~~~
  1. TheRETURNINGclause is optional within a subroutine, as not all subroutines return a value to their caller.
  2. TheRETURNINGclause is mandatory within a user-defined function, as all such must return a numeric result.
  3. The <identifier-1> data item should be defined as a USAGE BINARY-LONG data item.
  4. Main programs that wish to "pass back" a return code value to the operating system when they exit do not use RETURNING - they do so simply by MOVEing a value to theRETURN-CODEspecial register.
  5. This is not the only mechanism that a subprogram may use to pass a value back to it’s caller. Other possibilities are:
    1. The subprogram may modify any argument that is specified as "BY REFERENCE" on it’s PROCEDURE DIVISION header. Whether the calling program can actually "see" any modifications depends upon how the calling program passed the argument to the subprogram. See CALL, for more information.
    2. A data item with theGLOBAL(see GLOBAL) attribute specified in it’s description in the calling program is automatically visible to and updatable by a subprogram nested with the calling program. See Independent vs Contained vs Nested Subprograms, for more information on subprogram nesting.
    3. A data item defined with theEXTERNAL(see EXTERNAL) attribute in a subprogram and the calling program (same name in both programs) is automatically visible to and updatable by both programs, even if those programs are compiled separately from one another.

6.4. PROCEDURE DIVISION Sections and Paragraphs

The procedure division is the only one of the COBOL divisions that allows you to create your own sections and paragraphs. These are collectively referred to as ’Procedures’ Procedure names are optional in the procedure division and — when used — are named entirely according to the needs and whims of the programmer.

Procedure names may be up to thirty one (31) characters long and may consist of letters, numbers, dashes and underscores. A procedure name may neither begin nor end with a dash (-) or underscore (_) character. This means that "Main", "0100-Read-Transaction" and "17" are all perfectly valid procedure names.

There are three circumstances under which the use of certain GnuCOBOL statements or options will require the specification of procedures. These situations are:

  1. WhenDECLARATIVES(see DECLARATIVES) are specified.
  2. When theENTRYstatement (see ENTRY) is being used.
  3. When any procedure division statement that references procedures is used. These statements are:
    • ALTER <procedure-name>
    • GO TO <procedure-name>
    • MERGE … OUTPUT PROCEDURE <procedure-name>
    • PERFORM <procedure-name>
    • SORT … INPUT PROCEDURE <procedure-name>and/orSORT … INPUT PROCEDURE <procedure-name>

6.5. DECLARATIVES

DECLARATIVES Syntax

section-name-1 SECTION.

 USE { [ GLOBAL ] AFTER STANDARD { EXCEPTION } PROCEDURE ON { INPUT       } }
 ~~~ {   ~~~~~~                  { ~~~~~~~~~ }              { ~~~~~       } }
     {                           { ERROR     }              { OUTPUT      } }
     {                             ~~~~~                    { ~~~~~~      } }
     {                                                      { I-O         } }
     { FOR DEBUGGING ON { procedure-name-1           }      { ~~~         } }
     {     ~~~~~~~~~    { ALL PROCEDURES             }      { EXTEND      } }
     {                  { ~~~ ~~~~~~~~~~             }      { ~~~~~~      } }
     {                  { REFERENCES OF identifier-1 }      { file-name-1 } }
     {                                                                      }
     { [ GLOBAL ] BEFORE REPORTING identifier-2                             }
     {   ~~~~~~   ~~~~~~ ~~~~~~~~~                                          }
     {                                                                      }
     { AFTER EC|{EXCEPTION CONDITION}                                       }
             ~~  ~~~~~~~~~ ~~~~~~~~~

TheAFTER EXCEPTION CONDITION

  1. The reserved wordsAFTERFORONPROCEDUREandSTANDARDare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. ECandEXCEPTION CONDITIONare interchangeable.
  3. The declaratives area may contain any number of declarative procedures, but no two declarative procedures should be coded to trap the same event.
  4. The following points apply to theUSE BEFORE REPORTING
    1. <identifier-2> must be a report group.
    2. At run-time, the declaratives procedure will be executed prior to the processing of the specified report group’s presentation; within the procedure you may take either of the following actions:
      • You may adjust the value(s) of any items referenced inSUM(see SUM) orSOURCE(see SOURCE) clauses in the report group.
      • You may execute theSUPPRESS(see SUPPRESS) statement to squelch the presentation of the specified report group altogether. Note that you will be suppressing this one specific instance of that group’s presentation and not all of them.
  5. The following points apply to theUSE FOR DEBUGGING
    1. This clause allows you to define a declarative procedure that will be invoked whenever…
      • …<identifier-1> is referenced on any statement.
      • …<procedure-name-1> is executed.
      • …any procedure is executed ALL PROCEDURES.
    2. AUSE FOR DEBUGGINGdeclarative procedure will be ignored at compilation time unlessWITH DEBUGGING MODEis specified in theSOURCE-COMPUTER(see SOURCE-COMPUTER) paragraph. Neither the compiler’s-fdebugging-lineswitch
    3. AnyUSE FOR DEBUGGINGdeclarative procedures will be ignored at execution time unless the
    4. The typical use of aUSE FOR DEBUGGINGdeclarative procedure is to display theDEBUG-ITEMspecial register , which will be implicitly and automatically created in your program for you ifWITH DEBUGGING MODEis active.

      The structure of DEBUG-ITEM will be as follows:

      01  DEBUG-ITEM.
          05 DEBUG-LINE      PIC X(6).
          05 FILLER          PIC X(1) VALUE SPACE.
          05 DEBUG-NAME      PIC X(31).
          05 FILLER          PIC X(1) VALUE SPACE.
          05 DEBUG-SUB-1     PIC S9(4) SIGN LEADING SEPARATE.
          05 FILLER          PIC X(1) VALUE SPACE.
          05 DEBUG-SUB-2     PIC S9(4) SIGN LEADING SEPARATE.
          05 FILLER          PIC X(1) VALUE SPACE.
          05 DEBUG-SUB-3     PIC S9(4) SIGN LEADING SEPARATE.
          05 FILLER          PIC X(1) VALUE SPACE.
          05 DEBUG-CONTENTS  PIC X(31).
      

      where…

      DEBUG-LINE

      … is the program line number of the statement that triggered the declaratives procedure.

      DEBUG-NAME

      … is the procedure name or identifier name that triggered the declaratives procedure.

      DEBUG-SUB-1

      … is the first subscript value (if any) for the reference of the identifier that triggered the declaratives procedure.

      DEBUG-SUB-2

      … is the second subscript value (if any) for the reference of the identifier that triggered the declaratives procedure.

      DEBUG-SUB-3

      … is the third subscript value (if any) for the reference of the identifier that triggered the declaratives procedure.

      DEBUG-CONTENTS

      … is a (brief) statement of the manner in which the procedure that triggered the declaratives procedure was executed or the first 31 characters of the value of the identifier whose reference triggered the declaratives procedure (the value after the statement was executed).

  6. TheUSE AFTER STANDARD ERROR PROCEDURE
  7. TheGLOBAL(see GLOBAL) option, if used, allows a declarative procedure to be used across the program containing theUSEstatement and any subprograms nested within that program.
  8. Declarative procedures may not reference any other procedures defined outside the scope of DECLARATIVES.

6.6. Table References

For example, observe the following data structure which defines a 4 column by 3 row grid of characters:

01  GRID.
     05 GRID-ROW OCCURS 3 TIMES.
        10 GRID-COLUMN OCCURS 4 TIMES.
            15 GRID-CHARACTER       PIC X(1).

If the structure contains the following grid of characters:

A B C D
E F G H
I J K L

ThenGRID-CHARACTER (2, 3)references the "G" andGRID-CHARACTER (3, 2)references the "J".

Subscripts may be specified as numeric (integer) literals, numeric (integer) data items, data items created with any of the picture-less integerUSAGE(see USAGE) specifications,USAGE INDEXdata items or arithmetic expressions resulting in a non-zero integer value.

In the above examples, a comma is used as a separator character between the two subscript values; semicolons ; are also valid subscript separator characters, as are spaces! The use of a comma or semicolon separator in such a situation is technically optional, but by convention most COBOL programmers use one or the other. The use of no separator character (other than a space) is not recommended, even though it is syntactically correct, as this practice can lead to programmer-unfriendly code. It isn’t too difficult to read and understandGRID-CHARACTER(2 3) but it’s another story entirely when trying to comprehendGRID-CHARACTER(I + 1 J / 3)(instead ofGRID-CHARACTER(I + 1, J / 3). The compiler accepts it, but too much of this would make my head hurt.

6.7. Qualification of Data Names

To see qualification at work, observe the following segments of two data records defined in a COBOL program:

01  EMPLOYEE.                     01  CUSTOMER.
    05 MAILING-ADDRESS.               05 MAILING-ADDRESS.
       10 STREET        PIC X(35).       10 STREET        PIC X(35).
       10 CITY          PIC X(15).       10 CITY          PIC X(15).
       10 STATE         PIC X(2).        10 STATE         PIC X(2).
       10 ZIP-CODE.                      10 ZIP-CODE.
          15 ZIP-CODE-5 PIC 9(5).           15 ZIP-CODE-5 PIC 9(5).
          15 FILLER     PIC X(4).           15 FILLER     PIC X(4).

Now, let’s deal with the problem of setting the CITY portion of an EMPLOYEEs MAILING-ADDRESS to "Philadelphia". Clearly,MOVE 'Philadelphia' TO CITYcannot work because the compiler will be unable to determine which of the two CITY fields you are referring to.

In an attempt to correct the problem, we could qualify the reference to CITY asMOVE 'Philadelphia' TO CITY OF MAILING-ADDRESS

Unfortunately that too is insufficient because it still insufficiently specifies which CITY is being referenced. To truly identify which specific CITY you want, you’d have to codeMOVE 'Philadelphia' TO CITY OF MAILING-ADDRESS OF EMPLOYEE

Now there can be no confusion as to which CITY is being changed. Fortunately, you don’t need to be quite so specific; COBOL allows intermediate and unnecessary qualification levels to be omitted. This allowsMOVE 'Philadelphia' TO CITY OF EMPLOYEEto do the job nicely.

If you need to qualify a reference to a table, do so by coding something like<identifier-1> OF <identifier-2> ( subscript(s) )

The reserved wordINmay be used in lieu ofOF

6.8. Reference Modifiers

Reference Modifier (Format 1) Syntax

 identifier-1 [ OF|IN identifier-2 ] [ (subscript...) ] (start:[ length ])
                ~~ ~~

Reference Modifier (Format 2) Syntax

 intrinsic-function-reference (start:[ length ])

The <start> value indicates the starting character position being referenced (character position values start with 1, not 0 as is the case in some programming languages) and <length> specifies how many characters are wanted.

If no <length> is specified, a value equivalent to the remaining character positions from <start> to the end of <identifier-1> or to the end of the value returned by the function will be assumed.

Both <start> and <length> may be specified as integer numeric literals, integer numeric data items or arithmetic expressions with an integer value.

Here are a few examples:

CUSTOMER-LAST-NAME (1:3)

References the first three characters of CUSTOMER-LAST-NAME.

CUSTOMER-LAST-NAME (4:)

References all character positions of CUSTOMER-LAST-NAME from the fourth onward.

FUNCTION CURRENT-DATE (5:2)

References the current month as a 2-digit number in character form. See CURRENT-DATE, for more information.

Hex-Digits (Nibble + 1:1)

Assuming that "Nibble" is a numeric data item with a value in the range 0-15, and Hex-Digits is aPIC X(16)item with a value of "0123456789ABCDEF", this converts that numeric value to a hexadecimal digit.

Table-Entry (6) (7:5)

References characters 7 through 11 (5 characters in total) in the 6th occurrence of Table-Entry.

Reference modification may be used anywhere an identifier is legal, including serving as the receiving field of statements likeMOVE(see MOVE),STRING(see STRING) andACCEPT(see ACCEPT), to name a few.

6.9. Arithmetic Expressions

Arithmetic-Expression Syntax

 Unary-Expression-1 { **|^ } Unary-Expression-2
                    {  *|/ }
                    {  +|- }

Unary-Expression Syntax

 { [ +|- ] { ( Arithmetic-Expression-1 )          } }
 {         { [ LENGTH OF ] { identifier-1       } } }
 {         {   ~~~~~~ ~~   { literal-1          } } }
 {         {               { Function-Reference } } }
 { Arithmetic-Expression-2                          }

In complex expressions composed of multiple operators and operands, a precedence of operation applies whereby those operations having a higher precedence are computed first before operations with a lower precedence.

As is the case in almost any other programming language, the programmer is always free to use pairs of parenthesis to enclose sub-expressions of complex expressions that are to be evaluated before other sub-expressions rather than let operator precedence dictate the sequence of evaluation.

In highest to lowest order of precedence, here is a discussion of each category of operation:

Level 1 (Highest) — Unary Sign Specification +and-with a single argument)

The unary "minus" (-) operator returns the arithmetic negation of its single argument, effectively returning as its value the product of its argument and -1.

The unary "plus" (+) operator returns the value of its single argument, effectively returning as its value the product of its argument and +1.

Level 2 — Exponentiation **or^

The value of the left argument is raised to the power indicated by the right argument. Non-integer powers are allowed. The^and**operators are both supported to provide compatibility with programs written for other COBOL implementations.

Level 3 — Multiplication * and division /

The*operator computes the product of the left and right arguments while the/operator computes the value of the left argument divided by the value of the right argument. If the right argument has a value of zero, expression evaluation will be prematurely terminated before a value is generated. This may cause program failure at run-time.

A sequence of multiple 3rd-level operations A * B / C for example) will evaluate in strict left-to-right sequence if no parenthesis are used to control the order of evaluation.

Level 4 — Addition + or subtraction +

The+operator calculates the sum of the left and right arguments while the-operator computes the value of the right argument subtracted from that of the left argument.

A sequence of multiple 4th-level operations A - B + C for example) will evaluate in strict left-to-right sequence if no parenthesis are used to control the order of evaluation.

The syntactical rules of COBOL, allowing a dash (-) character in data item names, can lead to some ambiguity.

01  C        PIC 9 VALUE 5.
01  D        PIC 9 VALUE 2.
01  C-D      PIC 9 VALUE 7.
01  I        PIC 9 VALUE 0.
…
COMPUTE I=C-D+1

TheCOMPUTE(see COMPUTE) statement will evaluate the arithmetic expressionC-D+1and then save that result inI

What value will be stored inI The number 4, which is the result of subtracting the value ofD(2) from the value ofC(5) and then adding 1? Or, will it be the number 8, which is the value of adding 1 to the value of data itemC-D(7)?

The right answer is 8 — the value of data itemC-Dplus 1! Hopefully, that was the intended result.

The GnuCOBOL compiler actually went through the following decision-making logic when generating code for theCOMPUTEStatement:

  1. Is there a data item namedC-Ddefined? If so, use its value for the character sequenceC-D
  2. If there is noC-Ddata item, then are thereCandDdata items? If not, theCOMPUTEstatement is in error. If there are, however, then code will be generated to subtract the value ofDfromCand add 1 to the result.

Had there been at least one space to the left and/or the right of the- there would have been no ambiguity — the compiler would have been forced to use the individualCandDdata items.

To avoid any possible ambiguity, as well as to improve program readability, it’s considered good COBOL programming practice to always code at least one space to both the left and right of every operator in arithmetic expressions as well as the=sign on a COMPUTE.

Here are some examples of how the precedence of operations affects the results of arithmetic expressions (all examples use numeric literals, to simplify the discussion).

Expression Result Notes
3 * 4 + 1 13 * has precedence over +
4 * 2 ^ 3 - 10 22 2^3 is 8 (^ has precedence over *), times 4 is 32, minus 10 is 22.
(4 * 2) ^ 3 - 10 502 Parenthesis provide for a recursive application of the arithmetic expression rules, effectively allowing you to alter the precedence of operations. 4 times 2 is 8 (the use of parenthesis "trumps" the exponentiation operator, so the multiplication happens first); 8 ^ 3 is 512, minus 10 is 502.
5 / 2.5 + 7 * 2 - 1.15 15.35 Integer and non-integer operands may be freely intermixed

Of course, arithmetic expression operands may be numeric data items (any USAGE except POINTER or PROGRAM POINTER) as well as numeric literals.

6.10. Conditional Expressions

There are seven types of conditional expressions, as discussed in the following sections.

6.10.1. Condition Names

05  SHIRT-SIZE               PIC 99V9.
    88 TINY                  VALUE 0 THRU 12.5
    88 XS                    VALUE 13 THRU 13.5.
    88 S                     VALUE 14, 14.5.
    88 M                     VALUE 15, 15.5.
    88 L                     VALUE 16, 16.5.
    88 XL                    VALUE 17, 17.5.
    88 XXL                   VALUE 18, 18.5.
    88 XXXL                  VALUE 19, 19.5.
    88 VERY-LARGE            VALUE 20 THRU 99.9.

The condition namesTINYXSSMLXLXXLXXXLandVERY-LARGEwill have TRUE or FALSE values based upon the values within their parent data item (SHIRT-SIZE).

A program wanting to test whether or not the currentSHIRT-SIZEvalue can be classified asXLcould have that decision coded as a combined condition (the most complex type of conditional expression), as either:

IF SHIRT-SIZE = 17 OR SHIRT-SIZE = 17.5

- or -

IF SHIRT-SIZE = 17 OR 17.5

Or it could simply utilize the condition name XL as follows:

IF XL

6.10.2. Class Conditions

Class-Condition Syntax

 identifier-1 IS [ NOT ] { NUMERIC          }
                   ~~~   { ~~~~~~~          }
                         { ALPHABETIC       }
                         { ~~~~~~~~~~       }
                         { ALPHABETIC-LOWER }
                         { ~~~~~~~~~~~~~~~~ }
                         { ALPHABETIC-UPPER }
                         { ~~~~~~~~~~~~~~~~ }
                         { OMITTED          }
                         { ~~~~~~~          }
                         { class-name-1     }
  1. TheNUMERIC
  2. TheALPHABETIC
  3. TheALPHABETIC-LOWER
  4. TheNOToption reverses the TRUE/FALSE value of the condition.
  5. Note that what constitutes a "letter" (or upper/lower case too, for that manner) may be influenced through the use ofCHARACTER CLASSIFICATIONspecifications in theOBJECT-COMPUTER(see OBJECT-COMPUTER) paragraph.
  6. Only data items whoseUSAGE(see USAGE) is either explicitly or implicitly defined asDISPLAYmay be used inNUMERICor any of theALPHABETICclass conditions.
  7. Some COBOL implementations disallow the use of group items orPIC Aitems withNUMERICclass conditions and the use ofPIC 9items withALPHABETICclass conditions. GnuCOBOL has no such restrictions.
  8. TheOMITTED

The <class-name-1> option allows you to test for a user-defined class. Here’s an example. First, assume the followingSPECIAL-NAMES(see SPECIAL-NAMES) definition of the user-defined class "Hexadecimal":

SPECIAL-NAMES.
    CLASS Hexadecimal IS '0' THRU '9', 'A' THRU 'F', 'a' THRU 'f'.

Now observe the following code, which will execute the150-Process-Hex-Valueprocedure ifEntered-Valuecontains nothing but valid hexadecimal digits:

    IF Entered-Value IS Hexadecimal
        PERFORM 150-Process-Hex-Value
    END-IF

6.10.3. Sign Conditions

Sign-Condition Syntax

 identifier-1 IS [ NOT ] { POSITIVE }
                   ~~~   { ~~~~~~~~ }
                         { NEGATIVE }
                         { ~~~~~~~~ }
                         { ZERO     }
                           ~~~~
  1. APOSITIVE
  2. AZERO
  3. TheNOToption reverses the TRUE/FALSE value of the condition.

6.10.4. Switch-Status Conditions

Here are the relevant sections of code in a program named "testprog", which is designed to simply announce if SWITCH-1 is on:

…
ENVIRONMENT DIVISION.
SPECIAL-NAMES.
    SWITCH-1 ON STATUS IS Switch-1-Is-ON.
…
PROCEDURE DIVISION.
…
    IF Switch-1-Is-ON
        DISPLAY "Switch 1 Is On"
    END-IF
…

the following are two different command window sessions — the left on a Unix/Cygwin/OSX system and the right on a windows system — that will set the switch on and then execute the "testprog" program. Notice how the message indicating that the program detected the switch was set is displayed in both examples:

$ COB_SWITCH_1=ON           C:>SET COB_SWITCH_1=ON
$ export COB_SWITCH_1       C:>testprog
$ ./testprog                Switch 1 Is On
Switch 1 Is On              C:>
$

6.10.5. Relation Conditions

Relation-Condition Syntax

 { identifier-1            } IS [ NOT ] RelOp { identifier-2            }
 { literal-1               }      ~~~         { literal-2               }
 { arithmetic-expression-1 }                  { arithmetic-expression-2 }
 { index-name-1            }                  { index-name-2            }

RelOp Syntax

 { EQUAL TO                 }
 { ~~~~~                    }
 { EQUALS                   }
 { ~~~~~~                   }
 { GREATER THAN             }
 { ~~~~~~~                  }
 { GREATER THAN OR EQUAL TO }
 { ~~~~~~~      ~~ ~~~~~    }
 { LESS THAN                }
 { ~~~~                     }
 { LESS THAN OR EQUAL TO    }
 { ~~~~      ~~ ~~~~~       }
 { =                        }
 { >                        }
 { >=                       }
 { <                        }
 { <=                       }
  1. When comparing one numeric value to another, theUSAGE(see USAGE) and number of significant digits in either value are irrelevant as the comparison is performed using the actual algebraic values.
  2. When comparing strings, the comparison is made based upon the program’s collating sequence. When the two string arguments are of unequal length, the shorter is assumed to be padded (on the right) with a sufficient number of spaces as to make the two strings of equal length. String comparisons take place on a corresponding character-by-character basis, left to right, until the TRUE/FALSE value for the relation test can be established. Characters are compared according to their relative position in the program’sCOLLATING SEQUENCE(as defined inSPECIAL-NAMES(see SPECIAL-NAMES)), not according to the bit-pattern values the characters have in storage.
  3. By default, the program’sCOLLATING SEQUENCEwill, however, be based entirely on the bit-pattern values of the various characters.
  4. There is no functional difference between using the wordy version IS EQUAL TOIS LESS THAN …) versus the symbolic version =< …) of the actual relation operators.

6.10.6. Combined Conditions

Combined Condition Syntax

 [ ( ] Condition-1 [ ) ] { AND } [ ( ] Condition-2 [ ) ]
                         { ~~~ }
                         { OR  }
                         { ~~  }
  1. If either condition has a value of TRUE, the result ofOR
  2. In order forAND
  3. When chaining multiple, similar conditions together with the same operator (OR/AND), and left or right arguments have common subjects, it is possible to abbreviate the program code. For example:
    IF ACCOUNT-STATUS = 1 OR ACCOUNT-STATUS = 2 OR ACCOUNT-STATUS = 7
    

    Could be abbreviated as:

    IF ACCOUNT-STATUS = 1 OR 2 OR 7
    
  4. Just as multiplication takes precedence over addition in arithmetic expressions, so doesANDtake precedence overORin combined conditions. Use parenthesis to change this precedence, if necessary. For example:
    FALSE AND FALSE OR TRUE AND TRUE

    Evaluates to TRUE

    (FALSE AND FALSE) OR (TRUE AND TRUE)

    Evaluates to TRUE (since AND has precedence over OR) - this is identical to the previous example

    (FALSE AND (FALSE OR TRUE)) AND TRUE

    Evaluates to FALSE

6.10.7. Negated Conditions

Negated Condition Syntax

 NOT Condition-1
 ~~~
  1. TheNOToperator has the highest precedence of all logical operators, just as a unary minus sign (which "negates" a numeric value) is the highest precedence arithmetic operator.
  2. Parenthesis must be used to explicitly signify the sequence in which conditions are evaluated and processed if the default precedence isn’t desired. For example:
    NOT TRUE AND FALSE AND NOT FALSE

    Evaluates to FALSE AND FALSE AND TRUE which evaluates to FALSE

    NOT (TRUE AND FALSE AND NOT FALSE)

    Evaluates to NOT (FALSE) which evaluates to TRUE

    NOT TRUE AND (FALSE AND NOT FALSE)

    Evaluates to FALSE AND (FALSE AND TRUE) which evaluates to FALSE

6.11. Use of Periods

MOVE SPACES TO Employee-Address
ADD 1 TO Record-Counter
DISPLAY "Record-Counter=" Record-Counter

Some COBOL statements have a "scope of applicability" associated with them where one or more other statements can be considered to be part of or related to the statement in question. An example of such a situation might be the following, where the interest on a loan is being calculated and displayed — 4% interest if the loan balance is under $10000 and 4.5% otherwise (WARNING – the following code has an error!):

IF Loan-Balance < 10000
    MULTIPLY Loan-Balance BY 0.04 GIVING Interest
ELSE
    MULTIPLY Loan-Balance BY 0.045 GIVING Interest
DISPLAY "Interest Amount = " Interest

In this example, the IF statement actually has a scope that can include two sets of associated statements – one set to be executed when theIF(see IF) condition is TRUE and another if it is FALSE.

Unfortunately, there’s a problem with the above. A human being looking at that code would probably infer that theDISPLAY(see DISPLAY) statement, because of its lack of indentation, is to be executed regardless of the TRUE/FALSE value of theIFcondition. Unfortunately, the GnuCOBOL compiler (or any other COBOL compiler for that matter) won’t see it that way because it really couldn’t care less what sort of indentation, if any, is used. In fact, any COBOL compiler would be just as happy to see the code written like this:

IF Loan-Balance < 10000 MULTIPLY Loan-balance
BY 0.04 GIVING Interest ELSE MULTIPLY
Loan-Balance BY 0.045 GIVING Interest DISPLAY
"Interest Amount = " Interest

So how then do we inform the compiler that theDISPLAYstatement is outside the scope of theIF

That’s where sentences come in.

A COBOL ’Sentence

IF Loan-Balance < 10000
    MULTIPLY Loan-Balance BY 0.04 GIVING Interest
ELSE
    MULTIPLY Loan-Balance BY 0.045 GIVING Interest.
DISPLAY "Interest Amount = " Interest

See the period at the end of the secondMULTIPLY(see MULTIPLY)? That is what terminates the scope of theIF thus making theDISPLAYstatement’s execution completely independent of the TRUE/FALSE status of theIF

6.12. Use of VERB/END-VERB Constructs

Unfortunately, this caused some problems. Take a look at this code:

IF A = 1
    IF B = 1
        DISPLAY "A & B = 1"
ELSE *> This ELSE has a problem!
    IF B = 1
        DISPLAY "A NOT = 1 BUT B = 1"
    ELSE
        DISPLAY "NEITHER A NOR B = 1".

The problem with this code is that indentation — so critical to improving the human-readability of a program — can provide an erroneous view of the logical flow. AnELSEis always associated with the most-recently encounteredIF this means the emphasizedELSEwill be associated with theIF B = 1statement, not theIF A = 1statement as the indentation would appear to imply.

This sort of problem led to a band-aid solution — theNEXT SENTENCE

IF A = 1
    IF B = 1
        DISPLAY "A & B = 1"
    ELSE
        NEXT SENTENCE
ELSE
    IF B = 1
        DISPLAY "A NOT = 1 BUT B = 1"
    ELSE
        DISPLAY "NEITHER A NOR B = 1".

TheNEXT SENTENCEclause informs the compiler that if theB = 1condition is false, control should fall into the first statement that follows the next period.

With the 1985 standard for COBOL, a much more elegant solution was introduced. Any COBOL ’Verb

IF A = 1
    IF B = 1
        DISPLAY "A & B = 1"
    END-IF
ELSE
    IF B = 1
        DISPLAY "A NOT = 1 BUT B = 1"
    ELSE
        DISPLAY "NEITHER A NOR B = 1".

This new facility made the period almost obsolete, as our program segment would probably be coded like this today:

IF A = 1
    IF B = 1
        DISPLAY "A & B = 1"
    END-IF
ELSE
    IF B = 1
        DISPLAY "A NOT = 1 BUT B = 1"
    ELSE
        DISPLAY "NEITHER A NOR B = 1"
    END-IF
END-IF

COBOL (GnuCOBOL included) still requires that each procedure division paragraph contain at least one sentence if there is any executable code in that paragraph, but a popular coding style is now to simply code a single period right before the end of each paragraph.

The standard for the COBOL language shows the variousEND-verbclauses are optional because using a period as a scope-terminator remains legal.

If you will be porting existing code over to GnuCOBOL, you’ll find it an accommodating facility capable of conforming to whatever language and coding standards that code is likely to use. If you are creating new GnuCOBOL programs, however, I would strongly counsel you to use theEND-verbstructures in those programs.

6.13. Concurrent Access to Files

Not all GnuCOBOL implementations support file sharing and record-locking options. Whether they do or not depends upon the operating system they were built for and the build options that were used when the specific GnuCOBOL implementation was generated.

6.13.1. File Sharing

Any limitations imposed on a successfulOPEN(see OPEN) will remain in place until your program either issues aCLOSE(see CLOSE) against the file or the program terminates.

File sharing is controlled through the use of aSHARING

    SHARING WITH { ALL OTHER }
    ~~~~~~~      { ~~~       }
                 { NO OTHER  }
                 { ~~        }
                 { READ ONLY }
                   ~~~~ ~~~~

This clause may be used either in the file’sSELECTstatement (see SELECT), on theOPENstatement (see OPEN) which initiates your program’s use of the file, or both. If aSHARINGoption is specified in both places, the specifications made on theOPENstatement will take precedence over those from theSELECTstatement.

Here are the meanings of the three options:

ALL OTHER

When your program opens a file with this sharing option in effect, no restrictions will be placed on other programs attempting toOPENthe file after your program did. This is the default sharing mode.

NO OTHER

When your program opens a file with this sharing option in effect, your program announces that it is unwilling to allow any other program to have any access to the file as long as you are using that file;OPENattempts made in other programs will fail with a file status of 37 ("PERMISSION DENIED") until such time as youCLOSE(see CLOSE) the file.

READ ONLY

Opening a file with this sharing option indicates you are willing to allow other programs toOPENthe file for input while you have it open. If they attempt any otherOPEN theirs will fail with a file status of 37. Of course, your program may fail if someone else got to the file first and opened it with a sharing option that imposed file-sharing limitations.

If theSELECTof a file is coded with aFILE STATUSclause,OPENfailures — including those induced by sharing failures — will be detectable by the program and a graceful recovery (or at least a graceful termination) will be possible. If no such clause was coded, however, a runtime message will be issued and the program will be terminated.

6.13.2. Record Locking

The various I/O statements your program can execute are capable of imposing limitations on access by other concurrently-executing programs to the file record they just accessed. These limitations are syntactically imposed by placing a lock on the record using aLOCKclause. Other records in the file remain available, assuming that file-sharing limitations imposed at the time the file was opened didn’t prevent access to the entire file.

  1. If the GnuCOBOL build you are using was configured to use the Berkeley Database (BDB) package for indexed file I/O, record locking will be available by using the
  2. If theSELECT(see SELECT) statement or fileOPEN(see OPEN) specifiesSHARING WITH NO OTHER record locking will be disabled.
  3. If the file’sSELECTcontains aLOCK MODE IS AUTOMATIC
  4. If the file’sSELECTcontains aLOCK MODE IS MANUAL
  5. If theLOCK ONclause is specified in the file’sSELECT locks (either automatically or manually acquired) will continue to accumulate as more and more records are read, until they are explicitly released. This is referred to as ’multiple record locking

    Locks acquired vie multiple record locking remain in-effect until the program holding the lock…

    • …terminates, or …
    • …executes aCLOSEstatement (see CLOSE) against the file, or …
    • …executes anUNLOCKstatement (see UNLOCK) against the file, or …
    • …executes aCOMMITstatement (see COMMIT) or …
    • …executes aROLLBACKstatement (see ROLLBACK).
  6. If theLOCK ON
  7. ALOCKclause, which may be coded on aREAD(see READ),REWRITE(see REWRITE) orWRITEstatement (see WRITE) looks like this:
        { IGNORING LOCK    }
        { ~~~~~~~~ ~~~~    }
        { WITH [ NO ] LOCK }
        {        ~~   ~~~~ }
        { WITH KEPT LOCK   }
        {      ~~~~ ~~~~   }
        { WITH IGNORE LOCK }
        {      ~~~~~~ ~~~~ }
        { WITH WAIT        }
               ~~~~
    

    TheWITH [ NO ] LOCKoption is the only one available toREWRITEorWRITEstatements.

    The meanings of the various record locking options are as follows:

    IGNORING LOCK
    WITH IGNORE LOCK

    These options (which are synonymous) inform GnuCOBOL that any locks held by other programs should be ignored.

    WITH LOCK

    Access to the record by other programs will be denied.

    WITH NO LOCK

    The record will not be locked. This is the default locking option in effect for all statements.

    WITH KEPT LOCK

    When single record locking is in-effect, as a new record is accessed, locks held for previous records are released. By using this option, not only is the newly-accessed record locked (as WITH LOCK would do), but prior record locks will be retained as well. A subsequentREADwithout theKEPT LOCKoption will release all "kept" locks, as will theUNLOCKstatement.

    WITH WAIT

    This option informs GnuCOBOL that the program is willing to wait for a lock held (by another program) on the record being read to be released.

    Without this option, an attempt to read a locked record will be immediately aborted and a file status of 51 will be returned.

    With this option, the program will wait for a pre-configured time for the lock to be released. If the lock is released within the preconfigured wait time, the read will be successful. If the pre-configured wait time expires before the lock is released, the read attempt will be aborted and a 51 file status will be issued.

6.14. Common Clauses on Executable Statements

6.14.1. AT END + NOT AT END

AT END Syntax

 [ AT END imperative-statement-1 ]
      ~~~
 [ NOT AT END imperative-statement-2 ]
   ~~~    ~~~
  1. The following points pertain to the use of these clauses onREAD(see READ) andRETURN(see RETURN) statements:
    1. TheAT ENDclause will — if present — cause <imperative-statement-1> (see Imperative Statement) to be executed if the statement fails due to a file status of 10 (end-of-file). See File Status Codes, for a list of possible File Status codes.

      AnAT ENDclause will not detect other non-zero file-status values.

      Use aDECLARATIVES(see DECLARATIVES) routine or an explicitly-declared file status field tested after theREADorRETURNto detect error conditions other than end-of-file.

    2. ANOT AT ENDclause will cause <imperative-statement-2> to be executed if theREADorRETURNattempt is successful.
  2. The following points pertain to the use of these clauses onSEARCH(see SEARCH) andSEARCH ALL(see SEARCH ALL) statements:
    1. AnAT ENDclause detects and handles the case where either form of table search has failed to locate an entry that satisfies the search conditions being used.
    2. TheNOT AT ENDclause is not allowed on either form of table search.

6.14.2. CORRESPONDING

ADD CORRESPONDING group-item-1 TO group-item-2
MOVE CORRESPONDING group-item-1 TO group-item-2
SUBTRACT CORRESPONDING group-item-1 FROM group-item-2

This option allows one or more data items within one group item (<group-item-1> — the first named on the statement) to be paired with correspondingly-named (hence the name) in a second group item (<group-item-2> — the second named on the statement). The contents of <group-item-1> will remain unaffected by the statement while one or more data items within <group-item-2> will be changed.

In order for <data-item-1>, defined subordinate to group item <group-item-1> to be a "corresponding" match to <data-item-2> which is subordinate to <group-item-2>, each of the following must be true:

  1. Both <data-item-1> and <data-item-2> must have the same name, and that name may not explicitly or implicitly beFILLER
  2. Both <data-item-1> and <data-item-2>…
    1. …must exist at the same relative structural "depth" of definition within <group-item-1> and <group-item-2>, respectively
    2. …and all "parent" data items defined within each group item must have identical (but nonFILLER names.
  3. When used with aMOVEverb…
    1. …one of <data-item-1> or <data-item-2> (but not both) is allowed to be a group item
    2. …and it must be valid to move <data-item-1> TO <data-item-2>.
  4. When used withADDorSUBTRACTverbs, both <data-item-1> and <data-item-2> must be numeric, elementary, unedited items.
  5. Neither <data-item-1> nor <data-item-2> may be aREDEFINES(see REDEFINES) orRENAMES(see RENAMES) of another data item.
  6. Neither <data-item-1> nor <data-item-2> may have anOCCURS(see OCCURS) clause, although either may contain subordinate data items that do have anOCCURSclause (assuming rule 3a applies)

Observe the definitions of data items "Q" and "Y"…

01  Q.                           01  Y.
    03 X.                            02 A         PIC X(1).
       05 A         PIC 9(1).        02 G1.
       05 G1.                           03 G2.
          10 G2.                           04 B   PIC X(1).
             15 B   PIC X(1).        02 C         PIC X(1).
       05 C.                         02 G3.
          10 FILLER PIC X(1).           03 G5.
       05 G3.                              04 D   PIC X(1).
          10 G4.                        03 G6     PIC X(1).
             15 D   PIC X(1).        02 E         PIC 9(1).
       05 E         PIC X(1).        02 F         PIC X(1).
       05 F         REDEFINES V1     02 G         PIC X(4).
                    PIC X(1).        02 H         OCCURS 4 TIMES
       05 G.                                      PIC X(1).
          10 G6     OCCURS 4 TIMES   66 I         RENAMES E.
                    PIC X(1).        02 J.
       05 H         PIC X(4).           03 K.
       05 I         PIC 9(1).              04 L.
       05 J.                                  05 M.
          10 K.
             15 M   PIC X(1).

The following are the valid CORRESPONDING matches, assuming the statementMOVE CORRESPONDING X TO Yis being executed (there are no valid corresponding matches forADD CORRESPONDINGorSUBTRACT CORRESPONDINGbecause every potential match up violates rule #4):

A, B, C, G

The following are the CORRESPONDING match ups that passed rule #1 (but failed on another rule), and the reasons why they failed.

Data Item Failure Reason
D Fails due to rule #2b
E Fails due to rule #3b
F Fails due to rule #5
G1 Fails due to rule #3a
G2 Fails due to rule #3a
G3 Fails due to rule #3a
G4 Fails due to rule #1
G5 Fails due to rule #1
G6 Fails due to rule #6
H Fails due to rule #6
I Fails due to rule #5
J Fails due to rule #3a
K Fails due to rule #3a
L Fails due to rule #1
M Fails due to rule #2a

6.14.3. INVALID KEY + NOT INVALID KEY

INVALID KEY Syntax

 [ INVALID KEY imperative-statement-1 ]
   ~~~~~~~
 [ NOT INVALID KEY imperative-statement-2 ]
   ~~~ ~~~~~~~

Specification of anINVALID KEYclause will allow your program to trap an I/O failure condition (with an I/O error code in the file’sFILE-STATUS(see SELECT) field) that has occurred due to a record-not-found condition and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement).

An optionalNOT INVALID KEY

6.14.4. ON EXCEPTION + NOT ON EXCEPTION

ON EXCEPTION Syntax

 [ ON EXCEPTION imperative-statement-1 ]
      ~~~~~~~~~
 [ NOT ON EXCEPTION imperative-statement-2 ]
   ~~~    ~~~~~~~~~

Specification of an exception clause will allow your program to trap a failure condition that has occurred and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement). If such a condition occurs at runtime without having one of these clauses specified, an error message will be generated (by the GnuCOBOL runtime library) to the SYSERR device (pipe 2). The program may also be terminated, depending upon the type and severity of the error.

An optionalNOT ON EXCEPTION

6.14.5. ON OVERFLOW + NOT ON OVERFLOW

ON OVERFLOW Syntax

 [ ON OVERFLOW imperative-statement-1 ]
      ~~~~~~~~
 [ NOT ON OVERFLOW imperative-statement-2 ]
   ~~~    ~~~~~~~~

AnON OVERFLOWclause will allow your program to trap a failure condition that has occurred and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement). If such a condition occurs at runtime without having one of these clauses specified, an error message will be generated (by the GnuCOBOL runtime library) to the SYSERR device (pipe 2). The program may also be terminated, depending upon the type and severity of the error.

An optionalNOT ON OVERFLOW

6.14.6. ON SIZE ERROR + NOT ON SIZE ERROR

ON SIZE ERROR Syntax

 [ ON SIZE ERROR imperative-statement-1 ]
      ~~~~ ~~~~~
 [ NOT ON SIZE ERROR imperative-statement-2 ]
   ~~~    ~~~~ ~~~~~

Including anON SIZE ERRORclause on an arithmetic statement will allow your program to trap a failure of an arithmetic statement (either generating a result too large for the receiving field, or attempting to divide by zero) and handle it gracefully by executing <imperative-statement-1> (see Imperative Statement). Field size overflow conditions occur silently, usually without any runtime messages being generated, even though such events rarely lend themselves to generating correct results. Division by zero errors, when noON SIZE ERRORclause exists, will produce an error message (by the GnuCOBOL runtime library) to the SYSERR device (pipe 2) and will also abort the program.

An optionalNOT ON SIZE ERROR

6.14.7. ROUNDED

ROUNDED Syntax

 ROUNDED [ MODE IS { AWAY-FROM-ZERO         }
 ~~~~~~~   ~~~~    { ~~~~~~~~~~~~~~         }
                   { NEAREST-AWAY-FROM-ZERO }
                   { ~~~~~~~~~~~~~~~~~~~~~~ }
                   { NEAREST-EVEN           }
                   { ~~~~~~~~~~~~           }
                   { NEAREST-TOWARD-ZERO    }
                   { ~~~~~~~~~~~~~~~~~~~    }
                   { PROHIBITED             }
                   { ~~~~~~~~~~             }
                   { TOWARD-GREATER         }
                   { ~~~~~~~~~~~~~~         }
                   { TOWARD-LESSER          }
                   { ~~~~~~~~~~~~~          }
                   { TRUNCATION             }
                     ~~~~~~~~~~

The following rules apply to the rounding behaviour induced by this clause.

  1. Rounding only applies when the result being saved to a receiving field with aROUNDEDclause is a non-integer value.
  2. Absence of aROUNDEDclause is the same as specifyingROUNDED MODE IS TRUNCATION
  3. Use of aROUNDEDclause without aMODEspecification is the same as specifyingROUNDED MODE IS NEAREST-AWAY-FROM-ZERO

The behaviour of the eight different rounding modes is defined in the following table. Note that a "…" indicates the last digit repeats. The examples assume an integer receiving field.

AWAY-FROM-ZERO

Rounding is to the nearest value of larger magnitude.

-3.510 ⇒ -4 +3.510 ⇒ +4
-3.500 ⇒ -4 +3.500 ⇒ +4
-3.499… ⇒ -4 +3.499… ⇒ +4
-2.500 ⇒ -3 +2.500 ⇒ +3
-2.499… ⇒ -3 +2.499… ⇒ +3
NEAREST-AWAY-FROM-ZERO

Rounding is to the nearest value (larger or smaller). If two values are equally near, the value with the larger absolute value is selected.

-3.510 ⇒ -4 +3.510 ⇒ +4
-3.500 ⇒ -4 +3.500 ⇒ +4
-3.499… ⇒ -3 +3.499… ⇒ +3
-2.500 ⇒ -3 +2.500 ⇒ +3
-2.499… ⇒ -2 +2.499… ⇒ +2
NEAREST-EVEN

Rounding is to the nearest value (larger or smaller). If two values are equally near, the value whose rightmost digit is even is selected. This mode is sometimes called "Banker’s rounding".

-3.510 ⇒ -4 +3.510 ⇒ +4
-3.500 ⇒ -4 +3.500 ⇒ +4
-3.499… ⇒ -3 +3.499… ⇒ +3
-2.500 ⇒ -2 +2.500 ⇒ +2
-2.499… ⇒ -2 +2.499… ⇒ +2
NEAREST-TOWARD-ZERO

Rounding is to the nearest value (larger or smaller). If two values are equally near, the value with the smaller absolute value is selected.

-3.510 ⇒ -4 +3.510 ⇒ +4
-3.500 ⇒ -3 +3.500 ⇒ +3
-3.499… ⇒ -3 +3.499… ⇒ +3
-2.500 ⇒ -2 +2.500 ⇒ +2
-2.499… ⇒ -2 +2.499… ⇒ +2
PROHIBITED

No rounding is performed. If the value cannot be represented exactly in the desired format, the EC-SIZE-TRUNCATION condition (exception code 1005) is set (and may be retrieved via theACCEPT(see ACCEPT FROM Runtime-Info) statement) and the results of the operation are undefined.

-3.510 ⇒ Undefined +3.510 ⇒ Undefined
-3.500 ⇒ Undefined +3.500 ⇒ Undefined
-3.499… ⇒ Undefined +3.499… ⇒ Undefined
-2.500 ⇒ Undefined +2.500 ⇒ Undefined
-2.499… ⇒ Undefined +2.499… ⇒ Undefined
TOWARD-GREATER

Rounding is toward the nearest value whose algebraic value is larger.

-3.510 ⇒ -3 +3.510 ⇒ +4
-3.500 ⇒ -3 +3.500 ⇒ +4
-3.499… ⇒ -3 +3.499… ⇒ +4
-2.500 ⇒ -2 +2.500 ⇒ +3
-2.499… ⇒ -2 +2.499… ⇒ +3
TOWARD-LESSER

Rounding is toward the nearest value whose algebraic value is smaller.

-3.510 ⇒ -4 +3.510 ⇒ +3
-3.500 ⇒ -4 +3.500 ⇒ +3
-3.499… ⇒ -4 +3.499… ⇒ +3
-2.500 ⇒ -3 +2.500 ⇒ +2
-2.499… ⇒ -3 +2.499… ⇒ +2
TRUNCATION

Rounding is to the nearest value whose magnitude is smaller.

-3.510 ⇒ -3 +3.510 ⇒ +3
-3.500 ⇒ -3 +3.500 ⇒ +3
-3.499… ⇒ -3 +3.499… ⇒ +3
-2.500 ⇒ -2 +2.500 ⇒ +2
-2.499… ⇒ -2 +2.499… ⇒ +2

6.15. Special Registers

COB-CRT-STATUS

PIC 9(4) — This is the default data item allocated for use by theACCEPT <screen-data-item>statement (see ACCEPT screen-data-item), if noCRT STATUS(see SPECIAL-NAMES) clause was specified..

DEBUG-ITEM

Group Item — A group item in which debugging information generated by aUSE FOR DEBUGGINGsection in the declaratives area of the procedure division will place information documenting why theUSE FOR DEBUGGINGprocedure was invoked. Consult theDECLARATIVES(see DECLARATIVES) documentation for information on the structure of this register.

LINAGE-COUNTER

BINARY-LONG SIGNED — An occurrence of this register exists for each selected file having aLINAGE(see File/Sort-Description) clause. If there are multiple files whose file descriptions haveLINAGEclauses, any explicit references to this register will require qualification (usingOF file-name. The value of this register will be the current logical line number within the page body. The value of this register cannot be modified.

LINE-COUNTER

BINARY-LONG SIGNED — An occurrence of this register exists for each report defined in the program (via anRD(see REPORT SECTION)). If there are multiple reports, any explicit references to this register not made in the report section will require qualification OF report-name. The value of this register will be the current logical line number on the current page. The value of this register cannot be modified.

NUMBER-OF-CALL-PARAMETERS

BINARY-LONG SIGNED — This register contains the number of arguments passed to a subroutine — the same value that would be returned by theC$NARGbuilt-in system subroutine (see C$NARG). Its value will be zero when referenced in a main program. This register, when referenced from within a user-defined function, returns a value of one (1) if the function has any number of arguments and a zero if it has no arguments.

PAGE-COUNTER

BINARY-LONG SIGNED — An occurrence of this register exists for each report having anRD(see REPORT SECTION). If there are multiple such reports, any explicit references to this register not made in the report section will require qualification (OF report-name. The value of this register will be the current report page number. The value of this register cannot be modified.

RETURN-CODE

BINARY-LONG SIGNED — This register provides a numeric data item into which a subroutine mayMOVE(see MOVE) a value (which will then be available to the calling program) prior to transferring control back to the program that called it, or into which a main program mayMOVEa value before returning control to the operating system. Many built-in subroutines will return a value using this register. These values are — by convention — used to signify success (usually with a value of 0) or failure (usually with a non-zero value) of the process the program was attempting to perform. This register may also be modified by a subprogram as a result of that subprogram’s use of theRETURNING(see PROCEDURE DIVISION RETURNING) clause.

SORT-RETURN

BINARY-LONG SIGNED — This register is used to report the success/fail status of aRELEASE(see RELEASE) orRETURN(see RETURN) statement. A value of 0 is reported on success. A value of 16 denotes failure. AnAT END(see AT END + NOT AT END) condition on aRETURNis not considered a failure.

WHEN-COMPILED

PIC X(16) — This register contains the date and time the program was compiled in the format "mm/dd/yyhh.mm.ss". Note that only a two-digit year is provided.

6.16. Intrinsic Functions

MOVE FUNCTION LENGTH(Employee-Last-Name) TO Employee-LN-Len

Note how the wordFUNCTIONis part of the syntax when you use an intrinsic function. You can use intrinsic functions without having to include the reserved wordFUNCTIONvia settings in theREPOSITORY(see REPOSITORY) paragraph. You may accomplish the same thing by specifying the-fintrinsicsswitch

User-written functions (see Subprogram Types) never require theFUNCTIONkeyword when they are executed, because each user-written function a program uses must be included in that program’sREPOSITORYparagraph, which therefore makes theFUNCTIONkeyword optional.

The following intrinsic functions, known to other "dialects" of COBOL, are defined to GnuCOBOL as reserved words but are not otherwise implemented currently. Any attempts to use these functions will result in a compile-time error message.

BOOLEAN-OF-INTEGER
FORMATTED-CURRENT-DATE
INTEGER-OF-FORMATTED-DATE
CHAR-NATIONAL
FORMATTED-DATE
NATIONAL-OF
DISPLAY-OF
FORMATTED-DATETIME
STANDARD-COMPARE
EXCEPTION-FILE-N
FORMATTED-TIME
TEST-FORMATTED-DATETIME
EXCEPTION-LOCATION-N
INTEGER-OF-BOOLEAN

The supported intrinsic functions are listed in the following sections, along with their syntax and usage notes.

6.16.1. ABS

ABS Function Syntax

 ABS(number)
 ~~~

6.16.2. ACOS

ACOS Function Syntax

 ACOS(cosine)
 ~~~~

The result will be an angle, expressed in radians. You may convert this to an angle measured in degrees, as follows:

COMPUTE <degrees> = ( <radians> * 180 ) / FUNCTION PI

6.16.3. ANNUITY

ANNUITY Function Syntax

 ANNUITY(interest-rate, number-of-periods)
 ~~~~~~~

The <interest-rate> is the rate of interest paid at each payment. If you only have an annual interest rate and you wish to compute monthly annuity payments, divide the annual interest rate by 12 and use that value for <interest-rate> on this function.

Multiply the result of this function times the desired principal amount to determine the amount of each period’s payment.

A note for the financially challenged: an annuity is basically a reverse loan; an accountant would take the result of this function multiplied by -1 times the principal amount to compute a loan payment you are making.

6.16.4. ASIN

ASIN Function Syntax

 ASIN(sine)
 ~~~~

The result will be an angle, expressed in radians. You may convert this to an angle measured in degrees, as follows:

COMPUTE <degrees> = ( <radians> * 180 ) / FUNCTION PI

6.16.5. ATAN

ATAN Function Syntax

 ATAN(tangent)
 ~~~~

The result will be an angle, expressed in radians. You may convert this to an angle measured in degrees, as follows:

COMPUTE <degrees> = ( <radians> * 180 ) / FUNCTION PI

6.16.6. BYTE-LENGTH

BYTE-LENGTH Function Syntax

 BYTE-LENGTH(string)
 ~~~~~~~~~~~

For example, if <string> is encoded using a double-byte character set such as UNICODE (where each character is represented by 16 bits of storage, not the 8-bits inherent to character sets like ASCII or EBCDIC), then calling this function with a <string> argument whosePICTURE(see PICTURE) isX(4)would return a value of 8 rather than the value 4.

Contrast this with theLENGTH(see LENGTH) function.

6.16.7. CHAR

CHAR Function Syntax

 CHAR(integer)
 ~~~~

For example, if the program is using the (default) ASCII character set, CHAR(34) returns the 34th character in the ASCII character set — an exclamation-point ("!"). If you are using this function to convert a numeric value to its corresponding ASCII character, you must use an argument value one greater than the numeric value.

If an argument whose value is less than 1 or greater than 256 is specified, the character in the program collating sequence corresponding to a value of all zero bits is returned.

The following code is an alternative approach when you just wish to convert a number to its ASCII equivalent:

01  Char-Value.
    05 Numeric-Value        USAGE BINARY-CHAR.
…
    MOVE numeric-character-value TO Numeric-Value

TheChar-Valueitem now has the corresponding ASCII character value.

6.16.8. COMBINED-DATETIME

COMBINED-DATETIME Function Syntax

 COMBINED-DATETIME(days, seconds)
 ~~~~~~~~~~~~~~~~~

If a <days> value less than 1 or greater than 3067671 is specified, or if a <seconds> value less than 1 or greater than 86400 is specified, a value of 0 is returned and a runtime error will result.

6.16.9. CONCATENATE

CONCATENATE Function Syntax

 CONCATENATE(string-1 [, string-2 ]...)
 ~~~~~~~~~~~

If a numeric literal orPIC 9identifier is specified as an argument, decimal points, if any, will be removed and negative signs inPIC S9fields or numeric literals will be inserted as defined by theSIGN IS(see SIGN IS) clause (or absence thereof) of the field. Numeric literals are processed as ifSIGN IS TRAILING SEPARATEwere in effect.

6.16.10. COS

COS Function Syntax

 COS(angle)
 ~~~

The <angle> is assumed to be a value expressed in radians. If you need to determine the cosine of an angle measured in degrees, you first need to convert that angle to radians as follows:

COMPUTE <radians> = ( <degrees> * FUNCTION PI) / 180

6.16.11. CURRENCY-SYMBOL

CURRENCY-SYMBOL Function Syntax

 CURRENCY-SYMBOL
 ~~~~~~~~~~~~~~~

Changing the currency symbol via theSPECIAL-NAMES(see SPECIAL-NAMES) paragraph’sCURRENCY SYMBOLsetting will not affect the value returned by this function.

6.16.12. CURRENT-DATE

CURRENT-DATE Function Syntax

 CURRENT-DATE
 ~~~~~~~~~~~~
01  CURRENT-DATE-AND-TIME.
    05 CDT-Year                PIC 9(4).
    05 CDT-Month               PIC 9(2). *> 01-12
    05 CDT-Day                 PIC 9(2). *> 01-31
    05 CDT-Hour                PIC 9(2). *> 00-23
    05 CDT-Minutes             PIC 9(2). *> 00-59
    05 CDT-Seconds             PIC 9(2). *> 00-59
    05 CDT-Hundredths-Of-Secs  PIC 9(2). *> 00-99
    05 CDT-GMT-Diff-Hours      PIC S9(2)
                               SIGN LEADING SEPARATE.
    05 CDT-GMT-Diff-Minutes    PIC 9(2). *> 00 or 30

Since this function has no arguments, no parenthesis should be specified.

6.16.13. DATE-OF-INTEGER

DATE-OF-INTEGER Function Syntax

 DATE-OF-INTEGER(integer)
 ~~~~~~~~~~~~~~~

A value less than 1 or greater than 3067671 (9999/12/31) will return a result of 0.

6.16.14. DATE-TO-YYYYMMDD

DATE-TO-YYYYMMDD Function Syntax

 DATE-TO-YYYYMMDD(yymmdd [, yy-cutoff ])
 ~~~~~~~~~~~~~~~~

The optional <yy-cutoff> (a numeric integer data item or literal) argument is the year cutoff used to delineate centuries; if the year component of the date meets or exceeds this cutoff value, the result will be 19yymmdd; if the year component of the date is less than the cutoff value, the result will be 20yymmdd. The default cutoff value if no second argument is given will be 50.

6.16.15. DAY-OF-INTEGER

DAY-OF-INTEGER Function Syntax

 DAY-OF-INTEGER(integer)
 ~~~~~~~~~~~~~~

A value less than 1 or greater than 3067671 (9999/12/31) will return a result of 0.

6.16.16. DAY-TO-YYYYDDD

DAY-TO-YYYYDDD Function Syntax

 DAY-TO-YYYYDDD(yyddd [, yy-cutoff])
 ~~~~~~~~~~~~~~

The optional <yy-cutoff> argument (a numeric integer data item or literal) is the year cutoff used to delineate centuries; if the year component of the date meets or exceeds this cutoff value, the result will be 19yyddd; if the year component of the date is less than the cutoff, the result will be 20yyddd. The default cutoff value if no second argument is given will be 50.

6.16.17. E

E Function Syntax

 E
 ~

Since this function has no arguments, no parenthesis should be specified.

6.16.18. EXCEPTION-FILE

EXCEPTION-FILE Function Syntax

 EXCEPTION-FILE
 ~~~~~~~~~~~~~~

The name returned after the file status information will be returned only if the returned file status value is not 00.

Since this function has no arguments, no parenthesis should be specified.

The documentation of theCBL_ERROR_PROCbuilt-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.

6.16.19. EXCEPTION-LOCATION

EXCEPTION-LOCATION Function Syntax

 EXCEPTION-LOCATION
 ~~~~~~~~~~~~~~~~~~
  • primary-entry-point-name; paragraph OF section; statement-number
  • primary-entry-point-name; section; statement-number
  • primary-entry-point-name; paragraph; statement-number
  • primary-entry-point-name; statement-number

Since this function has no arguments, no parenthesis should be specified.

The program must be compiled with the-debugswitch

The documentation of theCBL_ERROR_PROCbuilt-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.

6.16.20. EXCEPTION-STATEMENT

EXCEPTION-STATEMENT Function Syntax

 EXCEPTION-STATEMENT
 ~~~~~~~~~~~~~~~~~~~

Since this function has no arguments, no parenthesis should be specified.

The program must be compiled with the-debugswitch

The documentation of theCBL_ERROR_PROCbuilt-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.

6.16.21. EXCEPTION-STATUS

EXCEPTION-STATUS Function Syntax

 EXCEPTION-STATUS
 ~~~~~~~~~~~~~~~~

Since this function has no arguments, no parenthesis should be specified.

The documentation of theCBL_ERROR_PROCbuilt-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.

The following are the error type strings, and their corresponding exception codes and descriptions.

Code Error Type Description
0101 EC-ARGUMENT-FUNCTION Function argument error
0202 EC-BOUND-ODO OCCURS … DEPENDING ON data item out of bounds
0204 EC-BOUND-PTR Data-pointer contains an address that is out of bounds
0205 EC-BOUND-REF-MOD Reference modifier out of bounds
0207 EC-BOUND-SUBSCRIPT Subscript out of bounds
0303 EC-DATA-INCOMPATIBLE Incompatible data exception
0500 EC-I-O input-output exception
0501 EC-I-O-AT-END I-O status "1x"
0502 EC-I-O-EOP An end of page condition occurred
0504 EC-I-O-FILE-SHARING I-O status "6x"
0505 EC-I-O-IMP I-O status "9x"
0506 EC-I-O-INVALID-KEY I-O status "2x"
0508 EC-I-O-LOGIC-ERROR I-O status "4x"
0509 EC-I-O-PERMANENT-ERROR I-O status "3x"
050A EC-I-O-RECORD-OPERATION I-O status "5x"
0601 EC-IMP-ACCEPT Implementation-defined accept condition
0602 EC-IMP-DISPLAY Implementation-defined display condition
0A00 EC-OVERFLOW Overflow condition
0A02 EC-OVERFLOW-STRING STRING overflow condition
0A03 EC-OVERFLOW-UNSTRING UNSTRING overflow condition
0B05 EC-PROGRAM-NOT-FOUND Called program not found
0D03 EC-RANGE-INSPECT-SIZE Size of replace item in inspect differs
1000 EC-SIZE Size error exception
1004 EC-SIZE-OVERFLOW Arithmetic overflow in calculation
1005 EC-SIZE-TRUNCATION Significant digits truncated in store
1007 EC-SIZE-ZERO-DIVIDE Division by zero
1202 EC-STORAGE-NOT-ALLOC The data-pointer specified in a FREE statement does not identify currently allocated storage
1203 EC-STORAGE-NOT-AVAIL The amount of storage requested by an ALLOCATE statement is not available

6.16.22. EXP

EXP Function Syntax

 EXP(number)
 ~~~

6.16.23. EXP10

EXP10 Function Syntax

 EXP10(number)
 ~~~~~

6.16.24. FACTORIAL

FACTORIAL Function Syntax

 FACTORIAL(number)
 ~~~~~~~~~

6.16.25. FRACTION-PART

FRACTION-PART Function Syntax

 FRACTION-PART(number)
 ~~~~~~~~~~~~~
<number> -- FUNCTION INTEGER-PART(<number>)

6.16.26. HIGHEST-ALGEBRAIC

HIGHEST-ALGEBRAIC Function Syntax

 HIGHEST-ALGEBRAIC(numeric-identifier)
 ~~~~~~~~~~~~~~~~~

6.16.27. INTEGER

INTEGER Function Syntax

 INTEGER(number)
 ~~~~~~~

6.16.28. INTEGER-OF-DATE

INTEGER-OF-DATE Function Syntax

 INTEGER-OF-DATE(date)
 ~~~~~~~~~~~~~~~

Once in that form, mathematical operations may be performed against the internal date before it is transformed back into a date using theDATE-OF-INTEGER(see DATE-OF-INTEGER) orDAY-OF-INTEGER(see DAY-OF-INTEGER) function.

6.16.29. INTEGER-OF-DAY

INTEGER-OF-DAY Function Syntax

 INTEGER-OF-DAY(date)
 ~~~~~~~~~~~~~~

Once in that form, mathematical operations may be performed against the internal date before it is transformed back into a date using theDATE-OF-INTEGER(see DATE-OF-INTEGER) orDAY-OF-INTEGER(see DAY-OF-INTEGER) function.

6.16.30. INTEGER-PART

INTEGER-PART Function Syntax

 INTEGER-PART(number)
 ~~~~~~~~~~~~

6.16.31. LENGTH

LENGTH Function Syntax

 LENGTH(string)
 ~~~~~~

The value returned by this function is not the number of bytes of storage occupied by string, but rather the number of actual characters making up the string. For example, if <string> is encoded using a double-byte character set such as UNICODE (where each character is represented by 16 bits of storage, not the 8-bits inherent to character sets like ASCII or EBCDIC), then calling this function with a <string> argument whosePICTURE is X(4)would return a value of 4 rather than the value 8 (the actual number of bytes of storage occupied by that item).

Contrast this function with theBYTE-LENGTH(see BYTE-LENGTH) andLENGTH-AN(see LENGTH-AN) functions.

6.16.32. LENGTH-AN

LENGTH-AN Function Syntax

 LENGTH-AN(string)
 ~~~~~~~~~

This intrinsic function is identical to theBYTE-LENGTH(see BYTE-LENGTH) function.

Note that the value returned by this function is not the number of characters making up the <string>, but rather the number of actual bytes of storage required to store <string>. For example, if <string> is encoded using a double-byte character set such as UNICODE (where each character is represented by 16 bits of storage, not the 8-bits inherent to character sets like ASCII or EBCDIC), then calling this function with a <string> argument whosePICTURE is X(4)would return a value of 8 rather than the value 4.

Contrast this with theLENGTH(see LENGTH) function.

6.16.33. LOCALE-COMPARE

LOCALE-COMPARE Function Syntax

 LOCALE-COMPARE(argument-1, argument-2 [ , locale ])
 ~~~~~~~~~~~~~~

Either or both of the 1st two arguments may be an alphanumeric literal, a group item or an elementary item appropriate to storing alphabetic or alphanumeric data. If the lengths of the two arguments are unequal, the shorter will be assumed to be padded to the right with spaces.

The two arguments will be compared, character by character, against each other until their relationship to each other can be determined. The comparison is made according to the cultural rules in effect for the specified <locale> name or for the current locale if no <locale> argument is specified. Once that relationship is determined, a one-character alphanumeric value will be returned as follows:

  • "<" — If <argument-1> is determined to be less than <argument-2>
  • "=" — If the two arguments are equal to each other
  • ">" — If <argument-1> is determined to be greater than <argument-2>

See LOCALE Names, for a list of typically-available locale names.

6.16.34. LOCALE-DATE

LOCALE-DATE Function Syntax

 LOCALE-DATE(date [, locale ])
 ~~~~~~~~~~~

You may include an optional second argument to specify the <locale> name (group item orPIC Xidentifier) you’d like to use for date formatting. If used, this second argument must be an identifier. Locale names are specified using UNIX-standard names.

6.16.35. LOCALE-TIME

LOCALE-TIME Function Syntax

 LOCALE-TIME(time [, locale ])
 ~~~~~~~~~~~

You may include an optional <locale> name (a group item orPIC Xidentifier) you’d like to use for time formatting. If used, this second argument must be an identifier. Locale names are specified using UNIX-standard names.

6.16.36. LOCALE-TIME-FROM-SECONDS

LOCALE-TIME-FROM-SECONDS Function Syntax

 LOCALE-TIME-FROM-SECONDS(seconds [, locale ])
 ~~~~~~~~~~~~~~~~~~~~~~~~

You may include an optional <locale> name (a group item orPIC Xidentifier) you’d like to use for time formatting. If used, this second argument must be an identifier. Locale names are specified using UNIX-standard names.

See LOCALE Names, for a list of typically-available locale names.

6.16.37. LOG

LOG Function Syntax

 LOG(number)
 ~~~

6.16.38. LOG10

LOG10 Function Syntax

 LOG10(number)
 ~~~~~

6.16.39. LOWER-CASE

LOWER-CASE Function Syntax

 LOWER-CASE(string)
 ~~~~~~~~~~

What constitutes a "letter" (or upper/lower case too, for that manner) may be influenced through the use of aCHARACTER CLASSIFICATION(see OBJECT-COMPUTER).

6.16.40. LOWEST-ALGEBRAIC

LOWEST-ALGEBRAIC Function Syntax

 LOWEST-ALGEBRAIC(numeric-identifier)
 ~~~~~~~~~~~~~~~~

6.16.41. MAX

MAX Function Syntax

 MAX(number-1 [, number-2 ]...)
 ~~~

6.16.42. MEAN

MEAN Function Syntax

 MEAN(number-1 [, number-2 ]...)
 ~~~~

6.16.43. MEDIAN

MEDIAN Function Syntax

 MEDIAN(number-1 [, number-2 ]...)
 ~~~~~~

6.16.44. MIDRANGE

MIDRANGE Function Syntax

 MIDRANGE(number-1 [, number-2 ]...)
 ~~~~~~~~

6.16.45. MIN

MIN Function Syntax

 MIN(number-1 [, number-2 ]...)
 ~~~

6.16.46. MOD

MOD Function Syntax

 MOD(value, modulus)
 ~~~

6.16.47. MODULE-CALLER-ID

MODULE-CALLER-ID Function Syntax

 MODULE-CALLER-ID
 ~~~~~~~~~~~~~~~~

The discussion of theMODULE-TIME(see MODULE-TIME) function includes a sample program that uses this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.48. MODULE-DATE

MODULE-DATE Function Syntax

 MODULE-DATE
 ~~~~~~~~~~~

The discussion of theMODULE-TIME(see MODULE-TIME) function includes a sample program that uses this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.49. MODULE-FORMATTED-DATE

MODULE-FORMATTED-DATE Function Syntax

 MODULE-FORMATTED-DATE
 ~~~~~~~~~~~~~~~~~~~~~

The discussion of theMODULE-TIME(see MODULE-TIME) function includes a sample program that uses this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.50. MODULE-ID

MODULE-ID Function Syntax

 MODULE-ID
 ~~~~~~~~~

The discussion of theMODULE-TIME(see MODULE-TIME) function includes a sample program that uses this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.55. MODULE-PATH

MODULE-PATH Function Syntax

 MODULE-PATH
 ~~~~~~~~~~~

The discussion of theMODULE-TIME(see MODULE-TIME) function includes a sample program that uses this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.52. MODULE-SOURCE

MODULE-SOURCE Function Syntax

 MODULE-SOURCE
 ~~~~~~~~~~~~~

The discussion of theMODULE-TIME(see MODULE-TIME) function includes a sample program that uses this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.53. MODULE-TIME

MODULE-TIME Function Syntax

 MODULE-TIME
 ~~~~~~~~~~~

Since this function has no arguments, no parenthesis should be specified.

The following sample program uses all the MODULE- Functions:

IDENTIFICATION DIVISION.
PROGRAM-ID. DEMOMODULE.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
    FUNCTION ALL INTRINSIC.
PROCEDURE DIVISION.
000-Main.
    DISPLAY "MODULE-CALLER-ID      = [" MODULE-CALLER-ID "]"
    DISPLAY "MODULE-DATE           = [" MODULE-DATE "]"
    DISPLAY "MODULE-FORMATTED-DATE = [" MODULE-FORMATTED-DATE "]"
    DISPLAY "MODULE-ID             = [" MODULE-ID "]"
    DISPLAY "MODULE-PATH           = [" MODULE-PATH "]"
    DISPLAY "MODULE-SOURCE         = [" MODULE-SOURCE "]"
    DISPLAY "MODULE-TIME           = [" MODULE-TIME "]"
    STOP RUN
    .

The program produces this output when executed:

MODULE-CALLER-ID      = []
MODULE-DATE           = [20120614]
MODULE-FORMATTED-DATE = [Jun 14 2012 15:07:45]
MODULE-ID             = [DEMOMODULE]
MODULE-PATH           = [E:\Programs\Demos\DEMOMODULE.exe]
MODULE-SOURCE         = [DEMOMODULE.cbl]
MODULE-TIME           = [150745]

6.16.54. MONETARY-DECIMAL-POINT

MONETARY-DECIMAL-POINT Function Syntax

 MONETARY-DECIMAL-POINT
 ~~~~~~~~~~~~~~~~~~~~~~

On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the

Using theDECIMAL-POINT IS COMMA(see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.55. MONETARY-THOUSANDS-SEPARATOR

MONETARY-THOUSANDS-SEPARATOR Function Syntax

 MONETARY-THOUSANDS-SEPARATOR
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the

Using theDECIMAL-POINT IS COMMA(see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.56. NUMERIC-DECIMAL-POINT

NUMERIC-DECIMAL-POINT Function Syntax

 NUMERIC-DECIMAL-POINT
 ~~~~~~~~~~~~~~~~~~~~~

On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the

Using theDECIMAL-POINT IS COMMA(see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.57. NUMERIC-THOUSANDS-SEPARATOR

NUMERIC-THOUSANDS-SEPARATOR Function Syntax

 NUMERIC-THOUSANDS-SEPARATOR
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~

On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the

Using theDECIMAL-POINT IS COMMA(see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.

Since this function has no arguments, no parenthesis should be specified.

6.16.58. NUMVAL

NUMVAL Function Syntax

 NUMVAL(string)
 ~~~~~~

The <string> must have any of the following formats, where ’#’ represents a sequence of one or more decimal digits:

# -# +# #- #+ #CR #DB #CR
#.# -#.# +#.# #.#- #.#+ #.#CR #.#DB

There must be at least one digit character in the string.

Leading and/or trailing spaces are allowed, as are spaces before and/or after the sign, CR and DB characters.

6.16.59. NUMVAL-C

NUMVAL-C Function Syntax

 NUMVAL-C(string[,symbol])
 ~~~~~~~~

The optional <symbol> character represents the currency symbol (a single-character group item,USAGE DISPLAYelementary item or alphanumeric literal) that may be used as the currency character in <string>. If no <symbol> is specified, the value that would be returned by theCURRENCY-SYMBOLintrinsic function (see CURRENCY-SYMBOL) will be used.

<string> may have any of the following formats, where ’#’ represents a sequence of one or more decimal digits and ’$’ represents the <symbol> character:

# -# +# #- #+ #CR #DB #CR
#.# -#.# +#.# #.#- #.#+ #.#CR #.#DB
$# -$# +$# $#- $#+ $#CR $#DB $#CR
$#.# -$#.# +$#.# $#.#- $#.#+ $#.#CR $#.#DB

There must be at least one digit character in the string.

Leading and/or trailing spaces are allowed, as are spaces before and/or after the currency symbol, sign, CR and DB characters.

6.16.60. NUMVAL-F

NUMVAL-F Function Syntax

 NUMVAL-F(char)
 ~~~~~~~~
# -# +# #E# -#E# +#E#
#E+# -#E+# +#E+# #E-# -#E-# +#E-#
#.# -#.# +#.# #.#E# -#.#E# +#.#E#
#.#E+# -#.#E+# +#.#E+# #.#E-# -#.#E-# +#.#E-#

There must be at least one digit character both before and after theEin the string.

Leading and/or trailing spaces are allowed, as are spaces before and/or after any sign characters.

6.16.61. ORD

ORD Function Syntax

 ORD(char)
 ~~~

For example, assuming the program is using the standard ASCII collating sequence,ORD('!')returns 34 because "!" is the 34th ASCII character. If you are using this function to convert an ASCII character to its numeric value, you must subtract one from the result.

The following code is an alternative approach when you just wish to convert an ASCII character to its numeric equivalent:

01  Char-Value.
    05 Numeric-Value        USAGE BINARY-CHAR.
…
    MOVE "character" TO Char-Value

Numeric-Valuenow has the numeric value ofcharacter

6.16.62. ORD-MAX

ORD-MAX Function Syntax

 ORD-MAX(char-1 [, char-2 ]...)
 ~~~~~~~

For example, assuming the program is using the standard ASCII collating sequence,ORD-MAX('Z', 'z', '!')returns 2 because the 2nd character in the argument list (the ASCII character ’z’) occurs after ’Z’ and ’!’ in the program collating sequence. Each <char-n> argument may be a group item,USAGE DISPLAYelementary item or alphanumeric literal.

6.16.63. ORD-MIN

ORD-MIN Function Syntax

 ORD-MIN(char-1 [, char-2 ]...)
 ~~~~~~~

For example, assuming the program is using the standard ASCII collating sequence,ORD-MIN('Z', 'z', '!')returns 3 because the 3rd character in the argument list (the ASCII character ’!’) occurs before ’Z’ and ’z’ in the program collating sequence. Each <char-n> argument may be a group item,USAGE DISPLAYelementary item or alphanumeric literal.

6.16.64. PI

PI Function Syntax

 PI
 ~~

Since this function has no arguments, no parenthesis should be specified.

6.16.65. PRESENT-VALUE

PRESENT-VALUE Function Syntax

 PRESENT-VALUE(rate, value-1 [, value-2 ])
 ~~~~~~~~~~~~~

All arguments are numeric data items and/or numeric literals.

6.16.66. RANDOM

RANDOM Function Syntax

 RANDOM[(seed)]
 ~~~~~~

The purpose of the optional <seed> argument, is to initialize the chain of pseudo-random numbers that will be returned by the function. Not only will calls to this function using the same <seed> value return the same pseudo-random number, but so will all subsequent executions of the function without a <seed>. This is actually a good thing when you are testing your program because you can rely on always receiving the same sequence of "random" numbers if you always start using the same <seed>.

The <seed> may be any form of literal or data item. If <seed> is numeric, its numeric value will serve as the seed value. If <seed> is alphanumeric, a value for it will be determined as if it were used as an argument toNUMVAL(see NUMVAL).

Take, for example, the following sample program:

    IDENTIFICATION DIVISION.
    PROGRAM-ID. DEMORANDOM.
    DATA DIVISION.
    WORKING-STORAGE SECTION.
    01  Pseudo-Random-Number        USAGE COMP-1.
    PROCEDURE DIVISION.
    000-Main.
        MOVE FUNCTION RANDOM(1) TO Pseudo-Random-Number
        DISPLAY Pseudo-Random-Number
        PERFORM 4 TIMES
            MOVE FUNCTION RANDOM    TO Pseudo-Random-Number
            DISPLAY Pseudo-Random-Number
        END-PERFORM
        STOP RUN
        .

Every time this program is executed, it will produce the same output, because the same sequence of pseudo-random numbers will be generated:

    0.41
    0.18467
    0.63340002
    0.26499999
    0.19169

It is worth mentioning that if the first execution ofRANDOMin your program lacks a <seed> argument, the result will be exactly as if that execution were coded with a <seed> argument value of 1.

Once your program has been thoroughly tested, you’ll want different sequences to be generated each time the program runs. One possible way to accomplish this is to use a <seed> that is likely to be different every time the program is executed, as is likely to be the case if the firstMOVEstatement in the previous example were replaced by this:

    MOVE RANDOM(FUNCTION CURRENT-DATE(1:16))
      TO Pseudo-Random-Number

The first 16 characters returned by theCURRENT-DATE(see CURRENT-DATE) function will be a number in the format "YYYYMMDDhhmmssnn", where "YYYYMMDD" is the current calendar date and "hhmmssnn" is the current time of day to the one one-hundredth of a second. Since two different executions of the program will never get identicalCURRENT-DATEvalues (unless they are executed in extremely close time frames to one another), using those first sixteen characters as theRANDOMseed will guarantee that receiving a duplicate sequence of pseudo-random numbers in two different executions of the program will be HIGHLY unlikely.

6.16.67. RANGE

RANGE Function Syntax

 RANGE(number-1 [, number-2 ]...)
 ~~~~~

All <number-n> arguments are numeric data items and/or numeric literals.

6.16.68. REM

REM Function Syntax

 REM(number,divisor)
 ~~~

6.16.69. REVERSE

REVERSE Function Syntax

 REVERSE(string)
 ~~~~~~~

6.16.70. SECONDS-FROM-FORMATTED-TIME

SECONDS-FROM-FORMATTED-TIME Function Syntax

 SECONDS-FROM-FORMATTED-TIME(format,time)
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~

The <time> string must contain hours, minutes and seconds. The time argument may be specified as a group item,USAGE DISPLAYelementary item or an alphanumeric literal.

The <format> argument is a string (a group item,USAGE DISPLAYelementary item or an alphanumeric literal) documenting the format of <time> using "hh", "mm" and "ss" to denote where the respective time information can be found. Any other characters found in <format> represent character positions that will be ignored. For example, a format ofhhmmssindicates that <time> will be treated as a six-digit string value where the first two characters are the number of hours, the next two represent minutes and the last two represent seconds. A <format> ofhh:mm:ss however, describes <time> as an eight-character string where characters 3 and 6 will be ignored.

6.16.71. SECONDS-PAST-MIDNIGHT

SECONDS-PAST-MIDNIGHT Function Syntax

 SECONDS-PAST-MIDNIGHT
 ~~~~~~~~~~~~~~~~~~~~~

Since this function has no arguments, no parenthesis should be specified.

6.16.72. SIGN

SIGN Function Syntax

 SIGN(number)
 ~~~~

6.16.73. SIN

SIN Function Syntax

 SIN(angle)
 ~~~

The <angle> is assumed to be a value expressed in radians. If you need to determine the sine of an angle measured in degrees, you first need to convert that angle to radians as follows:

COMPUTE <radians> = ( <degrees> * FUNCTION PI) / 180

6.16.74. SQRT

SQRT Function Syntax

 SQRT(number)
 ~~~~

The following two statements produce identical results:

01  Result           PIC 9(4).9(10).
…
    MOVE FUNCTION SQRT(15) TO Result
    COMPUTE Result = 15 ^ 0.5

6.16.75. STANDARD-DEVIATION

STANDARD-DEVIATION Function Syntax

 STANDARD-DEVIATION(number-1 [, number-2 ]...)
 ~~~~~~~~~~~~~~~~~~

6.16.76. STORED-CHAR-LENGTH

STORED-CHAR-LENGTH Function Syntax

 STORED-CHAR-LENGTH(string)
 ~~~~~~~~~~~~~~~~~~

6.16.77. SUBSTITUTE

SUBSTITUTE Function Syntax

 SUBSTITUTE(string, from-1, to-1 [, from-n, to-n ]...)
 ~~~~~~~~~~

The <from-n> strings must match sequences in <string> exactly with regard to value and case.

A <from-n> string does not have to be the same length as its corresponding <to-n> string.

All arguments are group items, <USAGE DISPLAY> elementary items or alphanumeric literals.

A null <to-n> string will be treated as a single space.

6.16.78. SUBSTITUTE-CASE

SUBSTITUTE-CASE Function Syntax

 SUBSTITUTE-CASE(string, from-1, to-1 [, from-n, to-n ]...)
 ~~~~~~~~~~~~~~~

All arguments are group items,USAGE DISPLAYelementary items or alphanumeric literals.

6.16.79. SUM

SUM Function Syntax

 SUM(number-1 [, number-2 ]...)
 ~~~

6.16.80. TAN

TAN Function Syntax

 TAN(angle)
 ~~~

The <angle> is assumed to be a value expressed in radians. If you need to determine the tangent of an angle measured in degrees, you first need to convert that angle to radians as follows:

COMPUTE <radians> = ( <degrees> * FUNCTION PI) / 180

6.16.81. TEST-DATE-YYYYMMDD

TEST-DATE-YYYYMMDD Function Syntax

 TEST-DATE-YYYYMMDD(date)
 ~~~~~~~~~~~~~~~~~~

A valid date is one of the form yyyymmdd in the range 1601/01/01 to 9999/12/31, with no more than the expected maximum number of days in the month, accounting for leap year.

If the <date> is valid, a 0 value is returned. If it isn’t, a value of 1, 2 or 3 is returned signalling the problem lies with the year, month or day, respectively.

6.16.82. TEST-DAY-YYYYDDD

TEST-DAY-YYYYDDD Function Syntax

 TEST-DATE-YYYYDDD(date)
 ~~~~~~~~~~~~~~~~~

A valid date is one of the form yyyyddd in the range 1601001 to 9999365. Leap year is accounted for in determining the maximum number of days in a year.

If the date is valid, a 0 value is returned. If it isn’t, a value of 1 or 2 is returned signalling the problem lies with the year or day, respectively.

6.16.83. TEST-NUMVAL

TEST-NUMVAL Function Syntax

 TEST-NUMVAL(string)
 ~~~~~~~~~~~

Note that these errors include but are not limited to: argument (string) is zero length, contains only spaces or contains valid characters but is incomplete, such as the string "+.".

6.16.84. TEST-NUMVAL-C

TEST-NUMVAL-C Function Syntax

 TEST-NUMVAL-C(string[,symbol])
 ~~~~~~~~~~~~~

Note that these errors include but are not limited to: argument (string) is zero length, contains only spaces or contains valid characters but is incomplete, such as the string "+.".

The optional <symbol> argument serves the same function — and has the same default and possible values — as the corresponding argument of theNUMVAL-Cfunction.

6.16.85. TEST-NUMVAL-F

TEST-NUMVAL-F Function Syntax

 TEST-NUMVAL-F(string)
 ~~~~~~~~~~~~~

Note that these errors include but are not limited to: argument (string) is zero length, contains only spaces or contains valid characters but is incomplete, such as the string "+.".

6.16.86. TRIM

TRIM Function Syntax

 TRIM(string [, LEADING|TRAILING ])
 ~~~~           ~~~~~~~ ~~~~~~~~

The second argument is specified as a keyword, not a quoted string or identifier. If no second argument is specified, both leading and trailing spaces will be removed. The case (upper, lower or mixed) of this argument is irrelevant.

6.16.87. UPPER-CASE

UPPER-CASE Function Syntax

 UPPER-CASE(string)
 ~~~~~~~~~~

What constitutes a "letter" (or upper/lower case too, for that manner) may be influenced through the use of aCHARACTER CLASSIFICATION(see OBJECT-COMPUTER).

6.16.88. VARIANCE

VARIANCE Function Syntax

 VARIANCE(number-1 [, number-2 ]...)
 ~~~~~~~~

6.16.89. WHEN-COMPILED

WHEN-COMPILED Function Syntax

 WHEN-COMPILED
 ~~~~~~~~~~~~~

Since this function has no arguments, no parenthesis should be specified.

Unlike theWHEN-COMPILEDspecial register, which has an ASCII value of the compilation date/time in the format "mm/dd/yyhh.mm.ss", theWHEN-COMPILEDintrinsic function returns the compilation date/time as an ASCII string in the format "yyyymmddhhmmssnnooooo", where "yyyymmdd" is the date, "hhmmss" is the time, "nn" is the hundredths of a second component of the compilation time, if available (or "00" if it isn’t) and "ooooo" is the time zone offset from GMT.

If the-fintrinsics=WHEN-COMPILEDswitch or-fintrinsics=ALLswitch is specified to the compiler or theREPOSITORY(see REPOSITORY) paragraph specifies eitherFUNCTION WHEN-COMPILED INTRINSICorFUNCTION ALL INTRINSIC then references toWHEN-COMPILED(without a leadingFUNCTIONkeyword will always reference this intrinsic function and there will be no way to access theWHEN-COMPILEDspecial register.

6.16.90. YEAR-TO-YYYY

YEAR-TO-YYYY Function Syntax

 YEAR-TO-YYYY(yy [, yy-cutoff ])
 ~~~~~~~~~~~~

The optional <yy-cutoff> argument is the year cutoff used to delineate centuries; if <yy> meets or exceeds this cutoff value, the result will be 19yy; if <yy> is less than the cutoff, the result will be 20yy. The default cutoff value if no second argument is given will be 50.

Both arguments must be numeric data items or numeric literals.

6.17. GnuCOBOL Statements

6.17.1. ACCEPT

6.17.1.1. ACCEPT FROM CONSOLE

ACCEPT FROM CONSOLE Syntax

   ACCEPT { identifier-1 }   [ FROM mnemonic-name-1 ]
   ~~~~~~                      ~~~~
          { OMITTED      }
            ~~~~~~~

 [ END-ACCEPT ]
   ~~~~~~~~~~
  1. If noFROMclause is specified,FROM CONSOLEis assumed.
  2. The specified <mnemonic-name-1> must either be one of the built-in device namesCONSOLESTDINSYSINorSYSIPT or a user-defined (see SPECIAL-NAMES) mnemonic name attached to one of those four device names.
  3. Input will be read either from the console window CONSOLE or from the system-standard input (pipe 0 =STDINSYSINorSYSIPT and will be saved in <identifier-1>.
  4. If <identifier-1> is a numeric data item, the character value read from the console or standard-input device will be parsed according to the rules for input to theNUMVALintrinsic function (see NUMVAL), except that none of the trailing sign formats are honoured.

6.17.1.2. ACCEPT FROM COMMAND-LINE

ACCEPT FROM COMMAND-LINE Syntax

   ACCEPT identifier-1
   ~~~~~~
          FROM { COMMAND-LINE                                }
          ~~~~ { ~~~~~~~~~~~~                                }
               { ARGUMENT-NUMBER                             }
               { ~~~~~~~~~~~~~~~                             }
               { ARGUMENT-VALUE                              }
               { ~~~~~~~~~~~~~~                              }
               { [ ON EXCEPTION imperative-statement-1 ]     }
               {      ~~~~~~~~~                              }
               { [ NOT ON EXCEPTION imperative-statement-2 ] }
 [ END-ACCEPT ]    ~~~    ~~~~~~~~~
   ~~~~~~~~~~
  1. The reserved wordONis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. When you accept from theCOMMAND-LINE
  3. By accepting fromARGUMENT-NUMBER
    1. Arguments will be separated by treating spaces and/or tab characters as the delimiters between arguments. The number of such delimiters separating two non-blank argument values is irrelevant.
    2. Strings enclosed in double-quote characters (") will be treated as a single argument, regardless of how many spaces or tab characters (if any) might be embedded within those quotation characters.
    3. On Windows systems, single-quote, or apostrophe characters (’) will be treated just like any other data character and will NOT delineate argument strings.
  4. By accepting fromARGUMENT-VALUE
  5. The optionalON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of an attempt to retrieve anARGUMENT-VALUE See ON EXCEPTION + NOT ON EXCEPTION, for additional information.

6.17.1.3. ACCEPT FROM ENVIRONMENT

ACCEPT FROM ENVIRONMENT Syntax

   ACCEPT identifier-1
   ~~~~~~
          FROM { ENVIRONMENT-VALUE            }
          ~~~~ { ~~~~~~~~~~~~~~~~~            }
               { ENVIRONMENT { literal-1    } }
               { ~~~~~~~~~~~ { identifier-1 } }
        [ ON EXCEPTION imperative-statement-1 ]
             ~~~~~~~~~
        [ NOT ON EXCEPTION imperative-statement-2 ]
          ~~~    ~~~~~~~~~
 [ END-ACCEPT ]
   ~~~~~~~~~~
  1. The reserved wordONis optional and may be included, or not, at the discretion of the programmer. The presence or absence of this word has no effect upon the program.
  2. By accepting fromENVIRONMENT-VALUE
  3. A simpler approach to retrieving an environment variables value is to use theENVIRONMENT
  4. The optionalON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to an attempt to retrieve the value of a non-existent environment variable or the successful retrieval of an environment variable’s value, respectively. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.

6.17.1.4. ACCEPT screen-data-item

ACCEPT screen-data-item Syntax

   ACCEPT { identifier-1 }
   ~~~~~~
          { OMITTED      }
            ~~~~~~~
                           [{ FROM EXCEPTION-STATUS }]
                              ~~~~ ~~~~~~~~~~~~~~~~
                           [{ FROM CRT ] [ MODE IS BLOCK ]}
                              ~~~~ ~~~     ~~~~    ~~~~~

          [ AT { | LINE NUMBER { integer-1    }            | } ]
            ~~ { | ~~~~        { identifier-2 }            | }
               { | COLUMN|COL|POSITION NUMBER { integer-2    } | }
               { | ~~~~~~ ~~~ ~~~~~~~~        { identifier-3 } | }
               {                                             }
               { { integer-3    }                            }
               { { identifier-4 }                            }

          [ WITH [ Attribute-Specification ]...
            ~~~~
                 [ LOWER|UPPER ]
                   ~~~~~ ~~~~~
                 [ SCROLL { UP   } [ { integer-4    } LINE|LINES ] ]
                   ~~~~~~ { ~~   }   { identifier-5 }
                          { DOWN }
                            ~~~~
                 [ TIMEOUT|TIME-OUT AFTER { integer-5    } ]
                   ~~~~~~~ ~~~~~~~~       { identifier-6 }
                 [ CONVERSION ]
                   ~~~~~~~~~~
                 [ UPDATE ] ]
                   ~~~~~~
          [ ON EXCEPTION imperative-statement-1 ]
               ~~~~~~~~~
          [ NOT ON EXCEPTION imperative-statement-2 ]
            ~~~    ~~~~~~~~~
 [ END-ACCEPT ]
   ~~~~~~~~~~

TheFROM CRT

  1. The reserved wordsAFTERISNUMBERandONare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. The reserved wordsCOLUMNCOLandPOSITIONare interchangeable.
  3. The reserved wordsTIMEOUTandTIME-OUTare interchangeable.
  4. If <identifier-1> is defined in theSCREEN SECTION(see SCREEN SECTION), anyAT <Attribute-Specification>,LOWERUPPERorSCROLLclauses will be ignored. In these cases, an impliedDISPLAY(see DISPLAY screen-data-item) of <identifier-1> will occur before input is accepted. Coding an explicitDISPLAY identifier-1before anACCEPT identifier-1is redundant and will incur the performance penalty of painting the screen contents twice.
  5. The variousATclauses provide a means of positioning the cursor to a specific spot on the screen before the screen is read. One or the other (but not both) may be used, as follows:
    1. TheLINEandCOLUMNclauses provide one mechanism for specifying the line and column position to which the cursor will be positioned before allowing the user to enter data. In the absence of one or the other, a value of 1 will be assumed for the one that is missing. The author’s personal preference, however, is to explicitly code both.
    2. The <literal-3> or <identifier-4> value, if specified, must be a four- or six-digit value with the 1st half of the number indicating the line where the cursor should be positioned and the second half indicating the column. You may code only one of each clause on anyACCEPT
  6. WITHoptions (including the various individual <Attribute-Specifications>) should be coded only once.
  7. The following <Attribute-Specification> clauses are allowed on theACCEPTstatement — these are the same as those allowed forSCREEN SECTIONdata items. A particular <Attribute-Specification> may be used only once in anyACCEPT
  8. TheSCROLL
  9. TheTIMEOUT
  10. This format of theACCEPTstatement will be terminated by any of the following events:
    1. When the ’Enter’ key is pressed.
    2. Expiration of theTIMEOUTtimer — this will be treated as if the Enter key had been pressed with no data being entered.
    3. When a function key (Fn) is pressed.
    4. The pressing of the PgUp or PgDn keys, if the
    5. The pressing of the Esc key if both the
    6. The pressing of the Up-arrow, Down-Arrow or PrtSc (Print Screen) keys. These keys are not detectable on Windows systems, however.
  11. The following apply when <identifier-1> is defined in theSCREEN SECTION
    1. Alphanumeric data entered into <identifier-1> or any screen data item subordinate to it must be consistent with thePICTURE(see PICTURE) clause of that item. This will be enforced at runtime by theACCEPTstatement.
    2. If <identifier-1> or any screen data item subordinate to it are defined as numeric, entered data must be acceptable asNUMVALintrinsic function (see NUMVAL) input (no decimal points are allowed, however). The value stored into the screen data item will be as if the input were passed to that function.
    3. If <identifier-1> or any screen data item subordinate to it are defined as numeric edited, entered data must be acceptable asNUMVAL-Cintrinsic function (see NUMVAL-C) input (again, no decimal points are allowed). The value stored into the screen data item will be as if the input were passed to that function.
  12. The following apply when <identifier-1> is not defined in theSCREEN SECTION
    1. Alphanumeric data entered into <identifier-1> should be consistent with thePICTURE(see PICTURE) clause of that item, although that will not be enforced by theACCEPTstatement. You may useClass Conditions(see Class Conditions) after the data is accepted to enforce the data type.
    2. If <identifier-1> is defined as numeric, entered data must be acceptable asNUMVALintrinsic function (see NUMVAL) input (no decimal points are allowed, however). The value stored into <identifier-1> will be as if the input were passed to that function.
    3. If <identifier-1> is defined as numeric edited, entered data must be acceptable asNUMVAL-Cintrinsic function (see NUMVAL-C) input (again, no decimal points are allowed). The value stored into <identifier-1> will be as if the input were passed to that function.
  13. The optionalON EXCEPTIONandNOT ON EXCEPTIONclauses may be used to detect and react to the failure or success, respectively, of the screen I/O attempt. See ON EXCEPTION + NOT ON EXCEPTION, for additional information.

    After this format of theACCEPTstatement is executed, the program’sCRT STATUS(see SPECIAL-NAMES) identifier will be populated with one of the following:

    Code Meaning
    0000 ENTER key pressed
    1001–1064 F1–F64, respectively, were pressed
    2001 PgUp was pressed
    2002 PgDn,was pressed
    2003 Up Arrow was pressed
    2004 Down-Arrow was pressed
    2006 PrtSc (Print Screen) was pressed
    2005 Esc was pressed
    8000 No data is available on screen ACCEPT
    9000 Fatal screen I/O error
  14. The actual key pressed to generate a function key (Fn) will depend on the type of terminal device you’re using (PC, Macintosh, VT100, etc.) and what type of enhanced display driver was configured with the version of GnuCOBOL you’re using. For example, on a GnuCOBOL build for a Windows PC using MinGW and PDCurses, F1-F12 are the actual F-keys on the PC keyboard, F13-F24 are entered by shifting the F-keys, F25-F36 are entered by holding Ctrl while pressing an F-key and F37-F48 are entered by holding Alt while pressing an F-key. On the other hand, a GnuCOBOL implementation built for Windows using Cygwin and NCurses treats the PCs F1-F12 keys as the actual F1-F12, while shifted F-keys will enter F11-F20. With Cygwin/NCurses, Ctrl- and Alt-modified F-keys aren’t recognized. Neither are Shift-F11 or Shift-F12.
  15. Numeric keypad keys are not recognizable on Windows MinGW/PDCurses builds of GnuCOBOL, regardless of the number lock settings. Windows Cygwin/NCurses builds recognize numeric keypad inputs properly. Although not tested during the preparation of this documentation, I would expect native Windows builds using PDCurses to behave as MinGW builds do and native Unix builds using NCurses to behave as do Cygwin builds.
  16. The optionalEXCEPTION-STATUSclause may be used to detect exceptions from a prior arthmetic verb such as COMPUTE to recover any errors produced. These are recovered using the functionEXCEPTION-STATUS

6.17.1.5. ACCEPT FROM DATE/TIME

ACCEPT FROM DATE/TIME Syntax

   ACCEPT identifier-1 FROM { DATE [ YYYYMMDD ] }
   ~~~~~~              ~~~~ { ~~~~   ~~~~~~~~   }
                            { DAY [ YYYYDDD ]   }
                            { ~~~   ~~~~~~~     }
                            { DAY-OF-WEEK       }
                            { ~~~~~~~~~~~       }
 [ END-ACCEPT ]             { TIME              }
   ~~~~~~~~~~
  1. The data retrieved from the system and the format in which it is structured will vary, as follows:
    Syntax Data Retrieved Format
    DATE Current date in Gregorian form yymmdd
    DATE YYYYMMDD Current date in Gregorian form yyyymmdd
    DAY Current date in Julian form yyddd
    DAY YYYYDDD Current date in Julian form yyyyddd
    TIME Time, including hundredths of a second (nn) hhmmssnn

6.17.1.6. ACCEPT FROM Screen-Info

ACCEPT FROM Screen-Info Syntax

   ACCEPT identifier-1
   ~~~~~~
          FROM { LINES|LINE-NUMBER }
          ~~~~ { ~~~~~ ~~~~~~~~~~~ }
               { COLS|COLUMNS      }
               { ~~~~ ~~~~~~~      }
               { ESCAPE KEY        }
                 ~~~~~~ ~~~
 [ END-ACCEPT ]
   ~~~~~~~~~~
  1. The reserved wordsLINESandLINE-NUMBERare interchangeable.
  2. The reserved wordsCOLSandCOLUMNSare interchangeable.
  3. The following points pertain to the use of theLINES
    1. TheLINES
    2. When the console is running in a windowed environment, this will be the sizing of the window in which the program is executing, in terms of horizontal COLUMNS or vertical LINES character counts — not pixels.
    3. When the system is not running a windowing environment, the physical console screen attributes will be returned.
    4. Values of 0 will be returned if GnuCOBOL was not generated to include screen I/O.
    5. See the documentation on theCBL_GET_SCR_SIZEbuilt-in system subroutine (see CBL_GET_SCR_SIZE) for another way to retrieve this information.
  4. TheESCAPE KEY

6.17.1.7. ACCEPT FROM Runtime-Info

ACCEPT FROM Runtime-Info Syntax

   ACCEPT identifier-1
   ~~~~~~
          FROM { EXCEPTION STATUS }
          ~~~~ { ~~~~~~~~~ ~~~~~~ }
               { USER NAME        }
                 ~~~~ ~~~~
 [ END-ACCEPT ]
   ~~~~~~~~~~
  1. The following points pertain to the use of theEXCEPTION STATUS
    1. <identifier-1> must be defined as aPIC X(4)item.
    2. See Error Exception Codes, for a complete list of the exception codes and their meanings.
    3. An alternative to the use ofACCEPT FROM Runtime-Infois to use theEXCEPTION-STATUSintrinsic function (see EXCEPTION-STATUS).
  2. The following points pertain to the use of theUSER NAME
    1. The returned result is the userid that was used to login to the system with, and not any actual first and/or last name of the user in question (unless, of course, that is the information used as a logon id).
    2. <identifier-1> should be defined large enough to receive the longest user-name on the system.
    3. If insufficient space is allocated, the returned value will be truncated.
    4. If excess space is allocated, the returned value will be padded with spaces (to the right).

6.17.1.8. ACCEPT OMITTED

ACCEPT OMITTED Syntax

   ACCEPT OMITTED
   ~~~~~~

   1.  For console : See 6.17.1.1 (ACCEPT FROM CONSOLE Syntax)

   2.  For Screen  : See 6.17.1.4 (ACCEPT screen-data-item Syntax)

 [ END-ACCEPT ]
   ~~~~~~~~~~
  1. The following are examples of keycodes that can be used:
    COB-SCR-INSERT
    COB-SCR-DELETE
    COB-SCR-BACKSPACE
    COB-SCR-KEY-HOME
    COB-SCR-KEY-END
    
  2. You can used extended attributes, useful for setting timeouts or positioning.

6.17.1.9. ACCEPT FROM EXCEPTION-STATUS

ACCEPT FROM EXCEPTION-STATUS Syntax

   ACCEPT exception-status-pic-9-4   FROM EXCEPTION-STATUS
   ~~~~~~                            ~~~~ ~~~~~~~~~~~~~~~~

 [ END-ACCEPT ]
   ~~~~~~~~~~
  1. The following is an example of usage:
     In WS:
     01  exception-status  pic 9(4).
    ..
     In PD:
    
     ACCEPT unexpected-rounding  FROM EXCEPTION-STATUS
     IF unexpected-rounding NOT EQUAL "0000" THEN
        DISPLAY "Unexpected rounding. Code " unexpected-rounding
                 UPON SYSERR
     END-IF
    

6.17.2. ADD

6.17.2.1. ADD TO

ADD TO Syntax

   ADD { literal-1    }...
   ~~~ { identifier-1 }

       TO { identifier-2
       ~~
          [ ROUNDED [ MODE IS { AWAY-FROM-ZERO         } ] ] }...
            ~~~~~~~   ~~~~    { ~~~~~~~~~~~~~~         }
                              { NEAREST-AWAY-FROM-ZERO }
                              { ~~~~~~~~~~~~~~~~~~~~~~ }
                              { NEAREST-EVEN           }
                              { ~~~~~~~~~~~~           }
                              { NEAREST-TOWARD-ZERO    }
                              { ~~~~~~~~~~~~~~~~~~~    }
                              { PROHIBITED             }
                              { ~~~~~~~~~~             }
                              { TOWARD-GREATER         }
                              { ~~~~~~~~~~~~~~         }
                              { TOWARD-LESSER          }
                              { ~~~~~~~~~~~~~          }
                              { TRUNCATION             }
                                ~~~~~~~~~~
     [ ON SIZE ERROR imperative-statement-1 ]
          ~~~~ ~~~~~
     [ NOT ON SIZE ERROR imperative-statement-2 ]
       ~~~    ~~~~ ~~~~~
 [ END-ADD ]
   ~~~~~~~
  1. The reserved wordsISandONare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. Both <identifier-1> and <identifier-2> must be numeric unedited data items while <literal-1> must be a numeric literal.
  3. An <identifier-1> data item may also be coded as an <identifier-2> — note, however, that the value of such a data item will therefore be included twice in the result.
  4. The contents of each <identifier-1> will remain unchanged by this statement.
  5. The optionalROUNDED(see ROUNDED) clause available to each <identifier-2> will control how non-integer results will be saved.
  6. The optionalON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-2> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.

6.17.2.2. ADD GIVING

ADD GIVING Syntax

   ADD { literal-1    }...
   ~~~ { identifier-1 }

     [ TO identifier-2 ]
       ~~
       GIVING { identifier-3
       ~~~~~~
         [ ROUNDED [ MODE IS { AWAY-FROM-ZERO         } ] ] }...
           ~~~~~~~   ~~~~    { ~~~~~~~~~~~~~~         }
                             { NEAREST-AWAY-FROM-ZERO }
                             { ~~~~~~~~~~~~~~~~~~~~~~ }
                             { NEAREST-EVEN           }
                             { ~~~~~~~~~~~~           }
                             { NEAREST-TOWARD-ZERO    }
                             { ~~~~~~~~~~~~~~~~~~~    }
                             { PROHIBITED             }
                             { ~~~~~~~~~~             }
                             { TOWARD-GREATER         }
                             { ~~~~~~~~~~~~~~         }
                             { TOWARD-LESSER          }
                             { ~~~~~~~~~~~~~          }
                             { TRUNCATION             }
                               ~~~~~~~~~~
     [ ON SIZE ERROR imperative-statement-1 ]
          ~~~~ ~~~~~
     [ NOT ON SIZE ERROR imperative-statement-2 ]
       ~~~    ~~~~ ~~~~~
 [ END-ADD ]
   ~~~~~~~
  1. The reserved wordsISandONare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. Both <identifier-1> and <identifier-2> must be numeric unedited data items while <literal-1> must be a numeric literal; <identifier-3> may be either a numeric or numeric edited data item.
  3. An <identifier-1> or <identifier-2> data item may be used as an <identifier-3>, if desired.
  4. The contents of each <identifier-1> and <identifier-2> will remain unchanged by this statement, unless they happen to also be specified as an <identifier-3>.
  5. The current value in each <identifier-3> at the start of the statement’s execution is irrelevant, since the contents of each <identifier-3> will simply be replaced with the computed sum.
  6. The optionalROUNDED(see ROUNDED) clause available to each <identifier-3> will control how non-integer results will be saved.
  7. The optionalON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-3> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.

6.17.2.3. ADD CORRESPONDING

ADD CORRESPONDING Syntax

   ADD CORRESPONDING identifier-1
   ~~~
       TO identifier-2
       ~~
     [ ROUNDED [ MODE IS { AWAY-FROM-ZERO         } ] ]
       ~~~~~~~   ~~~~    { ~~~~~~~~~~~~~~         }
                         { NEAREST-AWAY-FROM-ZERO }
                         { ~~~~~~~~~~~~~~~~~~~~~~ }
                         { NEAREST-EVEN           }
                         { ~~~~~~~~~~~~           }
                         { NEAREST-TOWARD-ZERO    }
                         { ~~~~~~~~~~~~~~~~~~~    }
                         { PROHIBITED             }
                         { ~~~~~~~~~~             }
                         { TOWARD-GREATER         }
                         { ~~~~~~~~~~~~~~         }
                         { TOWARD-LESSER          }
                         { ~~~~~~~~~~~~~          }
                         { TRUNCATION             }
                           ~~~~~~~~~~
     [ ON SIZE ERROR imperative-statement-1 ]
          ~~~~ ~~~~~
     [ NOT ON SIZE ERROR imperative-statement-2 ]
       ~~~    ~~~~ ~~~~~
 [ END-ADD ]
   ~~~~~~~
  1. The reserved wordsISandONare optional and may be included, or not, at the discretion of the programmer. The presence or absence of these words has no effect upon the program.
  2. Both <identifier-1> and <identifier-2> must be group items.
  3. See CORRESPONDING, for information on how corresponding matches will be found between <identifier-1> and <identifier-2>.
  4. The optionalROUNDED(see ROUNDED) clause available to each <identifier-3> will control how non-integer results will be saved.
  5. The optionalON SIZE ERRORandNOT ON SIZE ERRORclauses may be used to detect and react to the failure or success, respectively, of an attempt to perform a calculation. In this case, failure is defined as being an <identifier-3> with an insufficient number of digit positions available to the left of any implied decimal point. See ON SIZE ERROR + NOT ON SIZE ERROR, for additional information.

6.17.3. ALLOCATE

ALLOCATE Syntax

 ALLOCATE { expression-1 CHARACTERS } [ { INITIALIZED } ]
 ~~~~~~~~ { identifier-1 ~~~~~~~~~~ }   { ~~~~~~~~~~~ }
                                        { INITIALISED }
     [ RETURNING identifier-2 ]           ~~~~~~~~~~~
       ~~~~~~~~~
  1. The reserved wordsINITIALIZEDandINITIALISEDare interchangeable.
  2. Both <identifier-1> andRETURNING <identifier-2>may not be specified in the same statement.
  3. If used, <expres