www.delorie.com/gnu/docs/gforth/gforth_89.html   search  
Buy GNU books!

Gforth Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.8.1 Selection


If flag is non-zero (as far as IF etc. are concerned, a cell with any bit set represents truth) code is executed.


If flag is true, code1 is executed, otherwise code2 is executed.

You can use THEN instead of ENDIF. Indeed, THEN is standard, and ENDIF is not, although it is quite popular. We recommend using ENDIF, because it is less confusing for people who also know other languages (and is not prone to reinforcing negative prejudices against Forth in these people). Adding ENDIF to a system that only supplies THEN is simple:
: ENDIF   POSTPONE then ; immediate

[According to Webster's New Encyclopedic Dictionary, then (adv.) has the following meanings:

... 2b: following next after in order ... 3d: as a necessary consequence (if you were there, then you saw them).
Forth's THEN has the meaning 2b, whereas THEN in Pascal and many other programming languages has the meaning 3d.]

Gforth also provides the words ?DUP-IF and ?DUP-0=-IF, so you can avoid using ?dup. Using these alternatives is also more efficient than using ?dup. Definitions in ANS Forth for ENDIF, ?DUP-IF and ?DUP-0=-IF are provided in `compat/control.fs'.

  n1 OF code1 ENDOF
  n2 OF code2 ENDOF
  ( n ) default-code ( n )

Executes the first codei, where the ni is equal to n. If no ni matches, the optional default-code is executed. The optional default case can be added by simply writing the code after the last ENDOF. It may use n, which is on top of the stack, but must not consume it.

Programming style note: To keep the code understandable, you should ensure that on all paths through a selection construct the stack is changed in the same way (wrt. number and types of stack items consumed and pushed).

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003