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

StackOverflow https://stackoverflow.com/questions/21654109

  •  08-10-2022
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top