C/C++ NaN constant (literal)?

后端 未结 5 868
孤独总比滥情好
孤独总比滥情好 2020-11-29 21:20

Is this possible to assign a NaN to a double or float in C/C++? Like in JavaScript you do: a = NaN. So later you can chec

5条回答
  •  抹茶落季
    2020-11-29 21:47

    Is this possible to assign a NaN to a double or float in C ...?

    Yes, since C99, (C++11) offers the below functions:

    #include 
    double nan(const char *tagp);
    float nanf(const char *tagp);
    long double nanl(const char *tagp);
    

    which are like their strtod("NAN(n-char-sequence)",0) counterparts and NAN for assignments.

    // Sample C code
    uint64_t u64;
    double x;
    x = nan("0x12345");
    memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
    x = -strtod("NAN(6789A)",0);
    memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
    x = NAN;
    memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
    

    Sample output: (Implementation dependent)

    (7ff8000000012345)
    (fff000000006789a)
    (7ff8000000000000)
    

提交回复
热议问题