Click to See Complete Forum and Search --> : iif statements vs if then


Kdev
April 25th, 2001, 10:37 AM
I want to know why VB insists on executing both the true and false part of a iif statment when it should only do one part.

Example:

If nTotOutput = 0 then
fLinearity = 0
else
fLinearity = (1 - (nTotDev / nTotOutput))
End If

fLinearity = IIf(nTotOutput = 0, 0, (1 - nTotDev / nTotOutput)))



Both of these bits of code should do the same thing however the iif statement will produce an error when nTotOutput = 0 because of the division by 0 problem. Why must VB check that part of the statement when it is going to return the other part anyway?

-K

John G Duffy
April 25th, 2001, 02:15 PM
Thats the design of the IIF function. Read MSDN Help for details
Quote:
"IIf always evaluates both truepart and falsepart even though it returns only one of them. Because of this, you should watch for undesireable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is true."

John G

Kdev
April 25th, 2001, 03:09 PM
Don't I feel sheepish.

Ed_CompSci
September 16th, 2001, 12:33 AM
Hmm, I didn't know that VB had this Iif code. Looks a lot like the C++ ?: in place of if{}. Run into the same problems with it?