Share via


Small Basic: How to Remove Goto Statements

If your program has a lot of Goto statements, that can be called a spaghetti program.  Structured program doesn't use Goto.  So, how can you remove Goto from your program?


Endless Loop

If you use Goto for endless loop.  You can use While statement for the loop.

Before

start:
DoSomething()
Goto start

After

While "True"
  DoSomething()
EndWhile

Notice that indent in loop make your program more readable.  You can easily indent your program with "Format Program" command in the popup menu when you push mouse right button. 

Conditional Jump

If you'd like to change the direction from jump by the value of the variable, If-Then-ElseIf statements may be useful for that case.

Before

If case =  "a" Then
  Goto a
EndIf
If case =  "b" Then
  Goto b
EndIf
Goto end
a:
DoForA()
Goto end
b:
DoForB()
end:

After

If case =  "a" Then
  DoForA()
ElseIf case =  "b" Then
  DoForB()
EndIf

More Complicated Case

Actually there are many more complex flows in programs.  So, sometime Goto seems to be easer than structured statements such as For, While, If-Then-Else.  But many case if you use a flag (or some flags), you can remove Goto from your program.

Before

loop:
Search()
If eof Or  found Then
  Goto break
EndIf
Goto loop
break:

After

continue  = "True"
While continue
  Search()
  If eof Or  found Then
    continue = "False"
  EndIf
EndWhile

Variables eof, found, continue are flags which contains "True" or "False".


See Also

Other Languages