How do I return a value from a main function in MIPS?
Let's 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 an invalid program counter error. Apparently this is because you cannot jump out of the main function in MARS . So I tried to rewrite it like this:
main: ADDI $v0, $zero, 5 # $v0 = 5
li $v0, 10 # load 10(exit) for syscall
syscall # exit
After doing this, the $ v0 register contains the value 10, not 5. This is understandable, since I had to rewrite the $ v0 register in order for syscall to work. Then my question is, where can I store the value 5 so that it is correctly returned to the caller of this application?
+1
a source to share
1 answer
Use syscall 17 :
exit2 (terminate with value)
----------------------------
$v0 = 17
$a0 = termination result
Note: "If MIPS is started under GUI, the exit code in $ a0 is ignored."
+3
a source to share