Forth Control Flow
Primitive Keywords
BEGIN L = new label; push(L); emit "L:" AGAIN L = pop(); emit "jump to L" UNTIL L = pop(); emit "jump conditionally to L" AHEAD L = new label; push(L); emit "jump to L" IF L = new label; push(L); emit "jump conditionally to L" THEN L = pop(); emit "L:" [ n CS-ROLL ] stack manipulation: move the n-th label (where top is n=0) to the top * Conditionally means "if false".
Additional Keywords
ELSE equivalent to AHEAD [ 1 CS-ROLL ] THEN WHILE equivalent to IF [ 1 CS-ROLL ] REPEAT equivalent to AGAIN THEN EXIT emit "return from function" 0= (before UNTIL, IF and WHILE): emit "negate logically"
Primitive Patterns
AHEAD --> THEN jump forward ... IF --> THEN jump forward conditionally BEGIN <-- AGAIN jump backward BEGIN <-- ... UNTIL jump backward conditionally
Structured Patterns
... IF ... THEN if-then ... IF ... ELSE ... THEN if-then-else BEGIN ... AGAIN infinite loop BEGIN ... UNTIL do-while loop (with the condition negated) BEGIN ... WHILE ... REPEAT while loop
Example: BEGIN ... UNTIL
| Keyword | Primitive | Code | Stack (top on the right) | C++ equivalent | 
|---|---|---|---|---|
| BEGIN | A: | A | do { } while (!...); | |
| ... | ... | A | ||
| UNTIL | jump conditionally to A | |||
Example: ... IF ... ELSE ... THEN
| Keyword | Primitive | Code | Stack (top on the right) | C++ equivalent | 
|---|---|---|---|---|
| ... | ... | if (...) { ... } else { ... } | ||
| IF | jump conditionally to A | A | ||
| ... | ... | A | ||
| ELSE | AHEAD | jump to B | A B | |
| [ 1 CS-ROLL ] | B A | |||
| THEN | A: | B | ||
| ... | ... | B | ||
| THEN | B: | |||
Example: BEGIN ... WHILE ... REPEAT
| Keyword | Primitive | Code | Stack (top on the right) | C++ equivalent | 
|---|---|---|---|---|
| BEGIN | A: | A | while (true) { if (!...) break; ... } | |
| ... | ... | A | ||
| WHILE | IF | jump conditionally to B | A B | |
| [ 1 CS-ROLL ] | B A | |||
| ... | ... | B A | ||
| REPEAT | AGAIN | jump to A | B | |
| THEN | B: | |||
Example: BEGIN BEGIN ... WHILE ... UNTIL ... [ 1 CS-ROLL ]  REPEAT
| Keyword | Primitive | Code | Stack (top on the right) | C++ equivalent | 
|---|---|---|---|---|
| BEGIN | A: | A | while (true) { if (!...) break; if (!...) continue; ... } | |
| BEGIN | B: | A B | ||
| ... | ... | A B | ||
| WHILE | IF | jump conditionally to C | A B C | |
| [ 1 CS-ROLL ] | A C B | |||
| ... | ... | A C B | ||
| UNTIL | jump conditionally to B | A C | ||
| ... | ... | A C | ||
| [ 1 CS-ROLL ] | C A | |||
| REPEAT | AGAIN | jump to A | C | |
| THEN | C: | |||