Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ NaN or boolean?

Tags:

c++

fpu

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?

like image 539
Severin Pappadeux Avatar asked Sep 24 '15 19:09

Severin Pappadeux


People also ask

Is 0 true or false in C?

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

Is boolean NaN true?

The boolean value true if the given value is a number with value NaN . Otherwise, false .

How do I know if my float is NaN?

To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.

What type is NaN C++?

NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations.


1 Answers

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.

like image 131
YePhIcK Avatar answered Sep 16 '22 15:09

YePhIcK