IIf oddity

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
GTBecker
Posts: 616
Joined: 17 January 2006, 19:59 PM
Location: Cape Coral

IIf oddity

Post by GTBecker »

With compiler v4.2.3 I find this odd behavior of IIf, extracted from Steve's DS1307functions code:

Code: Select all

private strMonths as StringVectorData({
   "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" })

public Function MonthName(byval n as byte) as String
    MonthName = iif&#40;&#40;n>0 and n<13&#41;, strMonths&#40;n&#41;, "?"&#41;
end function

sub main&#40;&#41;
    dim i as byte
    for i= 0 to 14
        debug.print &#40;n>0 and n<13&#41;; " ";
        debug.print MonthName&#40;i&#41;
    next
end sub
which yields:
?
Jan
?
Mar
?
May
?
Jul
?
Sep
?
Nov
?
?

If the (n>0 and n<13) test is executed outside of IIf, however, the behavior is correct:

Code: Select all

private strMonths as StringVectorData&#40;&#123;
   "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" &#125;&#41;

public Function MonthName&#40;byval n as byte&#41; as String
    dim tf as boolean
    tf = &#40;n>0 and n<13&#41;
    MonthName = iif&#40;tf, strMonths&#40;n&#41;, "?"&#41;
end function

sub main&#40;&#41;
    dim i as byte
    for i= 0 to 14
        debug.print MonthName&#40;i&#41;
    next
end sub
yielding:
?
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
?
?

as expected.
Tom
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: IIf oddity

Post by dkinzer »

GTBecker wrote:With compiler v4.2.3 I find this odd behavior of IIf [...]
The issue has been confirmed and a correction is being developed. In the interim, one can get the correct behavior by introducing an intermediate variable thus:

Code: Select all

Public Function MonthName&#40;ByVal n as Byte&#41; as String
    Dim idxOK as Boolean = &#40;&#40;n>0&#41; and &#40;n<13&#41;&#41;
    MonthName = IIF&#40;idxOK, strMonths&#40;n&#41;, "?"&#41;
End Function
Another alternative is:

Code: Select all

Public Function MonthName&#40;ByVal n as Byte&#41; as String
    MonthName = IIF&#40;Not&#40;n<1&#41; and &#40;n<13&#41;, strMonths&#40;n&#41;, "?"&#41;
End Function
- Don Kinzer
Post Reply