|
|
|
|
|
int SumArray(int a[], int n)
{
int i, s; // <-- local variables
sum = 0;
for (i = 0; i < n; i++)
s = s + a[i];
return(s);
}
|
This function is called by main( ) as follows:
main()
{
int A[10], sum;
sum = SumArray( A, 10 );
}
|
|
First, this is the main program that invokes SumArray:
main:
move.l #A, d0 // Pass address of array
move.l #10, d1 // Pass #elements
bsr SumArray // Invoke SumArray
move.l d0, sum // When SumArray return, update
// total with return value
A: ds.l 10 // The array
sum: ds.l 1
|
Recall: for a non-recursive function, we can use:
|
SumArray:
MOVE.L #0, i ; i
MOVE.L #0, s ; s
WStart:
MOVE.L i, d2 ;; Get i in D2
CMP.L d1, d2 ; compares n (d1) and i (d2)
BGE WEnd ; if (i >= n) exit while loop
MOVE.L d0, a0 ; get base addr of array in a0
MOVE.L i, d4 ; d4 = i
MULS #4, d4 ; d4 = offset in array
MOVE.L 0(a0, d4.w), d4 ; d4 = a[i]
MOVE.L s, d3
ADD.L d4, d3 ;
MOVE.L d3, s ; s = s + a[i]
MOVE.L i, d2 ; d2 = i
ADD.L #1, d2 ; d2 = i + 1
MOVE.L d2, i ; i = i + 1
BRA WStart
WEnd:
MOVE.L d3, d0 ; return(s) [ in agreed place d0 ]
RTS
***** Function will not execute pass this point ****
i: ds.l 1 ; reserve SPACE for local variable i
s: ds.l 1 ; reserve SPACE for local variable s
|
NOTE:
|
|
|
|
We need a more advance way to store the local variables for a subroutine !!!
|
|