tags:

views:

66

answers:

1

I have to check a float variable to determine the existence of a particular variable. Ideally it should have been a bool value or at least an int. Because of interface constraints and legacy code I am not able to change the data type to bool. So if I've to make a check, can I directly do it as shown below in the sample code:

    void check(float f)
    {
        if (!f)
            printf ("Zero val!\n");
        else
            printf ("Value exists!\n");
    }

Would it be fool proof Or is there be a better way to do it, considering the fact how the value is stored in a float variable. Casting it to an short and checking is out of the game because : If the value is '1' it is stored as 0.9999998; casting it to a short would result in a '0' which is wrong.

P.S The code happens to be present in a Objective C file, but in the C format.

+1  A: 

What you have will work, with the slight caveat that it will detect both positive and negative zero as being zero values. That may or may not matter for your purposes. If you are running on a platform that doesn't have the default IEEE-754 behavior (like many embedded platforms), then denormals may also pass the !f check, depending on how your compiler handles it. This is probably not a problem for you, but it's something to be aware of.

If you must do this sort of thing in the future, it's probably a better idea to use "not a number" to indicate uninitialized float data, which you can then check for with either (f != f) or isnan(f).

Stephen Canon
Just curious. Is there a chance that a float value (1) be stored as 0.99999 or 1.00001 without any computation (like a division) involved?
voidone
No. 1 is exactly representable in any form, and will always be simply 1. However, 1.1 is *not* representable in floating point.
R..
@voidone: What **R..** said is correct; the value 1.0 is representable in all standard floating-point formats, and will not be rounded due to conversions between those formats or from integer formats.
Stephen Canon