It suddenly occurred to me that I have never written a tip about recursion in COBOL. You may think it sounds like a bad joke, but it is actually possible to make recursive calls in COBOL that works. You can also get into serious trouble and I will try to illustrate both in this tip.
The following program reads the PARM field in JCL and prints the contents in the parts separated
by commas. If you for instance executes the program using a
The program looks like this:
The first and most important detail is that when you want to use recursion in COBOL you need to write RECURSIVE after the program name specified in PROGRAM-ID. If RECURSIVE is not present you will receive a runtime error when the program calls itself either direct or indirectly through another program. You cannot use RECURSIVE on a nested/embedded program. Consequently recursion is only available with load modules. Second detail is that all variables in WORKING-STORAGE SECTION holds their values from call to call which is old news. If you have some variables that do NOT retain their values from call to call you need to declare a so-called LOCAL-STORAGE SECTION as in the above example.
You can study the functionality of WORKING-STORAGE versus LOCAL-STORAGE by relating the output to the program code. It is especially important to note that the variables that needs to contain the same value before and after the recursive call must be declared in LOCAL-STORAGE.
The experienced COBOL programmer will notice that I have not used my variables especially well. This is primarily because the program can be used to illustrate how bad it will execute if you try to make recursion using PERFORM instead of CALL. If you change CALL 'PARSING' USING PGMPARM to a PERFORM PGMSTART you ought to get the same functionality except that LOCAL-STORAGE and WORKING-STORAGE will work in the same way.
But, but, but after the first recursive call the program goes into a loop. The reason is that COBOL maintains only one return address for each paragraph/section. The result is that when PGMSTART terminates COBOL returns control to the statement right after PERFORM PGMSTART within paragraph PGMSTART. DISPLAY 'PARMNO=' PARMNO will reveal this for you when SYSOUT is filled with DISPLAY's. Remember to be ready to cancel the program if you want to check for yourself if this is really true.