float
to double
in a math function CXX-P2001Calling math functions from the C libray that only accept double
with float
arguments causes an implicit type promotion of the float
argument. Type promoting float
to double
costs extra space in memory, it also costs extra instructions for the conversion from float
and lastly vectorisation of float
is a lot more efficient compared to double
.
To fix this issue, use the math functions from the standard namespace that provide overloaded interfaces to accept float
directly. In case you are using pure C, you should use the f
suffixed math functions, to use the float
accepting API. Eg, sinf
, cosf
, etc. And in case you still want to use doubles, you should consider making the cast to double
explicit or ensure that the passed argument is a double
by default.
double acos(double);
double log(double);
double cosh(double);
void foo(float a) {
acos(a);
log(a);
cosh(a);
}
#include <cmath>
void foo(float a) {
/// sample using explicit cast to `double`
acos((double)a);
log((double)a);
cosh((double)a);
}
void bar(double a) {
/// sample using variable of tyoe `double`
acos(a);
log(a);
cosh(a);
}
void baz(float a) {
/// sample using standard method with support for type `float`
std::acos(a);
std::log(a);
std::cosh(a);
}
void car(float a) {
/// sample using C function with support for type `float`
acosf(a);
logf(a);
coshf(a);
}