Page 1 of 1


PostPosted: 19 Feb 2013, 21:29
by Ursego
The function iif() has 3 arguments. The 1st one is boolean. If it's true then the 2nd argument's value is returned; otherwise, the 3rd argument's value is returned:

Code: Select all
ls_greeting = iif(lc_sex = "M", "Mr", "Ms")

It works similar to "IIf" function of Visual Basic (as you can read there, "IIf" stands for "Internal If"), NVL2() function of PL/SQL and the ternary operator of C (<cond> ? <if true> : <if false>;). This approach is very convenient - why not to have it in PB? It helps to keep scripts shorter by avoiding the if...else construction - each use of iif() removes 4 extra lines from the script. That's how the fragment would be looking like without iif():

Code: Select all
if lc_sex = "M" then
   ls_greeting = "Mr"
   ls_greeting = "Ms"
end if

CAUTION! If you pass an expression as the 2nd or 3rd argument, that expression is evaluated before being sent to the function (no matter what the result of the Boolean expression is), so DON'T USE iif() as a protection, i.e. to prevent things like zero divide or reading from a not-existing row in a DataWindow:

Code: Select all
ll_result = iif(ll_2 <> 0, ll_1 / ll_2, 0) // runtime error if ll_val_2 = 0!!!
ls_name = iif(ll_row > 0,[ll_row], "No name") // runtime error if ll_row = 0!!!

Save the file iif.srf on your hard disk and import it into your application. The function is overloaded for the following datatypes: string, long, decimal, date, time, datetime, powerobject. To see the overloads, open the function in the "Edit Source" mode. If you are surprised that a global functions is overloaded then read here. :)