Uninitialized float (C ++)

If you want to initialize a float with an “uninitialized” state, what value would you choose? (the value is easily verified and the least probable for confusion with the actual value)

float min = -999999 .;

there may be problems that could potentially be confused with the actual value or even verified due to fuzzy float rounding (and it looks naive :-)

+4
source share
3 answers

If you want to avoid using valid values float, you can use NAN:

#include <limits>

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

Then you can use std::isnanto check:

#include <cmath>

....
bool not_cool = std::isnan(min);
+12
source

NAN.

. , . , NaN, SNaN , " ". , NaN " ", . (, , , NaN.)

Boost.Optional :

boost::optional<float> minValue;  // initially unset
+5

Judging by the name of the variable min, you would like it to be as large as possible. Thus, any comparison with this value will be a lower value and will update yours minValue.

float minValue = std::numeric_limits<float>::max();

PS do not minname your variable or you run the risk of shading the name.

+3
source

All Articles