Graphomata logo

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

KeywordPrimitiveCodeStack (top on the right)C++ equivalent
BEGINA:Ado {

} while (!...);
......A
UNTILjump conditionally to A

Example:
... IF ... ELSE ... THEN

KeywordPrimitiveCodeStack (top on the right)C++ equivalent
......if (...) {

...

} else {

...
}
IFjump conditionally to AA
......A
ELSEAHEADjump to BA B
[ 1 CS-ROLL ]B A
THENA:B
......B
THENB:

Example:
BEGIN ... WHILE ... REPEAT

KeywordPrimitiveCodeStack (top on the right)C++ equivalent
BEGINA:Awhile (true) {
if (!...)
break;

...
}
......A
WHILEIFjump conditionally to BA B
[ 1 CS-ROLL ]B A
......B A
REPEATAGAINjump to AB
THENB:

Example:
BEGIN BEGIN ... WHILE ... UNTIL ... [ 1 CS-ROLL ]  REPEAT

KeywordPrimitiveCodeStack (top on the right)C++ equivalent
BEGINA:Awhile (true) {

if (!...)
break;

if (!...)
continue;
...

}
BEGINB:A B
......A B
WHILEIFjump conditionally to CA B C
[ 1 CS-ROLL ]A C B
......A C B
UNTILjump conditionally to BA C
......A C
[ 1 CS-ROLL ]C A
REPEATAGAINjump to AC
THENC: