C和C ++编译器何时会隐式将float转换或提升为double? [英] When do C and C++-compilers convert or promote a float to double, implicitly?
问题描述
对于一个嵌入式项目,我想知道何时符合标准的C编译器(C99)和C ++编译器(C ++ 11)会隐式地将单浮点变量/值提升为两倍。
For an embedded project I'd like to know when does a standard-compliant C-compiler (C99) and C++-compiler (C++11) will most likely implicitly promote a single-float variable/value to double-float.
我知道两种情况:
- 后缀
f
。例如:3.14
- 传递浮点数以使用可变参数列表(
...
)
- literals which are not suffixed with
f
. For example:3.14
- passing a float to function with variadic argument-list (
...
)
还有其他吗?模板呢?
这个问题对我也非常有帮助-在此处包括以供参考。
The answers of this question are very helpful for me as well - including it here for reference.
推荐答案
在C中:
带有的数字文字。
,不带后缀,例如 3.14
,不涉及任何促销。整个生命周期都是翻倍
。
A numeric literal with .
and no suffix, e.g. 3.14
, does not involve any promotion. It is double
for its entire lifetime.
浮点数被提升,如果float是函数调用的参数,被调用的函数在范围内没有原型,或者该参数对应于原型中的省略号( ...
)
A float is promoted to double if the float is an argument to a function call, and the function being called has no prototype in scope, or the argument corresponds to the ellipsis (...
) in the prototype in scope.
在以下任何一种情况下,浮点数都会被转换以加倍:
A float is converted to double in any of the following situations:
- 浮点数是函数调用的参数,该函数调用与范围原型中的
double
类型的参数相对应。 - 二进制运算符具有
double
和float
作为两个参数类型。适用的运算符为:* / +-< > < => = ==!=
- 条件运算符具有
double
和float
作为第二个和第三个操作数(以任意顺序) - 浮点型强制转换为
double
- 浮点数已分配给
双人间
(包括复合分配)
- The float is an argument to a function call corresponding to a parameter of type
double
in a prototype in scope. - A binary operator has
double
andfloat
as the two argument types. The operators this applies to are:* / + - < > <= >= == !=
- The conditional operator has
double
andfloat
as the second and third operand (in either order) - The float is cast to
double
- The float is assigned to a
double
(including compound assignment)
在C ++中,除没有原型的情况外,以上所有情况仍然适用(因为C ++要求所有函数调用都必须有一个范围内的原型)。
In C++, all of the above cases still apply, except for the cases about no prototype (since C++ requires all function calls to have a prototype in scope).
有一个新情况:标准转换顺序,它太复杂了,以致无法简单总结。但例如,此C ++代码包含从 float
到 double
的隐式转换:
There is a new case: the standard conversion sequence which is too complicated to summarize briefly. 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
我不确定是否是C ++的详尽清单。
I'm not sure if this is an exhaustive list for C++ though.
这篇关于C和C ++编译器何时会隐式将float转换或提升为double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!