简体   繁体   English

printf和co如何区分float和double

[英]How does printf and co differentiate between float and double

Since it isn't strongly typed I thought it just picked the right memory size and interpreted it based on the type of argument. 由于它没有强类型,我认为它只是选择了正确的内存大小并根据参数的类型对其进行解释。 But float and double both use %f and they are different sizes. 但是float和double都使用%f,它们的大小不同。

PS I can see how promotion via copying the value to a temp and casting(is this right?) might work but how does it work for scanfs/sscanf? PS我可以看到如何通过将值复制到临时和转换(这是正确的吗?)可以起作用,但是它对scanfs / sscanf有什么作用?

It doesn't differentiate. 它没有区别。 It's not possible to receive a float as a vararg: any float argument that you provide is first promoted to double . 不可能将float作为vararg接收:您提供的任何float参数首先被提升为double

6.5.2.2/6 defines "default argument promotions", and /7 states that default argument promotions are applied to "trailing arguments", that is varargs denoted by ... . 6.5.2.2/6定义了“默认参数提升”,而/ 7表示默认参数提升应用于“尾随参数”,即由...表示的变量。

how does it work for scanfs/sscanf? 它对scanfs / sscanf有什么用?

The %f format for scanf requires a pointer to float . scanf%f格式需要指向float的指针。 %lf requires a pointer to double , %Lf requires a pointer to long double . %lf需要一个指向double的指针, %Lf需要一个指向long double的指针。

copying the value to a temp and casting(is this right?) 将值复制到temp和cast(这是对的吗?)

If you provide a float argument, then the implementation creates a temporary of type double, initializes it with the float value, and passes this as the vararg. 如果你提供一个float参数,那么实现会创建一个double类型的临时函数,用float值初始化它,并将其作为vararg传递。 Casting by definition is explicit conversion by use of the cast operator -- you can cast if you like in order to make it exactly clear to the reader what's going on, but float f = 3; printf("%f", f); 按定义进行的转换是通过使用强制转换操作符进行显式转换 - 如果您愿意,可以进行强制转换,以便让读者清楚地知道发生了什么,但是float f = 3; printf("%f", f); float f = 3; printf("%f", f); is exactly the same as float f = 3; printf("%f", (double)f); float f = 3; printf("%f", (double)f);完全相同float f = 3; printf("%f", (double)f); float f = 3; printf("%f", (double)f); . The default argument promotion has the same meaning as the cast. 默认参数提升与强制转换具有相同的含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM