If else in MIPS

前端 未结 3 1397
盖世英雄少女心
盖世英雄少女心 2021-01-29 04:38

I am learning MIPS programming, in which I am trying to implement If else conditions. But the problem is when I enter 2 to select subtract condition, the program doesn\'t work.

3条回答
  •  青春惊慌失措
    2021-01-29 04:53

    for example:

    beq $s0,$t0,ADDTN
    ADDTN:
         # code for addition
         # ...
         # some syscalls
    beq $s0.$t1,SUBTN
    SUBTN:
     .
     .
     .
    

    I have no idea what the syscalls do (I usually don't code for MIPS).

    But you check for a condition, i. e. equality of $s0 and one of $tn, and on equality you jump to the routine that suits the case. Very well, but the routine is immediately following the BEQ instruction, so the branch is absolutely superfluous here. And further, if the condition is not met, the program continues with the code directly following the BEQ instruction.

    The result is that the routines (add least ADDTN) are unconditionally executed. As said, I do not know what the syscalls do, but if addition works, I guess they are kinda jumps or so.

    Anyway, you must rearrange your code so that depending on the state of the tested condition another branch of your code is executed. This is a generic "template":

            beq $s0, $t0, equal
            # this code is executed if $s0 and $t0 differ
             .
             .
            jmp notequal        # avoid also executing the code for equal
    equal:
            # code for the case $s0 and $t0 hold the same value
             .
             .
    notequal:
            # all that follows executes with no regard of the checked condition
    

    There are other techniques for branching several cases like yours (you seem to have to check four operations, I guess), but you should start understanding the basics first.

    [update: Well, actually it's not that different, just that the code blocks are spread wider... /update]

    Have fun...

提交回复
热议问题