When do C and C++-compilers convert or promote a float to double, implicitly?

不羁的心 提交于 2019-12-03 17:18:29
M.M

In C:

A numeric literal with . and no suffix, e.g. 3.14, does not involve any promotion. It is double for its entire lifetime.

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:

  • 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 and float as the two argument types. The operators this applies to are: * / + - < > <= >= == !=
  • The conditional operator has double and float 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)

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).

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

I'm not sure if this is an exhaustive list for C++ though.

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