简体   繁体   中英

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. Where as C/C++ do not provide for non short-circuit versions.

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. At best we could guess here what their intention was.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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