Search code examples
cobolgnucobol

Does add only work for fields in WORKING-STORAGE SECTION.?


It seems a program like this does not work.

   PROGRAM-ID. Test.
   ENVIRONMENT DIVISION.
   INPUT-OUTPUT SECTION.

   FILE-CONTROL.
       SELECT CountFile ASSIGN TO "count.dat"
           ORGANIZATION IS LINE SEQUENTIAL.

   DATA DIVISION.
   FILE SECTION.

   FD CountFile.
   01 CountDetails.
       02 FCountA          PIC 99 VALUE 0.
       02 FCountB          PIC 99 VALUE 0.

   WORKING-STORAGE SECTION.
   PROCEDURE DIVISION.

   Begin.

       OPEN OUTPUT CountFile

       ADD 1 TO  FCountA
       ADD 1 TO  FCountB

       WRITE CountDetails
       CLOSE CountFile

       STOP  RUN.

This writes 9999 to the count.dat file. ADD works for fields in the WORKING-STORAGE SECTION but not in the FILE SECTION.

Is that true ?


Solution

  • Q: Is that true?
    A: No, it isn't.

    ADD works for any numeric field, no matter where it is stored.

    Note that data in FILE SECTION is only guaranteed to be available at all after a successful OPEN (as you've mentioned GnuCOBOL: this one always provides the storage). It does not have any guaranteed value, so you likely want to INITIALIZE the data.

    Sample COBOL sample that shows both and can be adjusted and executed:

    IDENTIFICATION DIVISION.
    PROGRAM-ID. HELLO-WORLD.
    ENVIRONMENT DIVISION.
           input-output section.
           file-control.
               select test-file
               assign to 'test-file'
               organization is line sequential.
    
     data division.
     file section.
           fd test-file.
               01 num-var  pic 9 value 0.
     working-storage section.
               01 num2-var  pic 9 value 0.
    PROCEDURE DIVISION.
    ADD  1 TO num-var num2-var
    DISPLAY 'Hello, num ' num2-var ' and file ' num-var.
    INITIALIZE num-var num2-var
    ADD  1 TO num-var num2-var
    DISPLAY 'Hello, num ' num2-var ' and file ' num-var.
    ADD num2-var to num-var
    ADD num2-var to num-var
    DISPLAY 'Hello, num ' num2-var ' and file ' num-var.
    ADD num-var to num-var
    DISPLAY 'Hello, num ' num2-var ' and file ' num-var.
    STOP RUN.
    

    Beware: it is fixed-form reference-format, not necessarily portable, the missing OPEN can mean it aborts - and it isn't any reasonable good style - but demonstrate the issue.