Traditionally Forth uses IF to execute conditional code, however there are times when the value or flag that is being tested is needed later. Of course one can simply DUP it for later use, but that involves adding an extra XT ( one CELL ) to the code, plus an extra instruction to execute: -IF is a non-destructive version of IF that overcomes this problem since it preserves the value being tested without adding an extra instruction ( in fact since IF executes code to drop the value -IF is slightly faster ). The most obvious use of -IF is eliminating a DUP preceding an IF, however there are other situations where it can provide more optimal code:
... ?DUP IF ... ELSE ... THEN ...as
... -IF ... ELSE DROP ... THEN ...which is faster ( especially for TRUE ) and which can allow further optimization if the DROP can be incorporated into the following code ( since it's always FALSE ( i.e. 0 ) we may be able to use it )
: IsWinConstant ( str -- str FALSE | val TRUE ) { \ WinVal -- } &LOCAL WinVal over count swap Call wcFindWin32Constant if drop WinVal TRUE else FALSE then ;then
: IsWinConstant ( str -- str FALSE | val TRUE ) { \ WinVal -- } &LOCAL WinVal over count swap Call wcFindWin32Constant -if 2drop WinVal TRUE then ;is both shorter ( 3 CELLS ) and faster ( especially when the condition is FALSE )
Document $Id: p-using-if.htm,v 1.1 2004/12/21 00:18:57 alex_mcdonald Exp $