Search code examples
cobolgnucobolcobol85

Call function in COBOL more than once


I have my main calling two functions. The second function called (Decrypt) calls the first function (Encrypt) inside of it. So here Encrypt is being called twice. Once in the main, and then once inside of Decrypt.

The issue is that it refuses to work this way. Once Encrypt gets used in the main, I can't use Encrypt again anywhere~ in the program. Its like the variables are still in use and I can't pass it new ones.

For example, if I remove Encrypt from the main function and ONLY call Decrypt - it works fine. I can't figure out why.

IDENTIFICATION DIVISION.
PROGRAM-ID. CAESER-1-CIPHER.
DATA DIVISION.
PROCEDURE DIVISION
CALL 'ENCRYPT' USING BY CONTENT INPUTE CIPHERE.
CALL 'DECRYPT' USING BY CONTENT INPUTD CIPHERD.
STOP RUN.

IDENTIFICATION DIVISION.
PROGRAM-ID. ENCRYPT.
DATA DIVISION.
PROCEDURE DIVISION BLAH BLAH
BLAH BLAH COMPUTE
END PROGRAM ENCRYPT.

IDENTIFICATION DIVISION.
PROGRAM-ID. DECRYPT.
DATA DIVISION.
PROCEDURE DIVISION BLAH BLAH
CALL 'ENCRYPT' USING BY CONTENT BLAH BLAH
EXIT PROGRAM.
END PROGRAM DECRYPT.

Solution

  • I'm not sure I follow your question completely, I would have expeced more problems with DECRYPT. This is why...

    Program SER-1-CIPHER contains two nested programs: ENCRYPT and DECRYPT. Until you declare ENCRYPT and DECRYPT as COMMON programs they cannot "see" each other because only programs at higher levels of nesting (eg. SER-1-CIPHER) can "see" programs that are nested within them. This is explained in the Open Cobol Programmers Guide on nested programs.

    Try declaring nested programs as:

     PROGRAM-ID. ENCRYPT IS COMMON.
     PROGRAM-ID. DECRYPT IS COMMON.
    

    This way program DECRYPT will be able to CALL ENCRYPT.

    Next, I would encourage you to use GOBACK in place of STOP RUN and EXIT PROGRAM when returning control to the operating system or calling programs. The OpenCobol Programmers Guide also makes this recommendation.

    Finally, each subprogram should contain as its last statement a GOBACK. I am not sure what the behaviour of ENCRYPT is without having an explicit return statement of some kind. Your actual program may have this, but the code example in your question doesn't.

    Open Cobol does not seem to have any restrictions on having recursion among nested programs, but some versions of COBOL do not allow this (eg. IBM Enterprise COBOL).