Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized float (C++)

If you want to initialize a float with an "uninitialized" state what value would you choose? (value easily testable and the least likely to be confused with an actual value)

float min=-999999.;

could have problems potentially either being confused with an actual value or even being tested due to fuzzy float roundings (and it looks naive :-)

like image 516
tru7 Avatar asked Dec 01 '22 01:12

tru7


2 Answers

If you want to avoid using valid values of float, you could use a NAN:

#include <limits>

....
float min = std::numeric_limits<float>::quiet_NaN();

You can then use std::isnan to check:

#include <cmath>

....
bool not_cool = std::isnan(min);
like image 150
juanchopanza Avatar answered Dec 05 '22 09:12

juanchopanza


You can use NAN. However

The problem was the use of an uninitialized floating point variable. Unlike integers, not all bit patterns are valid for use as floating point values. There is a category of values known as signaling NaNs, or SNaN for short, which are special "not a number" values. If you ask the processor to, it will keep an eye out for these signaling NaNs and raise an "invalid operand" exception when one is encountered. (This, after all, is the whole reason why it's called a signaling NaN.)

Also I would suggest you to use Boost.Optional like this:

boost::optional<float> minValue;  // initially unset
like image 34
Rahul Tripathi Avatar answered Dec 05 '22 11:12

Rahul Tripathi