FUNCTIONS CORE

IIF()

Return one of two values according to a logical condition

Syntax

Signature
IIF( lCondition, expTrue, expFalse ) --> xValue

Arguments

lCondition

: a logical expression, .T. or .F.

expTrue

: the expression to evaluate when the condition is .T.

expFalse

: the expression to evaluate when the condition is .F.

Return value

The value of the selected expression.

Description

Evaluates the condition and then evaluates only the selected expression. The other expression is not executed. This allows a branch to guard an operation such as division by zero. The condition must be logical; numbers and strings are not implicitly converted to logical values. All three expressions are required. Both branches must be valid source code and are subject to compile-time type checks, even when not selected.

Notes

IIF() is compiled directly as a conditional expression. With explicitly declared types, the compiler checks the result types of both branches and applies its common-type rules. The example prints "yes", "no" and .T. The division is not executed.

Deliberately invalid examples: IIF( 1, "yes", "no" ) and IIF( .T., 1 ). Expected result: a compilation error, not a runtime value.

Example

IIF.prg
PROCEDURE Main()

   LOCAL nDivisor := 0
   LOCAL nResult

   QOut( IIF( .T., "yes", "no" ) )
   QOut( IIF( .F., "yes", "no" ) )

   nResult := IIF( nDivisor != 0, 10 / nDivisor, 0 )
   QOut( nResult == 0 )

RETURN

Output

yes
no
.T.

See also