Tony
Tony

Reputation: 507

Bytecode in asm operators && or ||

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?

Upvotes: 2

Views: 1428

Answers (1)

Mike Strobel
Mike Strobel

Reputation: 25623

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.

Upvotes: 3

Related Questions