Forth/Manipulating the Stack
From Wikibooks, the open-content textbooks collection
< Forth
The Parameter Stack
A data structure common to many languages is the stack. A LIFO (last-in first-out) type of stack called the Parameter Stack (to distinguish it from the Return Stack ) is frequently the implied source and destination for many of the data and arithmetic operations performed in FORTH.
Typical operations will find their input parameters on the stack, usually remove ( Pop ) these inputs, then place the new results back onto the stack ( Push ).
While FORTH has variables, arrays, strings, and other data structures, the use of the stack is combined with the philosophy of the language to achieve a variety of advantages.
- If a piece of code only uses the stack for its inputs, outputs, and intermediate values, it is inherently re-entrant in almost every case.
- If a piece of code maintains stack parity, that is it neither removes or abandons values on the stack between its beginning and end, then a call to it can be inserted anywhere in a body of code.
- The stack is like a switchyard that can get data to and from anywhere. Data can be switched between all parts of the system by reading it or writing it to the top element of the stack.
- Op codes do not need to use bits to specify register values, instead, two RISC machine style instructions are used in sequence, analagous to LOAD then ADD. These simpler instructions allow efficient implementation, .