跳入 if 块
Jumping into an if block
所以我正在维护一些遗留代码,其中在 if 块的 End If 之前有一个 GoTo 前导。我的困境是我现在需要向该块添加一个 Else 子句。如果通过 GoTo 到达 Else 而不是使 If 失败,Else 是否会正常运行?
GoTo
是完全非结构化的,无论您将其带到哪个代码块,它都会在您指定的任何地方继续执行。如果您需要根据 If
测试之后但 GoTo
之前发生的参数更改来执行 Else
条件,它将不起作用。如果您不关心 If
语句的计算方式,它 可能 有效,但这将是修复底层控制流问题的理想时机。您可以通过使用调试器单步执行以下示例代码来查看此行为:
Private Sub DontTryThisAtHome()
Dim test As Long
Dim doneThat As Boolean
If test = 0 Then
Debug.Print "If condition tested."
Spaghetti:
Debug.Print "This always executes even if test = " & test & "."
If doneThat Then GoTo Pasta
Else
Debug.Print "test > 0"
End If
test = 1
doneThat = True
Debug.Print "Pasta express..."
GoTo Spaghetti
Pasta:
End Sub
输出:
If condition tested.
This always executes even if test = 0.
Pasta express...
This always executes even if test = 1.
千万别做。
遗留代码很难理解,即使没有以前的人利用一些语言的黑暗角落。不要让下一个人的生活变得混乱。
重写有问题的代码,使其清晰明了。
所以我正在维护一些遗留代码,其中在 if 块的 End If 之前有一个 GoTo 前导。我的困境是我现在需要向该块添加一个 Else 子句。如果通过 GoTo 到达 Else 而不是使 If 失败,Else 是否会正常运行?
GoTo
是完全非结构化的,无论您将其带到哪个代码块,它都会在您指定的任何地方继续执行。如果您需要根据 If
测试之后但 GoTo
之前发生的参数更改来执行 Else
条件,它将不起作用。如果您不关心 If
语句的计算方式,它 可能 有效,但这将是修复底层控制流问题的理想时机。您可以通过使用调试器单步执行以下示例代码来查看此行为:
Private Sub DontTryThisAtHome()
Dim test As Long
Dim doneThat As Boolean
If test = 0 Then
Debug.Print "If condition tested."
Spaghetti:
Debug.Print "This always executes even if test = " & test & "."
If doneThat Then GoTo Pasta
Else
Debug.Print "test > 0"
End If
test = 1
doneThat = True
Debug.Print "Pasta express..."
GoTo Spaghetti
Pasta:
End Sub
输出:
If condition tested.
This always executes even if test = 0.
Pasta express...
This always executes even if test = 1.
千万别做。
遗留代码很难理解,即使没有以前的人利用一些语言的黑暗角落。不要让下一个人的生活变得混乱。
重写有问题的代码,使其清晰明了。