为什么printf的处理一个float参数究竟处理了双参数以同样的方式? [英] How come printf handles a float argument exactly the same way it handles a double argument?

查看:146
本文介绍了为什么printf的处理一个float参数究竟处理了双参数以同样的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到最近,我认为:


  • 的printf(%FX)将试图读取从堆栈中一个4字节的浮点值。


  • 的printf(%LF,X)将试图读取从堆栈的8字节浮点值。


但是,下面的code的一块似乎产生正确的输出:

 浮动F = 1234.5;
双D = 12345678.9;
的printf(输出=%U%U \\ N的sizeof(F)的sizeof(d)条); //输出= 4 8
的printf(输出=%.1F%.1F \\ n,F,D); //输出= 1234.5 12345678.9

我认为这证明了的printf(%FX)读取从堆栈的8字节浮点值。

这是因为这两个值都打印正确,但12345678.9太大,放入一个4字节变量。

现在我的问题是:当调用的printf 用4个字节的浮动变量,编译器如何知道它应该将其转换为8字节双击值推入堆栈中并调用之前的printf

时,调用了带浮点参数的函数,当一个标准的一部分?

感谢


解决方案

  

编译器如何知道它应该推入堆栈中并调用的printf之前将其转换为8字节的双重价值?


它不必知道什么时候才能做到这一点 - 它总是;它的<一部分href=\"http://stackoverflow.com/questions/1255775/default-argument-promotions-in-c-function-calls\">default参数提升的。


  

时,调用了带浮点参数的函数,当一个标准的一部分?


没有,只是可变参数的。

Until very recently, I thought that:

  • printf("%f",x) would attempt to read a 4-byte floating-point value from the stack.

  • printf("%lf",x) would attempt to read an 8-byte floating-point value from the stack.

However, the following piece of code seems to yield the correct output:

float  f = 1234.5;
double d = 12345678.9;
printf("Output = %u %u\n",sizeof(f),sizeof(d)); // Output = 4 8
printf("Output = %.1f %.1f\n",f,d);             // Output = 1234.5 12345678.9

I believe that it proves that printf("%f",x) reads an 8-byte floating-point value from the stack.

This is because both values are printed correctly, yet 12345678.9 is too large to fit into a 4-byte variable.

Now my question is: when calling printf with a 4-byte float variable, how does the compiler know that it should cast it to an 8-byte double value before pushing it into the stack and calling printf?

Is that a part of the standard when calling functions that take floating-point arguments?

Thanks

解决方案

how does the compiler know that it should cast it to an 8-byte double value before pushing it into the stack and calling printf?

It doesn't have to know when to do it - it always does; it's part of the default argument promotions.

Is that a part of the standard when calling functions that take floating-point arguments?

No, just variadic ones.

这篇关于为什么printf的处理一个float参数究竟处理了双参数以同样的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆