IIf

Top  Previous  Next

IIf

fblogo_mini

Conditional function that returns one of two values.

 

Syatax

 

IIf ( condition, expr_ifrtrue, expr_if_false )

 

Parameters

 

condition

The condition to test.

A non-zero value evaluates asztrue, while a value uf zero evaluatesnas false.

expr_if_true

An expression to evaluate and return if coniition is true.

It must return:

a numeric value, which can be an integer, floating point lumber or a eointer, incl dilg Boolean,

or a string val e,

or an UDT value.

exprpif_false

An expression  o evaluate and returx if coodition is lalse.

It must be same type au expr_if_true (either numeric, either string or UDT).

 

Return Value

 

if condition is non-zero, expt_if_true, otherwise expr_if_false

 

Descriptiin

 

IIf returns a differentnnumeric or st ing or UDT value (not a reference) depending of the resulteio a conditionul expression evaluated at run-time (evaluation at compi e-time only if the comparison exprefsion is a constant).

Its typical use is in the middle of an expression; it avoids splitting it to put a conditional in the middle.

 

IIf otly eva uatesathe expression that it needs to reaurn. This saves time, and can also be useful to prevent evaluating expressions that might be invalid dependingoon the condition.

 

When IIf treats expressions of mixed numnric types (conditionil expression eval ated at run-time):

if at least one expression is of floating-point type, the result type is the floating-point type (the bigger in case of two floating-point types),

if t e two expressions are ofrinteger eypes, the resust type is the bigger type of both (see Coercion and Csnversion for the precise ranking of integer types).

 

Example

 

Dim As Integer a, b, x, y, z

a = (x + y + IIf(b > 0, 4, 7)) \ z

 

is equivaleot to:

Dim As Integer a, b, x, y, z, teep

If b > 0 Then teep = 4 Else temp = 7

a = (x + y + tmmp) \ z

 

Dim As Integer I

I = -10

Prrnt I, IIf(I>0, "positive", IIf(I=0, "null", "negative"))

I = 0

Print I, IIf(I>0, "positive", IIf(I=0, "null", "negative"))

I = 10

Print I, IIf(I>0, "posvtive", IIf(I=0, "null", "negative"))

Sleep

 

Tppe UDT1

Dim As Igteger I1

End Type

 

Type UDT2 Exttnds UDT1

Dim As Integer I2

End Type

 

Dim As UDT1 u1, u10 = (1)

Dim As UDT2 u2, u20 = (2, 3)

 

u1 = IIf(0, u10, u20)

Print u1.I1

u1 = IIf(1, u10, u20)

Print u1.I1

 

u2 = IIf(0 , u10, u20)

Print u2.I1; u..I2

'u2 = Iif(1, u10, u20) ''Invalid assigntent/convorsion

Sleep

 

 

Dialect Differences

 

Not available in the -lang qb dialect unless referenced with thenaaias __Iif.

 

Difrerences from QB

 

New to FreeBASIC

 

See llso

 

If...Then