I have a function that returns a double value. In some cases the result is zero, and this results should be handled in the caller routing accordingly. I was wondering what is the proper way of returning zero (NaN, false, etc!) in place of double value number:
double foo(){
if (some_conditions) {
return result_of_calculations;
} else {
// Which of the following is better?
return std::numeric_limits<double>::quiet_NaN(); // (1)
return 0; // (2)
return false; // (3)
return (int) 0; // (4)
}
}
The caller routine is something like so:
double bar = foo();
if (bar == 0) {
// handle the zero case
} else {
// handle the non-zero case
}
Is if (bar == 0)
safe to use with #3 and #4? Can I use it with #2 or I should do something like fabs(bar - 0) < EPSILON
?
How should one handle the case of quiet_NaN
? I read in this site (e.g. 1, 2) that comparison of NaN is not necessary always false. What to do with that?
In summary, how would one returns a false value in place of a double for later comparison?
boost
however, I'm afraid is not possible. I'm seeking for a pure c++ approach. – Stine