如何在程序集中退出循环

xbo*_*ods 1 x86 assembly

我有一个带有几个条件的循环,这意味着当循环结束时,它将继续通过剩余的循环段.即使ecx已经为0,如何强制程序跳过剩余的循环段?

龚元程*_*龚元程 6

使用LABELS,COMPARISONS和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
Run Code Online (Sandbox Code Playgroud)

您可以使用我们通常放在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
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用不同的标签在循环内使用条件:

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
Run Code Online (Sandbox Code Playgroud)