CANCEL Statement


  • CANCEL statement is used to release the resources associated with a previously called subprogram.
  • When a subprogram is called, a set resources are allocated for its execution. If the subprogram is no longer needed, a CANCEL statement is used to free up those resources.
  • CANCEL statement is crucial in environments with limited resources like memory. It becomes useful when a main program calls numerous subprograms during its execution, as it efficiently frees up these resources.
  • Nowadays, mainframe environments are fully equipped with resources, so we can't see the CANCEL statement in recent code changes introduced.

Syntax -

CANCEL "subprogram-name"

or

CANCEL ws-variable

Example - Let us assume SUBPROG is the subprogram name and WS-SUBPROG is working-storage variable that holds the subprogram name.

CANCEL "SUBPROG"

or

CANCEL WS-SUBPROG

Points to Note -

  • Effect on Subprogram - Depending on the implementation, the CANCEL statement may reset the subprogram to its initial state.
  • Error Handling - It's crucial to note that not all COBOL implementations support the CANCEL statement or may restrict its use.
  • When to Use - It's not always necessary to use the CANCEL statement to manage resources. Modern systems often have sufficient resources; the OS or COBOL runtime environment manages resources effectively.

Practical Example -


Scenario - CANCEL statement usage in main program.

MAINPROG -

----+----1----+----2----+----3----+----4----+----5----+
       ...
       DATA DIVISION.  
       WORKING-STORAGE SECTION. 
       01 WS-VAR.  
          05 WS-INP1          PIC 9(02) VALUE 47. 
          05 WS-INP2          PIC 9(02) VALUE 25.  
          05 WS-RESULT        PIC 9(04).
       01 WS-CALLING-PROG     PIC X(08) VALUE "SUBPROG".
       ...
	   PROCEDURE DIVISION. 
	  * Calling subprogram with two inputs and receiving the result 
           CALL WS-CALLING-PROG USING WS-INP1, WS-INP2, WS-RESULT. 

           DISPLAY "INPUTS:  " WS-INP1 ", " WS-INP2.
           DISPLAY "RESULTS: " WS-RESULT.

		   CANCEL WS-CALLING-PROG.
		   ...

Explaining Example -

MAINPROG is the main program and SUBPROG is the subprogram. "CANCEL WS-CALLING-PROG" releases all the resources used by SUBPROG.