c++ - NaN or false as double precision return value -


i have function returns double value. in cases result zero, , results should handled in caller routing accordingly. wondering proper way of returning 0 (nan, false, etc!) in place of double value number:

double foo(){     if (some_conditions) {         return result_of_calculations;     } else {         // of following better?         return std::numeric_limits<double>::quiet_nan(); // (1)         return 0;                                        // (2)         return false;                                    // (3)         return (int) 0;                                  // (4)     } } 

the caller routine so:

double bar = foo(); if (bar == 0) {     // handle 0 case  } else {     // handle non-zero case  } 

is if (bar == 0) safe use #3 , #4? can use #2 or should fabs(bar - 0) < epsilon?

how should 1 handle case of quiet_nan? read in site (e.g. 1, 2) comparison of nan not necessary false. that?

in summary, how 1 returns false value in place of double later comparison?

you should not mix actual value function computes additional message further describes result, i.e. error state.


good ways are:

  1. a custom result struct

    struct foo_result_t {     double value;     bool state; };  foo_result_t foo() {     foo_result_t r;     r.value = result_of_calculations;     r.state = some_conditions;     return r; } 

    this perhaps best way , extendable if need more information function. indicating why failed.

    for simple cases, can consider using std::pair<double,bool>.

    you use boost::optional (link).

  2. the c++ exception way

    double foo() {     if(some_conditions) {         return result_of_calculations;     }     else {         throw some_exception;     } } 

    this looks , elegant, might want keep code exception free.

  3. the old-school c-style way:

    bool foo(double& result) {     if(some_conditions) {         result = result_of_calculations;         return true;     }     else {         return false;     } } 

    this perhaps direct 1 , has no overhead (exceptions, additional struct). looks bit strange function tries return 2 values, 1 of them argument.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -