Jeff Abrahamson on 18 Aug 2004 15:09:02 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] Re: How to specify NaN in C programs?


On Wed, Aug 18, 2004 at 10:17:18AM -0400, Walt Mankowski wrote:
>   [21 lines, 152 words, 777 characters]  Top characters: etinosdh
> 
> On Wed, Aug 18, 2004 at 07:55:50AM -0400, Jeff Abrahamson wrote:
> > And if you want to stay compatible with C, you can always set it by
> > dividing by zero:
> > 
> >     float f = 0.0 / 0.0;
> > 
> > You may have to fiddle with signals to avoid faulting, but I've
> > certainly done this by accident. ;-)
> 
> Now you see, this highlights the inherent problems in doing this kind
> of coding.  In theory, my function should only return values between 0
> and 1, so I should be fine just setting it to -1 to mean "no value".
> But I'm trying to be defensive, so I set it to NaN instead.  But what
> if the code's broken and actually *does* divide by 0?
> 
> Sigh.
> 
> Since both events are unlikely, and since using NaN is causing me some
> headaches, I'm thinking I'm better off just using -1 as a flag.

If you really want to be safe, you have to give up some performance
(but not much) and add some complexity (but not much):

    typedef struct myfloat {
        float val;
        bool ok;
    } MyFloat;

With C++ overrides, this can behave syntactically like a float.

-- 
 Jeff

 Jeff Abrahamson  <http://www.purple.com/jeff/>    +1 215/837-2287
 GPG fingerprint: 1A1A BA95 D082 A558 A276  63C6 16BF 8C4C 0D1D AE4B

 A cool book of games, highly worth checking out:
 http://www.amazon.com/exec/obidos/ASIN/1931686963/purple-20

Attachment: signature.asc
Description: Digital signature