我试图在两个值之间找到最大值
_FindMax:
push ebp
mov ebp, esp
mov eax, dword [ebp+12] ; get fist argument
mov ebx, dword [ebp+8] ; get second argument
cmp eax, ebx
jl LESS ; if eax less to LESS
LESS:
mov eax, ebx ; ebx is greate and return it
mov esp, ebp
pop ebp
ret
但问题是LESS:标签始终在执行。例如,如果参数相等,则LESS:label正在执行。为什么?
答案 0 :(得分:3)
实现这一目标的一种非常有效的方法是(假设您至少拥有P6系列处理器):
_FindMax:
mov eax, dword [esp+8] /* get first argument */
mov ebx, dword [esp+4] /* get second argument */
cmp eax, ebx /* compare EAX to EBX */
cmovl eax, ebx /* MOV EBX to EAX if EBX > EAX */
ret
此代码省略了堆栈帧(EBP)并使用内联MOV
操作进行比较。尽管如此,返回值仍然在EAX
。
答案 1 :(得分:2)
LESS中的代码始终执行,无论是否采用分支。您需要跳过您不想执行的代码:
_FindMax:
push ebp
mov ebp, esp
mov eax, dword [ebp+12] ; get fist argument
mov ebx, dword [ebp+8] ; get second argument
; invert the condition, and jump over the code to skip
cmp eax, ebx
jge SKIP ; jmp and return, if aex is the larger one
mov eax, ebx ; ax is NOT larger, so return ebx
SKIP:
mov esp, ebp
pop ebp
ret