Search code examples
assemblyfasm

Assembly find max of two value


I'm trying to find maximum between two values

_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

but problem is that LESS: label is executing always. for example if parameters are equal then LESS: label is executing. Why??


Solution

  • A really efficient way to achieve this would be (assuming that you have at least a P6 family processor):

    _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
    

    This code omits the stack frame (EBP) and uses an inline MOV operation to do the comparison. Nevertheless, the return value is still in EAX.