3

It seems both JS and JL can implement the comparison in below code snippet (var >= 0), then what's the difference of using these 2 to implement if/else?

BTW: the EFLAGS they check are a little difference, so I am also wondering why different EFLAGS are tested for similar statement.

int var;
if (var >= 0)
{
...
}
else
{
...
}
Thomson
  • 20,586
  • 28
  • 90
  • 134

2 Answers2

7

JS jumps if the sign flag is set (SF=1), while JL jumps if the sign flag doesn't equal the overflow flag (SF != OF).

There are situations where one of these condtions will be met, but not the other. Consider the following:

mov al, -100
cmp al, 30

Here the flags will be set based on the result of -100 - 30. -100 is negative and 30 is positive, but the result (-130) can not be represented by 8 bits in two's complement, so you get arithmetic overflow and a result of positive 126.

This is perhaps easier to see if we use hexadecimal notation: -100 == 0x9C, 30 == 0x1E, 0x9C - 0x1E = 0x7E == 126.

So we have a positive result (SF=0) and overflow (OF=1). Therefore, in this case JS would not jump but JL would (since SF != OF).

Which jump condition you should use depends on what you're trying to achive. If you're comparing two values and you want them to be interpreted as signed and jump if one is less than the other; use JL. If you want to jump if the result if a calculation is negative; use JS.

Thomson
  • 20,586
  • 28
  • 90
  • 134
Michael
  • 57,169
  • 9
  • 80
  • 125
0

Some further investigation shows that to implement conditional statement in C, the selection of JS/JL depends on previous compare instruction. JS is used if comparing via TEST and JL is used if comparing by CMP.

Thomson
  • 20,586
  • 28
  • 90
  • 134
  • 2
    The `test` instruction always clears OF, so JL and JS are equivalent after a `test`. The compiler could use JS after a `test` if it feels like it. – Raymond Chen Aug 05 '14 at 04:00
  • `test eax,eax` / `jl` works perfectly fine because [`test eax, eax` sets FLAGS identically to `cmp eax, 0`](https://stackoverflow.com/a/38032818/224132). – Peter Cordes Sep 27 '20 at 02:25