//---------------------------------------------------------------- // fact.s // // Here is an implementation in assembly language for the // famous factorial function, defined recursively for any // nonnegative integer n by this two-part rule: // // unsigned int fact( unsigned int n ) // { // if ( n == 0 ) return 1; // else return n*fact( n-1 ); // } // // programmer: ALLAN CRUSE // written on: 10 MAY 2005 //---------------------------------------------------------------- .text fact: # setup access to the stack-frame pushl %ebp # preserve former frame-pointer movl %esp, %ebp # establish access to new frame # test for branching to the two-part rule cmpl $0, 8(%ebp) # function argument equals zero? jne recur # no, then do the recursive case # here we handle the base case movl $1, %eax # else setup one as return-value jmp factx # and exit to the calling routine recur: # here we handle the recursion case push %edx # preserve caller's value in EDX # prepare function-argument for recursive call movl 8(%ebp), %eax # copy current function-argument decl %eax # decrement argument for call # this is the recursive call to obtain: fact( n-1 ) pushl %eax # push the new argument n-1 call fact # call the factorial function addl $4, %esp # discard argument from stack # now the function-value in EAX gets multiplied by n mull 8(%ebp) # multiplies 'fact( n-1 )' by n popl %edx # restore caller's value to EDX factx: popl %ebp # restore former frame-pointer ret # and return conrol to caller .global fact # entry-point is a public symbol .end # no further statements follow