2

I have a question.

In my bytecode I calculate statements like if((1==1) && (2==2)){} with this code:

if (node.getOperator().equals(Operator.LOGICAL_AND)) {
    mn.instructions.add(new InsnNode(Opcodes.IAND));
    jmp = new JumpInsnNode(Opcodes.IFNE, null);
    mn.instructions.add(jmp);
}

What happens is that I need to calculate both operators' expressions right and left in order to have a result. The second way is obvious: if the left expression is zero then leave. In this way, you don't have to calculate both sides.

My question is: Is it wrong to do it the first way?

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Tony
  • 489
  • 2
  • 5
  • 22

1 Answers1

3

The IAND opcode is intended for bitwise operations (&). Yes, it is wrong to pre-evaluate the left and right operands if you are trying to implement the short-circuiting logical and operator (&&). Consider what would happen if your operands had side effects:

if (methodWithSideEffect() && otherMethodWithSideEffect()) {}

If methodWithSideEffect() evaluates to false, otherMethodWithSideEffect() should not be invoked. If you pre-evaluate as you suggest, you break this contract, as both methods would be invoked, always.

There is no opcode representing a logical and. I already touched on this in your previous question here.

Community
  • 1
  • 1
Mike Strobel
  • 25,075
  • 57
  • 69
  • OH ok.Can you do the same diagram thing with || like you did with && in the previous question? – Tony Jun 12 '13 at 21:30
  • I might be willing to do that if you go back and accept answers for all the questions you've asked this week :). – Mike Strobel Jun 12 '13 at 21:46
  • There should be an button that lets you 'accept' an answer. The idea is, for each question asked, the best answer gets 'accepted', and the user who provided the answer gets reputation points. You can only accept one answer per question. The button should be located near the up/down vote buttons (you should also upvote good answers). – Mike Strobel Jun 12 '13 at 21:51
  • i didn't know about that sorry mike. – Tony Jun 12 '13 at 22:00
  • No problem :). Since I cannot put multi-line code snippets in comments, I will revise my answer to the previous question to include a description of the `||` operator. As an added note, it is good etiquette to also upvote good answers (even if you did not accept them). You can also upvote insightful comments. – Mike Strobel Jun 12 '13 at 22:05