简体   繁体   English

尽管Java提供了逻辑运算符的非短路版本(例如逻辑|,&),但何时需要这些运算符?

[英]While java provides non short-circuit version of logical operators (like logical |, &), when are these required?

I see that java (and many other languages like C# and VB) provide short-circuit and non short-circuit versions of logical " and " and " or " operators. 我看到Java(以及许多其他语言,如C#和VB)提供逻辑“ and ”和“ and” “”运算符的短路和非短路版本。 Where as C/C++ do not provide for non short-circuit versions. 其中C / C ++不提供短路版本。

When are these non short-circuit versions required? 这些短路版本何时需要? And if one can do without them why have these other languages provided for it? 如果没有他们可以做到这一点,为什么还要提供其他语言呢?

For example, you might have a situation where your conditionals are calculated by two methods: 例如,您可能会遇到两种情况来计算条件的情况:

if (methodA() && methodB())

Now if you absolutely require that both methods be ran at this point (perhaps they do something else relevant, like mark down that they have been evaluated), then you should not short-circuit the call: 现在,如果您绝对要求此时都运行两种方法(也许它们做了其他相关的事情,例如标记它们已被评估),那么您就不应该使调用短路:

if (methodA() & methodB())

This guarantees the same result, but it also guarantees that both methods will run. 这样可以保证相同的结果,但是也可以保证两种方法都可以运行。 In general it's almost never used in practice from what I've seen, and I would possibly argue that it's even bad practice. 总的来说,从我所见,它几乎从未在实践中使用过,我可能会争辩说这甚至是不好的做法。

As to the question of WHY is this functionality in some languages and not others - that's simply a question for the language designers. 关于WHY问题,某些语言而不是其他语言具有此功能-这只是语言设计者的问题。 At best we could guess here what their intention was. 充其量我们只能在这里猜测他们的意图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM