Chapter 5: Branching using GOTO/GOSUB
|
5.1 |
Introduction
It's possible that you will never need to use GOTO or GOSUBs once you become familiar with the BASIC language. You can read the next Chapter to see why. It's considered "bad programming style" to use GOTOs, but in BASIC, it's as common as using arrays. Especially GOSUB, this is used quite often within loops. Anyway, if you can avoid branching using GOTO or GOSUB, then do it, but if not, don't worry, it might even be better (for optimization purposes). |
5.2 |
When to use GOTOs?
Most newbies to BASIC programming will use GOTO quite often to break out of a loop or something similar. In almost all cases, this can be avoided.
DO
I = I + 1
IF I = 50 THEN GOTO OUT
LOOP
OUT:
PRINT "I'm OUT!" In other cases that I've witnessed, GOSUB should have been used.
|
5.3 |
When to use GOSUB?
Here's an example where the programmer should have used GOSUB instead of GOTO:
DO
I = I + 1
IF (I MOD 2) = 0 THEN GOTO EvenNumbers
ReturnHere:
LOOP UNTIL I = 100
END
EvenNumbers:
PRINT I
GOTO ReturnHere This is how it would look using GOSUB:
DO
I = I + 1
IF (I MOD 2) = 0 THEN GOSUB EvenNumbers
LOOP UNTIL I = 100
END
EvenNumbers:
PRINT I
RETURN The RETURN statement is used in conjunction with GOSUB. You can think of GOSUB as a bookmark and GOTO statement all in one, and RETURN as a return to that bookmark. You'll see in the next chapter that GOSUB is very similar to creating a SUB or FUNCTION.
|
|
|