What are the difference between a GOTO and a GOSUB statements in BASIC programming language?
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.
BASIC
–
Kraut 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 statement 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 statement 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.
10 GOSUB 42:PRINT"X"
— a RETURN will not return to the next line after 10 but to the next statement after GOSUB. In this case the PRINT statement. Of course the next statement could be in the next line, but the answer sounds like it always continues with the next line. –
Tabanid © 2022 - 2024 — McMap. All rights reserved.