【问题标题】:MIPS nested function the program is dropped off bottomMIPS 嵌套函数程序被从底部丢弃
【发布时间】:2017-03-14 11:47:24
【问题描述】:

对不起,我不是 MIPS 方面的专家。我需要导入一个介于 0 和 5 (0 4,我会收到一条错误消息 errorDimensionMessage,并且我的程序会重新启动函数 jal dimension,直到输入正确的值。在此之后,如果我输入正确的值(例如 3),程序将进入 jal exit 以退出。

(代码更新)

问题是在 5 (error) -> 3 (OK) 之后程序掉线了。

.data
    InsertDimension: .asciiz " Insert an integer (n) with value between 0 and 5 (0 < n < 5): "
    errorDimensionMessage: .asciiz  " Error. Matrix dimension is not valid (e.g., 0 < n < 5)\n"
    messageExit: .asciiz " Exit...\n"


.text
.globl main
    main:
        jal dimension
        jal exit

   exit: 
        la $a0, messageExit 
        li $v0, 4 # print string
        syscall
        li $v0, 10 # loads the service that exits
        syscall

    dimension:
        move $s0, $ra # save return address into s0
        la $a0, InsertDimension 
        li $v0, 4 # print string
        syscall 
        li $v0, 5 # read an integer from console and put it in $v0!
        syscall
        jal isValidDimension
        move $ra, $s0    #restore return address that was saved into s0
        jr $ra #return

    isValidDimension: 
        move $s1, $s0 # save return address into s0
        beqz $v0, errorDimension
        bgt $v0, 4, errorDimension
        move $s0, $s1 # save return address into s0
        jr $ra #return

    errorDimension:
        la $a0, errorDimensionMessage 
        li $v0, 4 # print string
        syscall
        j dimension # return to dimension

【问题讨论】:

    标签: mips mars-simulator


    【解决方案1】:

    jal dimension # return to dimension 这不是跳回dimension 的正确方法。您想改用常规的无条件跳转,即J 指令(或B)。

    现在发生的情况是 jal 更改 $ra 以指向 jal 之后的指令地址,即超过程序的末尾。因此,当 dimension 中的 jr $ra 被执行时,你会跳过程序的末尾,因此你会得到 “程序从底部掉下来”

    【讨论】:

    • 谢谢迈克尔。我使用嵌套函数更新了代码,但仍未清除您的帮助。
    • 好吧,就像我说的,jal 不是在这里使用的正确指令。您应该使用常规跳转,或者可能使用jr $ra
    • 如果我使用 jr $ra,程序会在我需要返回维度时返回到 jal 退出
    • 然后像我在回答中建议的那样使用JBJAL 修改 $ra。除非您想要作为副作用,否则没有理由在J/B 上使用它。
    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    相关资源
    最近更新 更多