In this question, some answers showed how it is possible to make decisions without using "if" statements, however I suspect this is possible because "if" is not the only statement that generates jump
instructions.
Given a fixed compiled language (in example C++), can the generated assembly do some kind of decisions without using jump
and goto
instructions?
Please give an example alternative to a simple if/else statement that does not use such instructions in case of affirmative answer.
In the x86 assembly language, the JMP instruction performs an unconditional jump. Such an instruction transfers the flow of execution by changing the program counter.
The jnz (or jne) instruction is a conditional jump that follows a test. It jumps to the specified location if the Zero Flag (ZF) is cleared (0). jnz is commonly used to explicitly test for something not being equal to zero whereas jne is commonly found after a cmp instruction.
The ARM architecture has an interesting conditional execution trait. Running in full ARM mode, nearly every instruction can have a condition attached to it. These are the same conditions that are used on the B
ranch instructions. An instruction such as add r0, r0, #15
will always execute, but an instruction such as addeq r0, r0, #15
will only execute if the zero flag is set. An equivalent using branches would be:
beq afteradd ; skip add if equal
add r0, r0, #15 ; add 15 to R0
afteradd:
When running on a core that uses Thumb-2, the conditional execution is more limited, but still possible by using the IT
instruction. This instruction will create an "if-then" construct without using branches. The IT
construct is actually part of ARM's Unified Assembly Language, and should be used whether you're writing for ARM or Thumb-2. Here's the UAL version of the conditional add from above.
it eq ; if equal
addeq r0, r0, #15 ; then add 15 to r0
The IT
construct can include more than just a single instruction. Using a series of T
and E
in the instruction, you can add more conditional instructions. In the below example, we will add 15 to R0
if the zero flag is set, otherwise we will subtract 15 from R0
. The ITE
means, fairly literally, if-then-else. The first following instruction should have a condition that matches your ITE
condition, and then the second instruction will become the "else" and should have a condition that is the opposite of the ITE
condition.
ite eq ; if equal
addeq r0, r0, #15 ; then add 15 to r0
subne r0, r0, #15 ; else subtract 15 from r0
I guess this kind of does use if, which may go against what you were asking. In terms of the execution, this implements the if without using a jump, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With