Skip to content

Instantly share code, notes, and snippets.

@ChrisMoney
Created February 16, 2012 01:03
Show Gist options
  • Select an option

  • Save ChrisMoney/28da2b60932a77979bae to your computer and use it in GitHub Desktop.

Select an option

Save ChrisMoney/28da2b60932a77979bae to your computer and use it in GitHub Desktop.
Assembly - Recursive function that recursively returns the factorial of various numbers
#Recursive Function
#PURPOSE - Given a number, this program computes the factorial.
# For example, the factorial of 3 is 3*2*1, or 6.
# The factorial of 4 is 4*3*2*1
# This program shows how to call a function recursively
.section .data
#This program has no global data
.section .text
.globl _start
.globl factorial #this is unneeded unless we want to share this function among other programs
_start:
pushl $4 #The factorial takes one argument - the number we want a factorial of.
#So it gets pushed
call factorial #run the factorial function'
addl $4, 5esp #Scrubs the parameter that was pushed on the stack
#movl %eax, %ebx #factorial returns the answer in %eax, but we want it in %ebx to send it as #our status
movl $1, %eax #call the kernel's exit function
#The actual function
.type factorial, @function
factorial:
push1 %ebp #standard function stuff = we have to restore %ebp to its prior state vefore #returning, so we have to push it.
movl %esp, %ebp #This is because we don't want to modify the stack pointer so we use #%ebp
movl 8(%ebp), %eax #This moves the first argument to %eax, 4(%ebp) holds the return #address, and 8(%ebp) holds the first parameter
cmpl $1, 5eax #If the number is 1, that is our base case, and we simply return
#1 is already in %eax as the return value
je end_factorial
decl %eax #otherwise, decrease the value
pushl %eax #push it for our call to factorial
call factorial #call factorial
movl 8(%ebp), %ebx #multiply that by the result of the last call to factorial in %eax
#The answer is stored in 5eax, which is good since that's where return
#values go
end_factorial:
movl %ebp, %esp #standard function return stuff - we have to restore %ebp and %esp
#to where they were before the function started #return from the function
#(this pops the return value, too)
ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment