汇编语言循环只经过一次迭代?

Assembly language loop only goes through one iteration?

一整天都在做这个作业,不知道我哪里做错了。我的代码应该使用嵌套循环来打印如下内容:

xxxxxxxxxx
xxxxxxxxx
xxxxxxxx
xxxxxxx
xxxxxx
xxxxx
xxxx
xxx
xx
x

我为此编写的代码是:

# printStars2.s

# Useful constants
    .equ STDOUT,1
# Stack frame
    .equ theChar,-1
    .equ counter,-8
    .equ lineCounter, -16
    .equ localSize,-32
newline:
    .string "\n"
    .equ newlineSz,.-newline-1          # equate msgSz to # of chars

# Code
    .text
    .globl main
    .type main, @function
main:
    pushq %rbp # save base pointer
    movq %rsp, %rbp # set new base pointer
    addq $localSize, %rsp # for local var.

    movb $'*', theChar(%rbp) # character to print
    movl , counter(%rbp) # innerLoop control variable
    movl , lineCounter(%rbp) #outerLoop control variable

outerLoop:
    jmp innerLoop          # jumps to innerLoop
    decl lineCounter(%rbp) # lineCounter--
    movl lineCounter(%rbp), %ebx #copies lineCounter value to intermediate register
    movl %ebx, counter(%rbp) # copies lineCounter value from register to innerLoop counter
    cmpl [=11=], lineCounter(%rbp) #checks if outerLoop has gone through 10 iterations
    jne outerLoop #repeat if not
    jmp exitLoop #exitLoop when complete

innerLoop:
    leaq theChar(%rbp), %rsi # address of char
    movl , %edx # one character
    movl $STDOUT, %edi # standard out
    call write # invoke write function
    decl counter(%rbp) # counter--;
    jg innerLoop # repeat if > 0
    #newLine
    movl    $newlineSz, %edx        # message size
    movl    $newline, %esi          # address of message text string
    movl    $STDOUT, %edi       # standard out
    call    write               # invoke write function

exitLoop:
    movl [=11=], %eax # return 0;
    movq %rbp, %rsp # restore stack pointer
    popq %rbp # restore base pointer
    ret

当我 运行 它似乎只经过一次循环,它只打印一行 10 颗星。如果有人能告诉我我做错了什么或指出正确的方向,我将不胜感激。

输入outerLoop后跳转到innerLoop.

在那里你打印星星并循环,直到计数器达到 0(第 37–42 行)。

然后打印换行符(第 44–47 行)。

然后你return,程序结束

您绝不会跳回到 outerLoop,因此没有循环!

一种解决方法:用内循环的内容替换jmp innerLoop指令。然后,当内部循环完成后,它将继续执行您为外部循环编写的逻辑,一切都会正常进行。由于您的标签 outerLoop:innerLoop: 将紧挨着彼此,因此您可以将它们组合起来,只需要 Loop:.

organization 也避免了跳转到 exitLoop 的需要。