How can I distinguish between non-fixed float and one with value 0?

I have a method that should do another thing when an erratic float is given than a float with a value of 0. Basically, I need to check if the variable was considered to be set if it has a value of 0.

So, which placeholder should be used as an undefined value (nil, NULL, NO, etc.) and how can I check if a variable is reset without returning true for value 0?

+6
source share
3 answers

You can initialize your floats to NaN (for example, by calling nan() or nanf() ), and then check isnan() if they were changed to save the number. (Note that testing myvalue == nan() will not work.)

It's pretty simple (you might include math.h anyway) and conceptually reasonable: any value that is not set to a number is not a "number" ...

+16
source

Using a constant value to indicate cancellation status often leads to errors when a variable legitimately receives the value of this constant.

Consider using NSNumber to store your float. Thus, it can be not only nil , it will be by default for this state.

This suggests that you only need a small number of floats. If you need millions, NSNumber can be too slow and memory intensive.

+3
source

Instead of overloading these float properties (call them X and Y), create a separate isValid flag for each property. Initialize the flags to indicate that the floats have not been set, and to provide their own setters with the proper control of the flags. So your code might look something like this:

 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 } 

In fact, you can take another step, and the setter for X also assign Y and vice versa. Or, if X and Y are so closely related that you can calculate them based on the value of another, you really only need one variable for both properties.

+2
source

Source: https://habr.com/ru/post/913381/


All Articles