Let's say you're writing a Java (or subset-of-Java) compiler and you want to generate bytecode for a unary not expression, !E
. You're past type checking so you know E
has type boolean
, i.e. it will push a 1
or a 0
on to the operand stack.
One way to do it is something like (in Jasmin syntax):
E
ifeq truelabel
iconst_0
goto stoplabel
truelabel:
iconst_1
stoplabel:
i.e. if there's a 0 on the stack push 1, else push 0. Another way to do it, taking advantage of the fact that a boolean
is just an int
with value 1
or 0
, is to say !E = (E + 1) % 2
and generate
E
iconst_1
iadd
iconst_2
irem
Is there an advantage to using one over the other? Or something else entirely?