Shortcircuiting: OrElse combined with Or

微笑、不失礼 提交于 2019-12-05 08:40:39

This is an operator precedence problem. The relevant documentation is here:
http://msdn.microsoft.com/en-us/library/fw84t893.aspx?ppud=4

The important excerpts:

  • Operators with equal precedence are evaluated left to right in the order in which they appear in the expression.

and

Inclusive disjunction (Or, OrElse)

So what we learn here is that Or and OrElse have the same precedence and that operators with the same precedence are evaluated from left to right.

Therefore, I would expect that in cases where a is true, b is not evaluated. However, c still will be. In cases where a is false, b is evaluated and regardless of the b's value the Or operator will evaluate c. So, yes, c is always evaluated.

As a practical matter, you should generally prefer OrElse in your code unless you have a good reason to use Or. Or exists now mainly for backwards compatibility.

OrElse short circuits between the left and right side parameters (only 2 parameters). So I would say that C will always be evaluated as you could treat this as (A OrElse B) Or C.

MSDN OrElse

In the case presented, c is evaluated. A small test will tell you:

Debug.WriteLine(test(1) OrElse test(2) Or test(3))

Function test(ByVal a As Integer) As Boolean

    Debug.WriteLine(a)
    Return True

End Function

The above example outputs:

1
3
True

In my personal experience VB tends to obtain the value for all of them regardless of whether they be actually evaulated or not.

This is only helpfull when order matters for items existance and the like. Just wanted to note it.

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