The GoTo Statement


The GoTo statement can be used to branch to statements within a Sub or Function procedure. We have all heard the lectures on the "evils" of using GoTo statements, so all that is not going to be rehashed here. In general, use of modern programming constructs such as the ones previously presented (Do/Loop, If/Then/Else, Select Case, etc.) virtually eliminate the need to use GoTos.


The rules for using GoTo are as follows:

         The destination of a GoTo statement must be a line label or line number that resides within the same Sub or Function procedure as the statement that issues the GoTo (i.e., you cannot "go to" a line in a Sub or Function other than the one you are currently in).

         The name of the line label follows the same rules as that for naming a variable.

         A line label or line number must begin in the first column of the line and must be followed by a colon(:).


Following is a version of the factorial program presented earlier that uses GoTos instead of the For/Next loop for looping:


Sub Main()


Dim lngFactorial As Long

Dim intInputNbr As Integer

Dim intLoopCtr As Integer


Console.Write("Enter a number: ")

intInputNbr = Val(Console.ReadLine())


lngFactorial = 1

intLoopCtr = 1



If intLoopCtr > intInputNbr Then GoTo 10

lngFactorial = lngFactorial * intLoopCtr

intLoopCtr = intLoopCtr + 1

GoTo Loop_Start


10: ' End of loop


Console.WriteLine("{0}! = {1}", intInputNbr, lngFactorial)



Console.WriteLine("(Press Enter to close this window.)")



End Sub


Download the project code for the example above here.


Note: Previous versions VB supported the GoSub statement, which enabled you to call upon a block of code within a Sub or Function (sort of a "sub within a sub"). The GoSub statement dates back earlier versions of BASIC such as QBasic and GW-BASIC; in these older languages, GoSub was the only way you could make your programs modular. GoSub was retained in Visual Basic 1 through 6, however, it has been removed in VB.NET.