130 likes | 249 Views
By E. W. Dijkstra. Recursive Programming. The Aim . Old-skool way: static allocation Two problems: More memory is used than is needed No recursion!!!. The Aim. Dijkstra's way: the stack!. Stack Requirements. A static stack pointer variable
E N D
By E. W. Dijkstra Recursive Programming
The Aim • Old-skool way: static allocation • Two problems: • More memory is used than is needed • No recursion!!!
The Aim • Dijkstra's way: the stack!
Stack Requirements • A static stack pointer variable • Points to the top of the stack, or the first free space available to the stack • Bunches of consecutive space to put the stack • That's it!
Call Stack • We need to organize our variables somehow. • Parameters • Local variables • Anonymous immediate results--values that expressions evaluate to mid-procedure • Function call return values • Nested algebraic expressions • These can be placed in a separate stack, or atop the call stack.
Nested Algebraic Expressions • Plotting “(” as a function call and “)” as a return on a time line results in correctly-nested pairs of parentheses. • Likewise, complex algebraic expressions can be computed as a bunch of tiny subroutines, the parameters of which (the numbers) can be stored on a stack efficiently and simply.
Nested Algebraic Expressions • This can be achieved with two simple operations: • select a new number X, described as: vk := X; k := k+1; • Perform an arithmetic operation OP: k:= k-1; vk-1 := vk-1 OP vk;
Nested Algebraic Expressions • For example: A+(B-C)X(D/E+F)yields:V0 := A; v1:= B; v2 := C; v1 := v1-v2; v2 := D; v3 := E; v2 := v2/v3; v3 := F; v2 := v2+v3; v1 := v1Xv2; v0 := v0+v1; • V0 is the required result at the end.
Nested Algebraic Expressions • What if symbols A, B, C, etc. are functions requiring further calculations? For example, ifC := P/Q-R+SxTthen C's value would still end up in v2, and the subroutine's temporary data could be stored on the stack the same way without ruining anything before or after the call of the C function. • This means Dijkstra's simple stack system works for lotsa cases. • This is a good thang.
Performance Issues • Dijkstra suggests future systems designs might need to be created with stacks in mind to achieve desirable performance. • MIPS has registers for parameter passing, return values, the stack pointer, and the return address. • C / C++ uses these registers when they are sufficient, but Java pushes all parameters to the stack. • For nested algebraic expressions, magnetic tape can be used in the most efficient way possible for stack storage. HA!
Performance Issues • The stack also allows programs written with block structuring to save space at the cost of time by allocating space at the top of the stack for variables within a block only when they are needed. • Space is saved at the cost of performance because the address in relation to the stack pointer must be calculated at runtime.