1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
; afact.asm: assembly program to be linked with cfact.c
.386p ; 386 protected mode
.model flat, C ; flat memory model, C calling convention
.stack
.data
; formats will be used to call printf
; c strings terminate in a 0 byte
formats db "the factorial of 6 is %d", 13, 10, 0
.code
; declare printf and external function
extrn printf: proc
; must use masm procedure syntax
factorial proc
push ebp
mov ebp,esp
push ecx
push edx ; edx implicitly used in multiplication
mov ecx,[ebp+8] ; move param into a register
mov eax, 1 ; accumulator
lp0: mul ecx ; eax = eax * ecx (edx ignored)
dec ecx
cmp ecx,2 ; no need to multiply by 1
jge lp0
; at this point eax contains n!, the return value
; prepare for printf: (save eax, for printf returns a value!)
push eax ; second parameter to printf
mov ecx, offset formats ; address of format string
push ecx ; first parameter to printf
call printf
pop ecx ; deallocate parameters
pop eax
pop edx
pop ecx
mov esp,ebp
pop ebp
ret
factorial endp
end |
Partager