GO TO Statement
GO TO statement is used to transfer control to another part of the program, allowing the program to "jump" to a different paragraph or section.
Points to Note -
- It is a PROCEDURE DIVISION statement and should be coded in Area-B.
- If It is not the last in the sequence of statements, the statements after GO TO won't execute.
Different ways of using GO TO statement are -
- Unconditional
- Conditional
Unconditional GO TO -
Unconditional GO TO transfers the control unconditionally to another part of the program. It transfers control to the first statement in the paragraph or section coded with GO TO.
Syntax -
GO TO paragraph-1.
Parameters -
- paragraph-1 - Specifies a paragraph or sections where the control should transfer.
Examples -
Scenario - Passing control to a END-PARA.
PROCEDURE DIVISION.
BEGIN-PARA.
DISPLAY 'Start'.
GO TO END-PARA.
DISPLAY 'This will be skipped'.
STOP RUN.
END-PARA.
DISPLAY 'End'.
Output -
Start End
Conditional GO TO -
Conditional GO TO statement transfers control to the paragraph or section based on the DEPENDING ON the value of the variable (ws-variable).
Syntax -
GO TO paragraph-1[,paragraph-2,...]
DEPENDING ON ws-variable.
Parameters -
- paragraph-1[,paragraph-2,...] - Specifies a paragraph or sections where the control should transfer.
- DEPENDING ON ws-variable - Specifies the paragraph number to where the control should transfer.
If the value is 1, the control will transferred to the first statement in paragraph-1.
If the value is 2, the control will transfer to the first statement in paragraph-2 and so on.
No control transfer occurs if the value is other than a value range of 1 through n (where n is the number of paragraphs coded in GO TO statement). Instead, control passes to the next statement in the normal sequence of execution.
Examples -
Scenario - GO TO DEPENDING ON.
PROCEDURE DIVISION.
PARA-0.
DISPLAY 'Para0'.
MOVE 3 TO WS-P
GO TO PARA-1 PARA-2 DEPENDING ON WS-P.
DISPLAY 'This will be skipped'.
STOP RUN.
PARA-1.
DISPLAY 'Para1'.
PARA-2.
DISPLAY 'Para2'.
PARA-3.
DISPLAY 'Para3'.
Output -
Para0 Para3
GO TO with IF Statement -
GO TO statement not advised to use individually. But, it is advised to use with conditional statements like IF and EVALUATE.
Examples -
Scenario - GO TO with IF.
PROCEDURE DIVISION.
PARA0.
DISPLAY 'Para0'.
MOVE 3 TO WS-P
PERFORM PARA1
THRU PARA1-EXIT.
DISPLAY 'Return to para0'.
STOP RUN.
PARA1.
DISPLAY 'Para1'.
IF WS-P > 1
GO TO PARA1-EXIT
ELSE
COMPUTE WS-P = WS-P + 1
END-IF.
DISPLAY 'WS-P: ' WS-P.
PARA1-EXIT.
EXIT.
Output -
Para0 Para1 Return to para0