TKD21
TKD21

Reputation: 283

MIPS Assembly - if condition with substraction

I have the following code in C, representing a bubble sort algorithm:

#include <stdio.h>

int arr[5]={5,3,4,1,2};

int main(){

     int k;

     int N=5,i,j;
     char * parr0 = (char*) arr;/* la parr0, arr */

     char * parrj;

     i=0;
for1:
    if(i>=N) goto Endl; /* slt romp, ri, rN     ///   beq rcomp, $0, Endl*/

    j=0;
 for2:
     if(j>=N-1-i) goto End2;

     parrj = (parr0 + 4*j);

    int x1 = ((int)parrj); /*load word from register x1 to 0(ppj)  (lw x1,0(parrj) ~ replacement of arr[j]*/
    int x2 = ((int)(parrj+4));  /*(lw x2,4(parrj) ~ replacement of arr[j+1]*/

    if(x2 >= x1) goto SkipSwap;

    ((int)parrj) = x2; /*sw x2,0(parrj) ~ x2 -> arr[j]*/

    ((int)(parrj+4)) = x1;  /*sw x1,4(parrj) ~ x1 -> arr[j+1]*/
SkipSwap:
    j++;
        for(k=0; k<N;k++) printf("%d ", arr[k]);
        printf("\n");
    goto for2;
End2:
    i++;
    goto for1;

Endl:
   for(k=0; k<N;k++){
       printf("%d ", arr[k]);
  }

return 0;
}

I have to turn this into Assembly code. I'm particularly curious about this line here:

if(j>=N-1-i) goto End2;

How can I translate that into Assembly code? Do I first need to use the sub instruction to subtract N-1-i and store that in a register or can a simple branch-on-equal instruction do the trick?

Complete beginner to MIPS Assembly here, any advice or documentation you can give me is greatly appreciated!

Upvotes: 0

Views: 210

Answers (1)

Archit Gupta
Archit Gupta

Reputation: 26

You would have to store this result into a register, I would recommend using one of the temporary registers for this. or if you're using Callee or Caller Safe Conventions, you should choose a register accordingly.

sub $t3, $t0, $t1 // assuming i is in $t1, N is in $t0 and j is in $t2
sub $t3, $t3, 1
bge $t2, $t3, End2
// MIPS for Lines following if(j>=N-1-i) goto End2;

Upvotes: 1

Related Questions