In visual basic, the GoTo statement is useful to transfer the program control to the specified labeled statement. It is useful to get out of the loop or exit from deeply nested loops based on our requirements.
In visual basic, the defined labeled statement must always exist in the scope of GoTo
statement, and we can also define the multiple GoTo
statements in our application to transfer the program control to the specified labeled statement.
For example, we can use GoTo
statement in Select statement to transfer control from one Select-Case label to another or the default label based on our requirements.
Following is the syntax of defining the GoTo
statement in a visual basic programming language.
If you observe the above syntax, we defined a GoTo statement using GoTo
keyword and labeled_statement. Here, the labeled_statement transfers the program control to the specified labeled_statement position.
Now, we will see how to use GoTo
statement in visual basic for loop to get out of the loop at the particular condition with examples
Following is the example of using GoTo
statement in for loop to move the program control to the specified label statement based on our requirements.
If you observe above example, we used GoTo
statement in for loop with labeled statement “endloop” to exit for loop and transfer the program execution to the defined label statement whenever the variable (i) value equals 5.
We will get the following result when we execute the above visual basic program.
If you observe the above result, whenever the variable (i) value equals 5, the GoTo statement transfers the program control from for loop to the specified label statement (endloop) position.
In visual basic, we can use the GoTo statement to exit from the defined loops or transfer the control to the specific Select-Case label or the default label in the Select statement based on our requirements.
Now, we will see how to use GoTo
statement in the Select-Case statement with an example. Following is the example of using GoTo
with Select-Case statement to transfer the control from one Select-Case label to another based on our requirements.
If you observe the above example, we used GoTo
statement in multiple Select cases and trying to transfer the program control from case 2 / case 3 to case 1.
When we execute the above visual basic program, we will get the following result below.
This is how we can use GoTo
statement with Select-Case statements to transfer the program control from one case to another in visual basic programming language based on our requirements.
It’s better to avoid using GoTo
statement in our visual basic applications because it will make the program logic more complex, and it’s difficult to understand the process flow of program execution.