0

Is it possible to have multi conditional jumps following a single compare instruction?

For instance:

CMP EAX,ECX
    JG More
    JL Less
Equal:
    ;... do something
    RETN
More:
    ;... do something different from "equal" and "less"
    RETN
Less:
    ;... do something different from "more" and "equal"
    RETN

So that the program run "More" branch when EAX > ECX, and does "Less" branch when EAX < ECX.

Is this possible? And more importantly, are there better methods to achieve the same procedure?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
J.Smith
  • 111
  • 8
  • 2
    You apparently just wrote it. Did it work? – Zan Lynx May 17 '17 at 23:32
  • It's not clear where the GCC tag comes in, but GCC already [does this](https://godbolt.org/g/I5iESF) – harold May 17 '17 at 23:36
  • 1
    why wouldnt this work, when you look up the I assume x86 instruction since you didnt tag this, CMP what flags does it change? what flags does JG use, does JG change any flags, why can you use JG after CMP (flags right?). does JG change any flags that JL might rely on for it to work? – old_timer May 17 '17 at 23:56
  • [Your answer, plus an explanation, is contained in this other answer](http://stackoverflow.com/questions/43766549/assembly-jumps-automatically-to-next-label/43774984#43774984). Also, just use `RET`. No need for `RETN`; they are synonyms. – Cody Gray - on strike May 19 '17 at 08:07

1 Answers1

1

Yes, it is possible to have multiple conditional jumps following a single comparison instruction. The comparison instruction (in this case, CMP EAX, ECX) sets status bits in the EFLAGS status register which are used by following conditional branches when deciding whether or not to take a jump.

Take this code for example:

MOV EAX, 5    ; set EAX to 5
MOV ECX, 3    ; set ECX to 3
CMP EAX, ECX  ; sets comparison bits
JL  _target1  
JG  _target2

In this code section, 5 is greater than 3, so the code will jump to _target2.

There are 4 standard flags, ZNCV (Zero flag, Negative flag, Carry flag, Overflow flag), which are set by different instructions at different times. For example, addition (ADD EAX, ECX) would set the Overflow flag if the numbers added were very large and caused integer overflow.

For CMP, the Carry flag is used to show if the first number is greater or less than the second number. The Zero flag is set to 1 if both numbers are equal.

As far as different ways to go about this, if you are branching to many different places based on a single value (equivalent to a switch statement in C), this will often be written with a jump table in assembly. A jump table is a simple table with all the possible targets you might jump to. If you were switching on a number, you would use the number to index into the jump table and find your target.

Fifoernik
  • 9,779
  • 1
  • 21
  • 27
fileyfood500
  • 1,199
  • 1
  • 13
  • 29