What are the difference between a BASIC GOTO and GOSUB statement

The other answers provided give a good explanation on how to use GOTO and GOSUB, but there is an important difference in how they are processed. When a GOTO is executed it starts at the top of the instruction set and flips through all the lines of code until it finds the line it is supposed to GOTO. Then if you use another GOTO statement to get back, it again goes to the top of the instruction set and flips through everything until it gets to the next location.

GOSUB does almost the same thing as GOTO, but it remembers where it was. When you use the RETURN statement it just jumps back without first going to the top of the instruction set and flipping through everything again, so it's much faster. If you want your code to run fast you should put your most called subroutines at the top of the stack and use GOSUB/RETURN instead of GOTO.


When you call GOTO the program will jump to the line in question and carry on executing.

If you use GOSUB, it will do the same, however at some point you can code a RETURN statement and the code will return to the line just after the GOSUB.

So GOTO is go to X while GOSUB is go to X but remember where you are now and so you can return later.


GOTO simply jumps to another line, GOSUB keeps track of where it came from (on a stack, presumably), so when the interpreter encounters a RETURN, it goes back to the last place GOSUB was called.

Tags:

Basic