C / C ++ NaN or boolean?

I need to store one double value in the cache. After using it, it must be invalid. Two alternatives

One of them is to add the boolean flag true , when the cached value is good, when it is used, set it to false , and when the flag is false, recalculate and replenish.

The second is more interesting - I could save it as a double value and use NaN as invalid / should have the recalc flag.

 double get() const { if (!isnan(_value)) { double t = _value; _value = std::numeric_limits<double>::quiet_NaN; return t; } } 

Any objections to him? Any thoughts on effectiveness?

+6
source share
3 answers

use a boolean, otherwise you will encounter some interesting problems / errors on the road when your calculated double will actually turn out to be NaN (due to calculation). If you rely on NaN as a signal for "I used this value," then you cannot tell if the "real" unused NaN is.

Not to mention that such an overload of semantics will cause the future reader of your code (even after a few months) to scratch his head in attempts to decipher this clever use .; -)

In general, it is bad practice to overload the value of a variable. At first this may seem pretty, but it will inevitably cause more harm in the future.

As for efficiency - I would recommend the first measure to you and only then worry about optimization. I bet that after running the tests you will find that the difference in speed is significantly lower than the performance noise caused by fluctuations in processor temperature.

+6
source

I doubt there will be a difference with performance, but code with a boolean flag will be more readable:

 double get() const { if (!_cached) _value = recalculate(); _cached = !_cached; return _value; } 
+3
source

I believe it is worth noting that nan may be a more efficient solution, the big advantage is that you use less memory than with a flag (whose markup is likely to be more than 1 byte per double, due to alignment). This means that it is also more likely to be faster if you need to read a lot of memory.

Another thing to keep in mind is that IEEE nans can have different meanings. Their exponents should be all, but the mantissa can be anything but all zeros. This means that you can use a "special" nan to distinguish from those obtained by the calculation, or even use different types of nans if you need a flag with more than two states.

0
source

All Articles