Nilesh Agrawal
Nilesh Agrawal

Reputation: 3042

Mutiple conditions in if in MIPS

MIPS provides branching instructions like branch on equal, branch on not equal to register,branch on less than or equal to zero, branch on greater than or equal to zero and so on... all the branching instructions use only two operands and one conditions . What happens if we suddenly encounter multiple conditions in if statement.

So the question is how can one write a MIPS code for :

if( (a<b) & ( b>c ) || (c==d)) {

}
else 
{

 }

Please help with this kind of multiple conditions in if statement.

Upvotes: 1

Views: 13616

Answers (2)

Assuming that $t0 has a, $t1 has b, $t2 has c and $t3 has d:

     outter_if_lbl: 
     bge $t0,$t1,exit_outter   #if a>=b break
     ble $t1,$t2,exit_outter   #if b=< c break
     bne $t2,$t3,exit_outter   #if c != d break
     #add functionality here   

     exit_outter:
     jr $ra #or whatever does your job

I use pseudo-instructions so if you want you can convert them. Google how. The idea behind that ,is the fact that you have to use the opposite case of the if statement for the code to work similarly (and that is a general C to Mips Conversion rule).

Upvotes: 2

markgz
markgz

Reputation: 6266

You can rewrite:

if( (a<b) && ( b>c ) || (c==d)) {

}

Like this:

bool altb = a < b;
bool bgtc = b > c;
bool ceqd = c == d;
bool and1 = altb && bgtc;
bool condition = and1 || ceqd;
if (condition) {
} else {
}

This is how most compilers will evaluate a complex condition in an if statement. Doing it this way is also much faster than chaining a lot of conditional branches together.

Upvotes: 4

Related Questions