log(10.0) can compile but log(0.0) cannot with undefined reference?

前端 未结 2 2106
闹比i
闹比i 2020-12-01 13:49

For the following C source code:

#include 

int main(void)
{
    double          x;

    x = log(0.0);

    return 0;
}
2条回答
  •  -上瘾入骨i
    2020-12-01 14:08

    The compilation is alright, it's just the linker switch -lm that is missing.

    The second version probably compiles and links because gcc replaces log(10.0) with a constant, so no call to the math library is needed. In the second case, the result is mathematically undefined, and evaluation results in a domain error. In that case, the expression cannot be replaced by a constant, since handling of domain errors might be different at run-time.

    Quote from the C-standard (draft):

    On a domain error, the function returns an implementation-defined value; if the integer expression math_errhandling & MATH_ERRNO is nonzero, the integer expression errno acquires the value EDOM; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the ‘‘invalid’’ floating-point exception is raised.

    So evaluation of log(0.0) either results in returning the value HUGE_VAL (not NAN as I claimed before) or a floating point exception.

    EDIT: I corrected my answer based on the comments received and added link to the description in the C-standard.

提交回复
热议问题