When do C and C ++ compilers convert or promote floats to double, implicitly?
For an embedded project, I would like to know when a C ++ compliant compiler (C99) and a standards compliant C ++ compiler (C ++ 11) is likely to implicitly push a single-float variable / value into a double-float ...
I know of two cases:
- literals that do not have a suffix
f
. For example:3.14
- passing float to work with variable list argument (
...
)
Are there others? How about templates?
The answers to this question are very helpful to me, including it here for reference.
source to share
In C:
Numeric literal with .
and without suffix for example. 3.14
does not include any promotions. This is double
for the entire lifetime.
The float is promoted to double if float is an argument to a function call and the called function has no prototype in scope, or the argument matches an ellipsis ( ...
) in prototype in scope.
The float transforms to double in any of the following situations:
- The float is an argument to a function call corresponding to the type parameter
double
in the prototype in scope. - Binary operator has
double
andfloat
how two types of arguments. These operators include:* / + - < > <= >= == !=
- The conditional operator has
double
bothfloat
as second and third operands (in any order) - The float is added to
double
- Float assignment
double
(including compound assignment)
In C ++, all of the above cases still apply, except in cases without a prototype (since C ++ requires all function calls to have an in-scope prototype).
There is a new case: a standard conversion funnel that is too complex to be summarized. But as an example, this C ++ code contains an implicit conversion from float
to double
:
class T { public: T(double dummy) {} };
void foo(T);
foo(3.14f); // Conversion sequence: float->double->T
I'm not sure if this is an exhaustive list for C ++.
source to share