ElseIf vs Else If

China☆狼群 提交于 2019-12-02 07:49:25

问题


For years now I've been using Else If to code in VBScript...

If a = b Then
    ...
Else If a = c Then
    ...
End If

Which seems to work as required. I've also seen many sites on the web that use Else If, excepting MSDN that uses ElseIf.

Is there a difference between ElseIf versus Else If?

Snippet

Here's one I coded earlier that's working just fine through Classic ASP:

If IsDate(wD) Then
    wS = wD
Else If wD&"" <> FormatDisplayDate(wS) Then
    wS = WeekStart(Date())
    wD = FormatDisplayDate(wS)
End If

Here's a snippet from an older piece of code, written by someone else...

if opip = "IP" then
    opip = "In Patient"
Else If opip = "OP" then
    opip = "Out Patient"
End If

None of these are run through a compiler, however, it's all interpreted.

Ignore that junk - I messed up a search and replace in the IDE.


回答1:


That example code doesn't compile and produces the compilation error

Microsoft VBScript compilation error: Expected 'End'

as I'd expect (as @ekkehard-horner point's out in the comments).

I've never known ElseIf to work any other way then detailed in MSDN. The only thing I can think of is you are writing it as a nested If statement.

If a = b Then
    ...
Else If a = c Then
    ...
End If
End If

which looks really ugly but is the same as writing

If a = b Then
    ...
Else
    If a = c Then
        ...
    End If
End If

Problem with this approach is you end up with an un-handled condition on the nested If statement. What happens if a = d for example?

You would need to make sure your nested If caught the extra condition which isn't needed with an ElseIf statement.

If a = b Then
    ...
Else
    If a = c Then
        ...
    Else
        ...
    End If
End If

ElseIf approach would be;

If a = b Then
    ...
ElseIf a = c Then
    ...
Else
    ...
End If

Interesting musing by @eric-lippert (one of the programmers behind the VBScript compiler) in the sea of comments...well worth a read. I certainly learned something.




回答2:


Else If puts a nested If inside the Else branch of the first If statement whereas ElseIf is part of the initial If statement.

Basically it's two 2-way conditionals (one nested in the other)

If condition Then
  ...
Else
  If condition Then
    ...
  Else
    ...
  End If
End If

vs one n-way conditional

If condition Then
  ...
ElseIf condition Then
  ...
Else
  ...
End If

And, as @Ekkehard.Horner pointed out, the former should raise an error without a closing nested End If.



来源:https://stackoverflow.com/questions/38439170/elseif-vs-else-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!