Search code examples
assemblyx8632-bit

Finding the Min of 3 Numbers with a Macro in x86 Assembly


I've put together a simple macro that is meant to find the minimum of three numbers. In it's current state the macro will only work if the first or third parameter is the min, but not the second. Is there something off with my loops or comparisons that i'm not catching? Or anything I should be doing differently? Any recommendations or suggestions are appreciated.

findMin     MACRO   arg1, arg2, arg3
                
            mov eax, arg1 
            
            cmp eax, arg2         ; if eax is greater than arg2 swap
            jg swap1

            cmp eax, arg3         ; if eax is greater than arg3 swap
            jg swap2

            jmp endMac

            swap1: xchg eax, arg2
            swap2: xchg eax, arg3
            endMac:
          
            ENDM

Solution

  • Simplified Macro to Find the Min of 3 Numbers (Min will be in EAX register)

    findMin    MACRO   arg1, arg2, arg3
    
               LOCAL L2, L3
    
               mov   eax, arg1
               
               cmp   eax, arg2
               jg    l2
               cmp   eax, arg3
               jg    l3
               jmp   endMac
    
               L2: xchg eax, arg2
                   cmp  eax, arg3
                   jg   L3
                   jmp  endMac
               L3: xchg eax, arg3
    
               endMac:
    
               ENDM