CompOrg Spring 2005 - HW2 FAQ

Click on a question to expand it (for the details).
Click on the question title again to hide the details.

+ factorial sample code

Question:

Where is the code we developed in class (factorial)?


Answer:

The assembly code is shown below. The complete code (including a main to test the function and a Makefile), is available here.

#
# Code developed in class Feb 25th - a factorial function written
#  in IA32 assembly language.
#  The C code we started with was:	
#  int fact(int x) {
#     int y=x;
#     if (x==0) return(1);
#     while (x>1) {
#	x--;
#	y*=x;
#     }
#     return(y);
#  }
	
	.text
.globl fact
	.type	fact,@function
fact:
	pushl	%ebp
	movl	%esp, %ebp
	movl    8(%ebp),%eax     # eax is x

	movl    %eax,%edx        # y = x (y is in edx)
	cmpl    $0,%eax          #
	jne     maincode	 # jump to main code if x!=0 

	# x is 0, so return 1
	movl    $1,%eax		 # eax is return value
	jmp     fact_end         # done - go to end of function

maincode:		
# while (x>1) { x=x-1   y = y*x }
	cmpl    $1,%eax		 # compare x and 1
	jle     fact_almost_end  # jump if x <= 1
	decl    %eax		 #  x--
	imull   %eax,%edx	 # y=x*y
	jmp     maincode
fact_almost_end:
	movl    %edx, %eax       # need to put y in eax (to return it).
		
fact_end:		
	leave
	ret