Search code examples
arraysassemblyprocedure

Procedure returning -1 regardless of array being sorted


I'm currently writing a procedure in Assembly to see if an array is sorted. Here is my code:

.DATA

inputIntMessage BYTE "Enter an integer: ", 0
intArray     DWORD  4 DUP (?)
integerInput DWORD   ?
sorted DWORD ?

.CODE
main PROC
;Here is where I insert whatever the user input into the array
mov eax, 0
mov ecx, LENGTHOF intArray
L1:
    intInput inputIntMessage, integerInput ;This is the user input
    mov ebx, integerInput
    mov intArray[eax*4], ebx
    inc eax
    loop L1

call if_sorted
intOutput sorted
INVOKE ExitProcess, 0


if_sorted PROC
    mov esi, OFFSET intArray
    mov ebx, 0
    mov ecx, LENGTHOF intArray

    L2: 
        mov eax, [esi + TYPE intArray * ebx]
        inc ebx
        cmp eax, [esi+ TYPE intArray * ebx]
        jle less_than_or_equal
        jg greater_than
    less_than_or_equal:
        mov sorted, 1
        loop L2
    greater_than:
        mov sorted, -1
    ret
if_sorted endp

main ENDP

The if_sorted procedure returns 1 or -1 based on if the array is sorted (1 if the array is sorted, and -1 if it is not). I have run through the debugger and when the array is sorted, the debugger goes to the line call if_sorted and then instantly goes to intOutput sorted and outputs -1 (when it should have ran through the if_sorted procedure). When the array is not sorted, the debugger goes to the line call if_sorted and properly runs through the procedure, and outputs -1. Any ideas?


Solution

  • I have solved it! What I had forgotten is to put a ret after the loop finished, so:

    less_than_or_equal:
            mov sorted, 1
            loop L2
            ret
        greater_than:
            mov sorted, -1
            ret
    

    Once I included that the procedure worked fine.