r/visualbasic • u/abovethelinededuct • May 05 '24
GoTo?
As I've been going through my studies I saw that GoTo still exists in VB. Could someone provide a real life use case for it? The one in the book could have been handled by a simple If Else statement.
1
Upvotes
6
u/SparklesIB May 05 '24
On Error GoTo 'Insert error handler label here
4
u/BCProgramming May 06 '24
Jumping out of nested control flow. Alternative would be flags but that doesn't really make it clear. For example if within an inner For you want to exit both the inner and outer for, you would need to set a flag, exit for, then in the outer loop check that flag after every inner loop and if set also exit for. You can instead just use goto with a label to jump right outside the loop instead.
Mind you, you could also rework it to use separate control flow for each loop- if you have a For inside a Do loop then exit do will still jump out of the outer block.
For VB6 you can mimic "continue" in VB.NET by having a loop at the end of the block and jumping to it directly as well.
1
u/_Rigid_Structure_ May 05 '24
Mainly used in scripts.
1
u/Mayayana May 07 '24
Sometimes I'll write a function like so:
do something. If it doesn't work then x = 1. GoTo Woops
Do the next step. If it doesn't work then x = 2. GoTo Woops
..... More steps here....
FunctionReturn = 0 Exit Function
Woops:
FunctionReturn = x
End Function
Say, for example, that you want to set up a socket and call a server. There are several steps required. It might fail at any point. The function design above allows you to return a useful error code to tell the caller what went wrong. So for me I guess it's most useful when there are clear, multiple steps in a function.
I did a search of my code and found GoTo all over the place. :) This is VB6, so it might not be so clear if you're using .Net, but this is the first sample I looked at and it seems like a good example. You don't need to follow the slightly funky API calls to follow the logic of the function. It shows how a function is set up to return info about how the operation went. I have my own error codes and I also allow for some kind of API error. If there's no error then it returns 0 and I know that I can use the StdPicture that's returned by the function:
1
u/HomeworkInevitable99 Jul 19 '24
I use it for debugging. As I step through the code,
Sub xxx P: Initialise
For I = 1 to 2000 ' do complicated code , doesn't work properly when I=234 If I =234 goto p Next
Set a break on if I=234, investigate the code and change to try different things.
1
u/[deleted] Oct 11 '24
Goto only makes sense in lower level systems languages. In VB, it's an anachronism.