问题
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
{
...
}
回答1:
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
.
回答2:
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
.
来源:https://stackoverflow.com/questions/25031860/difference-between-js-and-jl-x86-instructions