不知道如何在汇编中正确实现 while 循环?
Can't figure out how to implement while loop correctly in assembly?
我试图在汇编中实现以下伪代码:
我的解决方案尝试使用 LOOP 指令实现 while 循环,但这给了我一个无限循环。 (我知道这是 ECX 中垃圾值的 b/c,但我不明白如何克服这个问题并正确实现 WHILE 循环)。这是我的代码:
.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
如果比较结果大于或等于,跳转到开始,否则继续跳出循环,例如到退出电话。这实际上是一个 ,这在 asm 中是最自然的。由于无法提前计算循环需要运行的迭代次数,因此无法使用loop
指令作为循环条件。
你的循环体内还有其他错误,但这是如何循环的。您可能希望将 X
保存在寄存器中,而不是每次访问它时都使用内存。
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
我试图在汇编中实现以下伪代码:
我的解决方案尝试使用 LOOP 指令实现 while 循环,但这给了我一个无限循环。 (我知道这是 ECX 中垃圾值的 b/c,但我不明白如何克服这个问题并正确实现 WHILE 循环)。这是我的代码:
.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
如果比较结果大于或等于,跳转到开始,否则继续跳出循环,例如到退出电话。这实际上是一个 loop
指令作为循环条件。
你的循环体内还有其他错误,但这是如何循环的。您可能希望将 X
保存在寄存器中,而不是每次访问它时都使用内存。
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