Search code examples
assemblyx86masm

Can't figure out how to implement while loop correctly in assembly?


I'm trying to implement the following pseudocode in assembly: enter image description here

My solution tries to implement the while loop using a LOOP instruction, but this gives me an infinite loop. (I know this is b/c of the garbage values in the ECX, but I don't understand how to overcom this problem and correctly implement the WHILE loop). Here's my code:

.386
.model flat, stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD

.data
A WORD 9
B WORD 8
X WORD 15
sum WORD 0

.code
main PROC
L1:
    cmp X, 3     
    jne ELSEE   ;jump to ELSEE if X!=3 (short circuits the AND condition)
    mov ax, A+3
    cmp X, ax
    jle TRUE  ;jump to TRUE if X<=A+3
    mov bx, B-3
    cmp X, bx
    jl TRUE ;jump to TRUE if X<B-3
    cmp X,0
    jge WHYLE

    TRUE:
        sub X,2
        inc sum
    ELSEE:
        dec X
WHYLE:
    loop L1

    invoke ExitProcess, 0
main ENDP
END main

Solution

  • If the comparison yields greater or equal, jump to the start, otherwise continue out of the loop, e.g. to the exit call. This is effectively a do{}while() loop, which is most natural in asm. Since you can't easily calculate ahead of time how many iterations the loop needs to run, you can't use the loop instruction as the loop condition.

    There are other bugs inside you loop body, but this is how to loop. You might want to keep X in a register instead of using memory every time you access it.

        cmp X,0
        jl SKIP      ; skip the loop entirely if the condition is false to start with
    
    L1:              ; do {
    
       ;;; loop body goes here
        
        cmp X,0
        jge L1       ; }while(X >= 0);
    SKIP:
    
       ;; after the loop