简体   繁体   中英

Is it safe to equal compare DBL_MIN or DBL_MAX?

One of my functions returns a double and I'd like to indicate an error condition with an invalid value like for example DBL_MIN , DBL_MAX or -DBL_MAX .

#include <stdio.h>
#include <stdlib.h>
#include <float.h>

double foo_fail(void)
{
    /* some code that could fail */
    return DBL_MIN;
}

int main(void)
{
    double d = foo_fail();
    /* Is this comparison in any way safe, defined, portable? */
    if (d == DBL_MIN)
        puts("foo failed");

    return 0;
}

I know, that usually you shouldn't equal compare double values, as rounding errors and alike could occur, but in this case it's a constant (I think).

As far as the comparison itself goes, this should be fine.

You're potentially missing out on some optimisations this way, because the range of your results is not just the real values - but that shouldn't be a huge issue.

Suggestion if you can still change the interface: A more readable solution could be something like:

double result;
int err = foo_fail(&result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM