简体   繁体   中英

How to exit a loop in assembly

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 skip past the remaining loop segment even if ecx is already at 0?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM