How do I return a value from the main function in MIPS?

4.8k views Asked by At

Say I want to write the following C program in MIPS:

int main () {
  return 5;
}

When I try the following MIPS code in MARS:

main:   ADDI $v0, $zero, 5     # $v0 = 5
        JR $ra                 # return from main()

I get a 'invalid program counter' error. This is apparently because you cannot jump out of the main function in MARS. So I tried rewriting it like so:

main:   ADDI $v0, $zero, 5     # $v0 = 5
        li $v0, 10             # load 10(exit) for syscall
        syscall                # exit

After executing this, the $v0 register contains the value 10, not 5. Which is understandable since I had to overwrite the $v0 register in order for syscall to work. My question, then, is where would I save the value 5 in order for it to be returned to the caller of this application correctly?

1

There are 1 answers

0
Michael On BEST ANSWER

Use syscall 17:

exit2 (terminate with value)
----------------------------
$v0 = 17
$a0 = termination result

Note that "If the MIPS program is run under control of the MARS graphical interface (GUI), the exit code in $a0 is ignored."