I have a method that needs to do a different thing when given an unset float than a float with the value of 0. Basically, I need to check whether or not a variable has been, counting it as set if it has a value of 0.
So, what placeholder should I use as an unset value (nil, NULL, NO, etc) and how can test to see if a variable is unset without returning true for a value of 0?
You can initialize your floats to NaN (e.g. by calling nan()
or nanf()
) and then test with isnan()
if they have been changed to hold a number. (Note that testing myvalue == nan()
will not work.)
This is both rather simple (you will probably include math.h
in any case) and conceptually sensible: Any value that is not set to a number is "not a number"...
Using a constant value to indicate the unset state often leads to errors when the variable legitimately obtains the value of that constant.
Consider using NSNumber
to store your float. That way it can not only be nil
, it will default to that state.
This assumes that you only need a small number of floats. If you need millions of them, NSNumber
may be too slow and memory-intensive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With