C++ 函数调用中的自动转换和提升

Automatic conversions and promotions in function calls in C++

如何了解函数调用中的转化促销

从我之前的 关于为什么有些函数被调用而其他函数也可以被调用,我想强调三个关键字:conversions,促销,绝配.

Numeric conversions: Unlike the promotions, numeric conversions may change the values, with potential loss of precision.

Numeric promotions: a conversion from a smaller type to a larger same type (E.g char to int), but without any loss of content

不那么简单的部分来了。 我希望有人能解释一下你在分析函数参数时需要思考的方式针对调用的不同情况:

我想实际看一些例子,因为对于初学者来说,cpp中的参考文献并不容易理解。

拥有:

int fun(double a)

调用 float x 使其成为浮点提升,这是因为 double 将始终与 float 相同或更大,这意味着我们的参数a 将始终能够保存我们通过 float 传递给它的数据,不会发生数据丢失,因此这是一种提升。


但是,有:

int fun(float a)

使用 double x 调用会导致浮点转换,可能会丢失数据或可能发生 UB。正是因为这种情况与上述情况相反,我们的 double 可能持有无法在 float 中表示的值,这反过来可能会导致 UB。有关详细规则,请参阅 Floating-point conversions