CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2001
    Posts
    165

    iif statements vs if then

    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


  2. #2
    Join Date
    Apr 2000
    Location
    South Carolina,USA
    Posts
    2,210

    Re: iif statements vs if then

    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

  3. #3
    Join Date
    Jan 2001
    Posts
    165

    Re: iif statements vs if then

    Don't I feel sheepish.


  4. #4
    Join Date
    Aug 1999
    Location
    California
    Posts
    143

    Re: iif statements vs if then

    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?


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured