Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I distinguish between an unset float and one with a value of 0?

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?

like image 833
Nathan Avatar asked Apr 17 '12 02:04

Nathan


2 Answers

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

like image 57
gha.st Avatar answered Sep 21 '22 21:09

gha.st


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.

like image 33
Cowirrie Avatar answered Sep 18 '22 21:09

Cowirrie