Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4,VB5,VB6,VBS
Expertise: beginner
Oct 16, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Write concise code with the IIf function

Use IIf when setting a value based upon an expression. This works only in situations where you have two choices, based upon the result of a Boolean expression.

'long way
If Var1 > Var2 Then
   Var3 = Var1 / Var2
   Var3 = Var2 / Var1
End If

'this is more concise
Var3 = IIf(Var1 > Var2, Var1 / Var2, Var2 / Var1)
The IIf function is often useful to evaluate the minimum or the maximum of two numbers:

' the minimum of n1, n2
min = IIf(n1 <= n2, n1, n2)

' the maximum of n1, n2
max = IIf(n1 >= n2, n1, n2)
Note, however, that the IIf syntax takes nearly 3 times as long to execute. Although it compacts the code, it should not be used in situations requiring many repetitions of the code. Moreover, IIf works ONLY in cases where all expressions execute correctly at run-time. In the above example, if either Var1 or Var2 is zero, the "short way" will always generate a run time error as all expressions on the line are evaluated.
Bryan Fazekas
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date