int fact(int N) {
int x;
if (N < 2) return 1;
x = fact(N-1);
return N*x;
}
fact: subu $sp, $sp, 16 #allocate space on the stack sw $fp, 4 ($sp) addu $fp, $sp, 16 sw $ra, -8 ($fp) #losing the return address would be bad # End of the prolog bge $a0, 2, nope #notice that in C it was (N < 2) li $v0, 1 b epi # end of the basis case nope: sw $a0, -4 ($fp) # we don't want to lose N subu $a0, $a0, 1 jal fact sw $v0, 0 ($fp) #Not needed # but we made space for it so we will use it. lw $v1, -4 ($fp) #get N back mul $v0, $v0, $v1 #epiloge epi: lw $ra, -8($fp) #restore the return address lw $fp, -12 ($fp) addu $sp, $sp, 16 #fix the stack so it looks like we did not touch it. jr $ra
bsy+cse30.f99@cs.ucsd.edu, last updated
email bsy.