Search code examples
c++fpu

C/C++ NaN or boolean?


I have to keep one double value cached. After it is used, it should be invalidated. Two alternatives

One is to add boolean flag, true when cached value is good, when it is used set it to false, and when flag is false, recalculate and refill.

Second one is more interesting - I could keep it as double value and use NaN as invalid/need to recalc flag.

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

Any objections against it? Any thoughts on efficiency?


Solution

  • use the boolean otherwise you'll end up with some interesting problems/bugs down the road when your calculated double actually turns out to be a NaN (due to calculation). If you rely on NaN as a signal for "I have used that value" then you won't be able to distinguish in case of a "valid" unused NaN.

    Not to mention that such semantics overload will cause a future reader of your code (even yourself a few month from now) to scratch his head in attempts to decipher that clever use. ;-)

    In general it is a bad practice to overload the meaning of a variable. It may seem cute at first but it will inevitably cause more harm down the road.

    As far as efficiency goes - I would really recommend you first measure and only then worry about optimization. I will bet you that once you run the tests you'll find that the difference in speed is well below the performance noise caused by the CPU temperature fluctuations.