CANCEL Statement


The CANCEL statement is used to release the resources associated with a previously called subprogram. When a subprogram is called, certain resources are allocated for its execution. If the subprogram is no longer needed, the CANCEL statement can be used to free up those resources.

The CANCEL statement specially useful in environments where memory or other resources are limited, or when main program calls many different subprograms during its execution.

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

Notes -

  • Effect on Subprogram - Depending on the implementation, the CANCEL statement may reset the subprogram to its initial state.
  • Error Handling - Not all COBOL implementations may support the CANCEL statement or may have restrictions on its use.
  • When to Use - While the CANCEL statement can be useful for managing resources, it's not always necessary. Modern systems often have sufficient resources; the OS or COBOL runtime environment manages resources effectively.

Practical Example -


Scenario - CANCEL statement usage in main program.

Main Program -

       IDENTIFICATION DIVISION.  
       PROGRAM-ID. MAINPROG. 
       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.

           STOP RUN. 

Explaining Example -

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