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;
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