Skip to main content

Command Palette

Search for a command to run...

FORTH Basic Master Level 3

Updated
•9 min read•View as Markdown

Stack Operations

The key to understanding FORTH lies in the fact that all computation and control is performed on a simple structure called the "stack." A stack is a mechanism where data is pushed in sequence (push), like stacking plates, and retrieved from the top (pop). Using this simple structure, FORTH can perform complex calculations without variables or function calls.

Basic Stack Operations

In FORTH, simply entering numbers automatically pushes them onto the stack. For example, if you enter 2 3, the stack state becomes [2 3] (left is bottom, right is top). When you execute +, it takes the top two values, adds them, and pushes the result back. The result becomes [5], and entering . displays the top value.

2 3 + .
→ Output: 5

In this way, FORTH thinks in terms of "flow of operations" rather than "expressions." Instead of assigning to a variable like a = 2 + 3 as in C or Python, you build up sequential actions: "push 2 and 3 onto the stack, add them, and get the result." This clear flow is FORTH's strength, and also why bugs are easy to trace visually.

Arithmetic Operations and Stack Visualization

All arithmetic operations in FORTH are performed through the stack. The main ones are as follows:

OperatorMeaningExampleResult
+Addition2 3 + .5
-Subtraction10 4 - .6
*Multiplication5 2 * .10
/Division9 3 / .3
modModulo5 3 mod .2
/modDivision and modulo5 3 /mod . .1 2

You can check the stack state by inserting .S during execution.

For example, executing 2 3 + 4 .S lets you see all values on the stack (in this case, 5 and 4). Unlike ., values are not removed from the stack. This kind of interactive visualization makes learning FORTH intuitive.

Also, in gforth version 0.7.9, the stack state is always displayed at the bottom of the screen, making it very easy to understand.

Thinking in Compound Expressions

The first stumbling block for FORTH beginners is not being able to "write expressions." However, in FORTH, all calculations are understood as the flow of "pushing values onto the stack and transforming them with instructions." This is also training to develop a "stack-thinking brain."

For example, to write (a*b) + (c*d), in C you would simply write a*b + c*d, but in FORTH it expands as follows:

a b * c d * +

First, a b * calculates a*b, and while leaving that on the stack, c d * is calculated. Finally, + adds both to complete the operation. This concept of "sequential processing + stack retention" is the foundation of FORTH's dataflow design. Advanced users can assemble code while mentally simulating stack operations.

Basic Stack Operation Words

FORTH's power lies in the basic words that freely manipulate the stack. By combining the following operations, you can construct almost any process.

WordActionExampleResult
DUPDuplicate top3 DUP[3 3]
DROPRemove top3 4 DROP[3]
SWAPExchange top two2 3 SWAP[3 2]
OVERDuplicate second1 2 OVER[1 2 1]
ROTRotate top three1 2 3 ROT[2 3 1]
.SDisplay stack contents1 2 3 .S1 2 3 <top>

These operations may seem simple, but when combined, they enable extremely flexible computation.

For example, to write (a + b) * 2 in FORTH:

a b + 2 *

If you want to reuse the same value midway, use DUP:

3 DUP * 2 *

This means "duplicate 3 → 3×3=9 → 9×2=18." In this way, stack operations are designed so that each process can be visually traced, allowing you to think of the entire program as a "flow of numbers."

Most operations can be done with combinations of the previous words, but that alone can become verbose. It's good to remember the following words as well:

WordActionExampleResult
?DUPDuplicate if top is non-zero1 ?DUP 0 ?DUP[1 1 0]
DOWNReverse of ROT1 2 3 DOWN[3 1 2]
-ROTReverse of ROT1 2 3 -ROT[3 1 2]
NIPRemove second1 2 NIP[2]
TUCKDuplicate top below second1 2 TUCK[2 1 2]
2DUPDuplicate top two1 2 2DUP[1 2 1 2]
2DROPRemove top two1 2 3 2DROP[1]
2OVERDuplicate 3rd and 4th to top1 2 3 4 2OVER[1 2 3 4 1 2]
2SWAPExchange 1st-2nd with 3rd-4th1 2 3 4 2SWAP[3 4 1 2]
PICKDuplicate (n+1)th to top1 2 3 2 PICK[1 2 3 1]
ROLLMove (n+1)th to top1 2 3 2 ROLL[2 3 1]

gforth and most other FORTH systems are case-insensitive. Words produce the same result whether entered in uppercase or lowercase.

To exit gforth, type bye or press Ctrl+D at the beginning of an empty line.

Defining and Reusing Words

In FORTH, you can define any process as a "word." A word is the unit of instruction in FORTH, equivalent to a function or subroutine.

: ADD3NUM ( a b c -- sum ) + + ;

With this definition, executing 2 3 4 ADD3NUM . outputs 9. Word definitions are registered in FORTH's dictionary and become available the moment they're defined. This "define and immediately execute" structure makes FORTH a "self-growing language."

: add3num ( a b c -- sum ) + + ;
2 3 4 add3num .
→ Output: 9

To decompile a defined word, enter see followed by the word.

Comments

Characters between ( and ), and characters from \ to the end of the line, are comments. A space is required after ( and \, but no space is needed before ).

1 2 ( one two ) 3 4 \ three four
.s
→ Output: <4> 1 2 3 4

Thinking with Stack Diagrams

In FORTH, there's a convention of writing "stack diagrams" to clarify the input and output of words (instructions). Since ( to ) is treated as a comment, stack diagrams use this feature to describe what data a word takes from the stack and what data it returns, in the form (input -- output).

The stack diagram format is defined in the ANS Forth standard (1994 onwards).

( before -- after )   \ Data stack
( before -- after ) ( R: beforeR -- afterR )   \ Return stack can also be noted

The stack diagram ( n -- n^2 ) means "takes n as input and returns n² as output." By reading this notation, you can understand program behavior as a "flow" rather than an expression. Even in complex programs, you can grasp the overall behavior just by following how each word consumes the stack and what it pushes.

FORTH programming, which manipulates the stack, is actually close to dataflow diagrams. Each word becomes a node that "receives input and passes output," and data on the stack passes through these nodes in sequence.

For example, consider the following program:

: HYPOT ( a b -- c ) DUP * SWAP DUP * + FSQRT ;

This is a word that calculates the hypotenuse of a right triangle. The stack diagram ( a b -- c ) indicates that it takes values a and b as input and returns output c. Within this single line, DUP and SWAP adjust the data flow, while + and FSQRT perform mathematical processing. By tracing the meaning of each operation with stack diagrams, you can understand the entire algorithm visually.

Symbols Used in Stack Diagrams

AbbreviationMeaning
nNormal integer
uUnsigned integer
xAny type
cCharacter value (1 byte)
addrAddress
a-addrAligned address
c-addrCharacter address
dDouble integer (2 cells)
f rFloating-point value
xtExecution token
flagBoolean flag
lenString length
iIndex

Notation for Special Stacks and Regions

SymbolMeaningExample
(--)Data stackNormal stack diagram
(R:--)Return stackExample: >R ( x -- R: x )
(F:--)Floating-point stackExample: F+ ( F: r1 r2 -- r3 )
(C:--)Control stack (compile time)Used in explanations of compile-time words

Examples for Variables, Arrays, and Addresses

WordStack DiagramMeaning
@( addr -- x )Read value from address
!( x addr -- )Write value to address
+!( n addr -- )Add n to contents at address and write back
CREATE( "<name>" -- )Create a name (dictionary registration)
ALLOT( n -- )Allocate n bytes of memory
,( x -- )Write value at current dictionary pointer

Checking Stack Depth

In FORTH, you can use the word depth which returns "how many values are on the stack (depth)."

1 2 3 depth .    \ → 3

Add All Values on Stack

: SUM
    DEPTH 1 DO
        +
    LOOP
;

Delete Stack Values

: CLEAR
    BEGIN DEPTH 0> WHILE
        DROP
    REPEAT
    \ Also clear floating-point stack
    BEGIN FDEPTH 0> WHILE
        FDROP
    REPEAT
;

What It Means to Think in Stacks

Programming in FORTH is not "writing statements to instruct a machine," but rather the work of designing "how data flows and where it changes form." This way of thinking also connects to modern dataflow languages (such as LabVIEW and TensorFlow).

Through the minimal structure of the stack, FORTH achieves "maximum expression with minimum elements." Not procedural, but fluid—FORTH programming proceeds as numbers flow and instructions sculpt that flow.