Math interface vs cMath in C++

痞子三分冷 提交于 2019-11-27 22:24:01

In the C++ standard, the math library functions are defined in two headers:

<cmath>

contains them in the namespace std (e.g. std::sin), while

<math.h>

contains them in the global namespace (so just sin).

There are further differences between the two: while <math.h> contains all the C math functions with distinct names for distinct types, such as

double sin(double);
float sinf(float);
long double sinl(long double);

etc., <cmath> contains overloaded functions such as

namespace std {
    double sin(double);
    float sin(float);
    long double sin(long double);
}

etc. (C++ libraries might additionally export sinf from <cmath>, but you can't rely on this in a portable program.)

Finally, the fabs, fabsf and fabsl functions from the C standard library have become overloads of std::abs in <cmath>.

Though both headers are in the standard, you should really prefer <cmath>, as <math.h> is only there for backward compatibility with pre-standard C++ and C.

There's no such thing as <cmath.h> in standard C++.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!