CSE 30 -- Lecture 9 -- Oct 28


This is the example that was given in class.

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

[ search CSE | CSE home | bsy's home page | webster i/f | yahoo | hotbot | lycos | altavista | pgp key svr | spam | commerce ]
picture of bsy

bsy+cse30.f99@cs.ucsd.edu, last updated Wed Nov 3 12:54:02 PST 1999. Copyright 1999 Bennet Yee.
email bsy.


Don't make me hand over my privacy keys!