Forth Easy · Lesson 1 · On the house

CASE OF ENDOF ENDCASE

Dispatch on a kept selector with case ... of ... endof ... endcase, and put a default branch before endcase. Lesson 1 is free — on the house.

Lessons · Forth Easy · Lesson 1 of 10 · On the house

CASE OF ENDOF ENDCASE

Dispatch on a kept selector with case ... of ... endof ... endcase, and put a default branch before endcase.

Illustration for Forth
Lesson 1 is on the house.

case marks a multi-way branch. It compiles so it only works inside a colon definition. The selector stays on the stack through every test until a match consumes it.

of ... endof compares the selector to the value that was on top when of ran. On a match it drops the selector, runs the body, and jumps past endcase. On a miss it drops only the compared value and tries the next clause.

Put a default branch after the last endof and before endcase. That code sees the selector still on the stack, so either use it or drop it. endcase itself drops whatever is left when no of matched.

Any stack-effect word can build the value of compares: dup 3 6 within if ... else ... then before endcase is a range default. Keep every branch's leftover stack the same shape.

case nests inside if or loops. Prefer it over a chain of nested if ... else when one selector chooses among several fixed options.

Common mistake: leaving an extra copy of the selector in an of body. After a match the selector is already gone, so dup inside of copies something else.

case of endcase

: describe ( n -- )
  case
    0 of ." zero" endof
    1 of ." one" endof
    2 of ." two" endof
    dup 3 6 within if ." few" else ." many" then
  endcase cr ;
0 describe 1 describe 2 describe 4 describe 9 describe
: traffic ( n -- )
  case
    1 of ." red" endof
    2 of ." amber" endof
    3 of ." green" endof
    ." ?"
  endcase cr ;
2 traffic 3 traffic
Match this when you type.

Quiz

Where may case ... endcase appear?

Quiz

What happens to the selector when an of clause matches?

Quiz

What must a default branch before endcase do with the selector?

Quiz

After 4 describe with the range default, what prints?

Check

Match the still for: CASE OF ENDOF ENDCASE.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.