开发者

Check a float variable for existence

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 f开发者_高级运维ile, but in the C format.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜