How to exit a loop in assembly

后端 未结 2 2000
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 00:09

I have a loop with a couple of conditions, which means that when the loop is finished, it will proceed to go through the remaining loop segment. How can I force the program to s

相关标签:
2条回答
  • 2021-01-27 00:38

    You'll have to jump past them. That's the only flow control you get. Try to emulate the structure you would use in a higher level language, though, so as to avoid making spaghetti code.

    0 讨论(0)
  • 2021-01-27 00:40

    Loops and conditions are created with LABELS, COMPARISONS and JUMPS:

    xor ecx,ecx                ;ECX = 0
    mov eax,8                  ;EAX = 8
    mov ebx,4                  ;EBX = 4
    
    START_LOOP:
    
    sub eax,ebx                ;EAX = EAX - EBX
    cmp eax,ecx                ;compare EAX and ECX
    jne START_LOOP             ;if EAX != ECX, jump back and loop
                               ;When EAX = ECX, execution continues pas the jump
    

    You can loop a number of times using a loop index that we usually put in ECX:

    xor ecx,ecx                ;ECX = 0
    mov eax,2                  ;EAX = 2
    mov ebx,2                  ;EBX = 2
    
    START_LOOP:
    
    add eax,ebx                ;EAX = EAX + EBX
    inc ecx                    ;ECX = ECX + 1
    cmp ecx,5                  ;compare ECX and 5
    jne START_LOOP             ;if ECX != 5 jump back and loop
                               ;When ECX == 5, execution continues pas the jump
    

    Last, you can use conditions inside a loop using different labels:

    xor ecx,ecx                ;ECX = 0
    mov eax,2                  ;EAX = 2
    xor ebx,ebx                ;EBX = 0
    
    START_LOOP:
    
    cmp eax,ebx               ;compare EAX and EBX
    jle CONTINUE              ;if EAX <= EBX jump to the CONTINUE label
    inc ebx                   ;else EBX = EBX + 1
    jmp START_LOOP            ;JUMP back to the start (until EBX>=EAX)
                              ;You'll never get past this jump until the condition in reached
    
    CONTINUE:
    add eax,ebx                ;EAX = EAX + EBX
    inc ecx                    ;ECX = ECX + 1
    cmp ecx,5                  ;compare ECX and 5
    jne START_LOOP             ;if ECX != 5 jump back and loop
                               ;When ECX == 5, execution continues pas the jump
    
    0 讨论(0)
提交回复
热议问题