MODULE 7: COBOL Control statements
GO TO statement
- GO TO is used to unconditionally and permanently transfer control to another paragraph of program
- Basic syntax:-
GO TO paragraph-name
- The above statement will permanently transfer control to the very first statement of the paragraph
- When we use PERFORM, specified paragraph executes and control is transferred back to the next statement following PERFORM. But when we use GO TO, specified paragraph will be executed but control will NOT be returned back
In PROCEDURE DIVISION,PARA-0. DISPLAY ‘IN PARA-0’ GO TO PARA-1 DISPLAY ‘RETURNED FROM PARA-1’ STOP RUN. PARA-1. DISPLAY ‘IN PARA-1’.SYSOUT display (output):-IN PARA-0 IN PARA-1If you see output, ‘RETURNED FROM PARA-1’ is not displayed i.e. because control is NOT transferred back when PARA-1 is called using GO TO.Please refer SIMPLE PERFORM topic here to understand difference between PERFORM and GO TO.
GO TO with DEPENDING phrase
- This is also called as Conditional GO TO.
- Basic syntax:-
GO TO paragraph-1 [paragraph-2]… DEPENDING ON identifier
- identifier must be numeric data item
- Above statement will transfer control to one of the paragraph depending on value of identifier. If identifier holds ‘1’, control will be transferred to paragraph-1. If identifier holds ‘2’, control will be transferred to paragraph-2 and so on. If identifier holds some invalid value, then GO TO will not call any paragraph and next statement following GO TO will be executed.
In PROCEDURE DIVISION,PARA-0. DISPLAY ‘IN PARA-0’ MOVE 2 TO WS-X GO TO PARA-1 PARA-2 DEPENDING ON WS-X DISPLAY ‘IN PARA-0 AGAIN’ STOP RUN. PARA-1. DISPLAY ‘IN PARA-1’. PARA-2. DISPLAY ‘IN PARA-2’.SYSOUT display (output):-IN PARA-0 IN PARA-2
How to use GO TO in structured programming?
- Usage of GO TO is not encouraged in structured programming
- Since GO TO permanently transfer control to another part of program, there are high chances of logical errors. It is suggested to use PERFORM instead
- However, there is no risk if the GO TO is used to transfer control to the part of program which is within the scope of paragraphs being performed
In PROCEDURE DIVISION,PARA-0. DISPLAY ‘IN PARA-0’ MOVE 5 TO WS-X PERFORM PARA-1 THRU PARA-1-EXIT. DISPLAY ‘IN PARA-0 AGAIN’ STOP RUN. PARA-1. DISPLAY ‘IN PARA-1’. IF WS-X > 3 GO TO PARA-1-EXIT ELSE ADD 10 TO WS-X END-IF. DISPLAY ‘WS-X: ’ WS-X. PARA-1-EXIT. EXIT.SYSOUT display (output):-IN PARA-0 IN PARA-1 IN PARA-0 AGAIN
- In above example, GO TO is used within scope of paragraphs being performed. This kind of controlled GO TO is acceptable in structured programming