gpt4 book ai didi

c++ - 为什么 printf() 将 float 提升为 double ?

转载 作者:太空狗 更新时间:2023-10-29 16:56:52 30 4
gpt4 key购买 nike

来自之前的question :

If you attempt to pass a float to printf, it'll be promoted to double before printf receives it

printf() 是可变参数函数吧?那么可变参数函数是否会在传递参数之前将 float 参数提升为 double

最佳答案

是的,可变参数函数的浮点参数被提升为 double 。

draft C99 standard 6.5.2.2 函数调用部分说:

[...]and arguments that have type float are promoted to double. These are called the default argument promotions.[...]

来自 draft C++ standard 5.2.2 函数调用部分:

[...]a floating point type that is subject to the floating point promotion (4.6), the value of the argument is converted to the promoted type before the call. [...]

4.6 部分:

A prvalue of type float can be converted to a prvalue of type double. The value is unchanged

cppreference覆盖 default conversions对于 C++ 中的可变参数函数:

  • std::nullptr_t is converted to void*
  • float arguments are converted to double as in floating-point promotion
  • bool, char, short, and unscoped enumerations are converted to int or wider integer types as in integer promotion

我们可以在 C 中看到,并且大概在 C++ 中,为了与 K&R C 兼容,此转换被保留,来自 Rationale for International Standard—Programming Languages—C (强调我的):

For compatibility with past practice, all argument promotions occur as described in K&R in the absence of a prototype declaration, including the not always desirable promotion of float to double.

关于c++ - 为什么 printf() 将 float 提升为 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41283762/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com