除非堆栈指针做任何事情,否则没有真正的理由我们想保留一些东西。然而,在这样一个简单的程序中,仅仅使用寄存器更容易。 (仅使用添加,子,多重峰,阿迪,与,或,ANDI,ORI,LW,SW,BEQ,BNE,SLT,的SLTⅠ,MFLO。)
.text
.global main
main:
addi $t0, $zero, 10 # (counter) we will start with 10 and go down to zero
add $t1, $zero, $zero # (sum) our sum, 0
count:
add $t1, $t1, $t0 # sum += counter
addi $t0, $t0, -1 # counter -= 1
bne $t0, $zero, count # if (counter) goto count
add $v0, $zero, $t1 # return value, our sum
#jr $ra # return (jr not allowed?)
如果你真的想利用堆栈存储局部变量(count和sum),你可以做这样的事情。但是,正如你所看到的,这是一个相当广泛和不必要的。
.text
.global main
main:
addi $sp, $sp, -12 # Make room on the stack ($ra, sum, counter)
sw $ra, 0($sp) # save the return address (not really needed)
sw $zero, 4($sp) # sum variable, set to 0
addi $t0, $zero, 10
sw $t0, 8($sp) # counter variable, set to 10
count:
lw $t0, 4($sp) # load sum
lw $t1, 8($sp) # load counter
add $t0, $t0, $t1 # sum += counter
addi $t1, $t1, -1 # counter -= 1
sw $t0, 4($sp) # save the sum value
sw $t1, 8($sp) # save the counter
bne $t1, $zero, count # if (counter) goto count
lw $v0, 4($sp) # return value, the sum
lw $ra, 0($sp) # restore caller's address
addi $sp, $sp, 12 # pop the stack
#jr $ra # return to caller (jr not allowed?)
请把你在这里的东西放在这里,所以我们知道从哪里开始。顺便说一句,这听起来完全像家庭作业。 – 2012-02-28 19:26:50
意识到,但它不是。发誓对我母亲的生活。它是我们明天在测试中使用的“备忘单”。当我回到我的房间时,我可以提出我的确切时间,它在我的电脑上 – zipzapzoop45 2012-02-28 19:38:20
第二天测试的“备忘单”属于我书中的“作业”范畴 – hirschhornsalz 2012-02-28 19:46:00