Reputation: 7032
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?
Upvotes: 6
Views: 5019
Reputation: 11126
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"...
Upvotes: 16
Reputation: 125007
Instead of overloading these float
properties (let's call them X and Y), create a separate isValid
flag for each property. Initialize the flags to indicate that the floats haven't been set, and provide your own setters to manage the flags appropriately. So your code might look something like:
if (self.isXValid == YES) {
self.Y = ... // assigning to Y sets isYValid to YES
}
else if (self.isYValid == YES) {
self.X = ... // assigning to Y sets isXValid to YES
}
You could actually go a step further and have the setter for X also assign Y and vice versa. Or, if X and Y are so closely linked that you can calculate one based on the value of the other, you really only need one variable for both properties.
Upvotes: 2
Reputation: 7226
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.
Upvotes: 3