printf()函数如何工作 [英] How printf() Function work

查看:101
本文介绍了printf()函数如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<conio.h>

int f1();
int f2();
void main()
{
clrscr();
 printf(" %dt %d", f1(), f2());
  getch();
}
int f1()
{
 printf("f1() enteredn ");
 return 4;
}

int f2()
{
 printf("  f2() enteredn ");
 return 5;
}</conio.h></stdio.h>




输出:
f2()entern f1()enterdn 4t 5

为什么输出像这样,为什么不像 fi()enterdn 4t f2()enterdn 5 比在这里如何模拟printf函数?




Out put:
f2() enteredn f1() enterdn 4t 5

Why the output is as like that, why not as fi() enterdn 4t f2() enterdn 5 Than how printf Function is simulated here ?

推荐答案

这与编译器生成评估函数参数列表的代码的方式有关.您刚刚发现main中的printf调用的参数列表是从右到左评估的.

这就是全部.

欢呼声,
This has to do with the way the compiler generates the code that evaluates the parameter lists of a function. You have just found out that the parameter list of your printf call in main is evaluated from right to left.

That''s all there is to it.

Cheers,


C标准(和C ++规范)对在其中评估功能参数的代码没有施加任何限制.结果,它是特定于实现的,并且可以随编译器的不同而变化.如果您考虑一下,RHS的评估是有一定意义的,因为可以将结果值以相反的顺序推入堆栈,因此LHS参数始终位于顶部-如果这样可以简化进入例程的代码情况.

因此,可以按照编译器想要的任何顺序计算出printf参数.不要依赖这种行为:绝对不能保证下一个Service Pack不会改变它! (话虽如此,它可能不会,但实际上,真的,不要这样做!)
The C standard (and the C++ specification) does not impose any restrictions on the roder in which function parameters are evaluated. As a result it is implementation specific, and can change from compiler to compiler. If you think about it, there is some sense in evaluation from the RHS, since the resulting values can be pushed onto the stack in reverse order so the LHS parameter is always at the top - simpler to code when you enter the routine if that is the case.

So, printf parameters can be worked out in any order the compiler wants. Do not rely on this behaviour: there is absolutely no guarantee that the next service pack will not change it! (Having said that, it probably won''t, but really, really, do not do it!)


因为首先调用了f2(这导致"f2()输入") ,然后是f1(现在您已经输入了"f2()f1()"),最后附加了最后一个输出,即您的数值.因此,调用以相反的顺序进行.
Because f2 is called first (this leads to "f2() enteredn "), then f1 (now you have "f2() enteredn f1() enteredn") and in the end the last output is appended which is your numeric values. So the calls are done in reverse order.


这篇关于printf()函数如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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