Qbasic Tutorial for beginners and children (Under Construction)


The GOTO statement

The GOTO statement branches to a specific line number or to the first statement after a specified label. 

In  the example below the GOTO statement braches to the instruction after the "label1" label until the value of variable "x" is equal to 5. 

Code Output
  DIM x AS INTEGER
  x = 0
label1:
  x = x + 1
  PRINT x
  IF x < 5 THEN
     GOTO label1
  END IF

1

2

3

4

5

You should advoid using the GOTO statement wherever possible. Programmers who used GW-BASIC, the predecessor of qbasic, used to put a lot of GOTO statements, branching in every directions, in their programs, thus making it difficult to maintain. It was called spaghetti codes. The above program is simpler to write if you use the DO LOOP statement instead.

The same as above using the DO - LOOP
'This program displays a sentence 5 times
CLS
DIM x AS INTEGER
x = 0
DO
    PRINT x
    x = x + 1
LOOP UNTIL x = 5

 

However, in some cases, there are no alternatives. The GOTO statement is used in conjunction with the ON ERROR statement which is used to trap errors in your program.

[ Previous Index Next ]


pages viewed since January  19 2002