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. I know could have used BNE but I want to learn BEQ. Please tell me what is the problem is this code
.text
main:
li $t0,1
li $t1,2
li $t2,3
li $t3,4
li $v0,5
syscall
move $s0,$v0
beq $s0,$t0,ADDTN
ADDTN:
li $a0,40
li $v0,1
syscall
li $v0,5
syscall
move $s1,$v0
li $v0,5
syscall
move $s2,$v0
add $a0,$s1,$s2
li $v0,1
syscall
li $v0,10
syscall
beq $s0,$t1,SUBTN
SUBTN:
li $a0,50
li $v0,1
syscall
li $v0,5
syscall
move $s3,$v0
li $v0,5
syscall
move $s4,$v0
sub $a0,$s3,$s4
li $v0,1
syscall
li $v0,10
syscall
for example:
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
BEQinstruction, so the branch is absolutely superfluous here. And further, if the condition is not met, the program continues with the code directly following theBEQinstruction.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”:
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…