2

I am writing a program in MIPS but cannot wrap my head around writing the following statement below. How do I write a logical statement like this in MIPS instruction set?

return a > b ? a : b;
Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

2 Answers2

2
  • return : return some value to the callee (if expression presents).
  • A ? B : C : This is conditional operator. If A is true (non-zero), B is evaluated. Otherwise, C is evaluated.

If a and b are signed 32-bit integers, it should be like this:

# assuming
# a = $t0
# b = $t1
# return value = $v0

slt   $t2, $t1,   $t0     # $t2 = (b < a)
beq   $t2, $zero, nottrue # if (!(a > b)) goto nottrue
addui $v0, $t0,   $zero   # return value = a (not harmful even if executed when jump is taken)
jr  $ra                   # return
sll $zero, $zero, 0       # nop: prevent instruction after branch from being executed
nottrue:
addui $v0,   $t1,   $zero # return value = b
jr    $ra                 # return
sll   $zero, $zero, 0     # nop: prevent instruction after branch from being executed
Konrad Lindenbach
  • 4,911
  • 1
  • 26
  • 28
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
-1

First of all break it in simple if statements, MIPS is an Assembly Language so all that won't work if they are complicated,remember the fact that your brain is not a compiler so try not to write complex code.