CS 250 Computer Programming and Problem Solving - FALL 1998 |
---|
[ Home | Syllabus | Notes | Glossary | CS250 WEB Version Home Page | Project Page | Final Study Guide]
Every function call allocates a chunk of memory on the ACTIVATION STACK called the ACTIVATION RECORD.
When you call a function, the activation record is allocated on the stack.
local variables are defined there, parameters are placed there, the return address also.
When you return, the activation record is used to find the
return address and is then destroyed.
That is why local variables can't remember values in between function calls.
Calling a function recursively is no different. It means however, that every time you call a function you get an seperate activiation record which keeps everything straight (it is like you have mutliple copies of the same function).
See also previous notes on this subject
//Let's lable RFind to identify the Return Address by name
int RFind(int a[ ], int x, int start, int end) // PRE: a is an array with elements defined between a[start] and a[end] // and start <= end // Array "a" is sorted // POST: return the location of the element "x" in the array between a[start] and a[end] // if exists, else return where it should be placed { if(start == end) // one element arrays are easy (BASE CASE) return start; int middle = (start+end)/2; // find the middle of the sub- array if(x < a[middle]) // must be in the first "half" of the array return /*call1*/ RFind(a,x,start,middle); // narrow the search to first half else if(x > a[middle]) must be in the second "half" return /*call2*/ RFind(a,x,middle+1,end); else return middle; // here it is! }