[英]How the printf function works in C programming?
I wrote this C program.我写了这个 C 程序。
#include<stdio.h>
int main()
{
int k=35;
printf("\n%d %d %d",k==35,k=50,k>40);
return 0;
}
and got this output.并得到了这个 output。
0 50 0 0 50 0
Now, I am thinking about how the printf function worked and why the output is 0 50 0.现在,我在思考 printf function 是如何工作的,以及为什么 output 是 0 50 0。
You are invoking undefined behavior by modifying k
and using its value in the same statement, before a sequence point.您通过在序列点之前修改k
并在同一语句中使用其值来调用未定义的行为。
While any output is legal and valid, it is possible to understand why 0 50 0
happens in this case:虽然任何output 都是合法有效的,但可以理解为什么在这种情况下会发生0 50 0
:
When a C function is called, its parameters can be evaluated in any order, but they are often evaluated in reverse order (right-most-first, left-most-last).当调用 C function 时,可以按任何顺序评估其参数,但它们通常以相反的顺序进行评估(最右边在前,最左边最后)。
This is not guaranteed, but is frequently true.这不能保证,但通常是正确的。
So the 4 parameters are evaluated as:因此,这 4 个参数被评估为:
1.) k>40
(false / 0
, because k
is 35) 1.) k>40
(false / 0
, 因为k
是 35)
2.) k=50
(assign 50 to k
, and evaluate to 50) 2.) k=50
(将 50 分配给k
,并评估为 50)
3.) k==35
(false / 0
, because k is 50, which is not 35) 3.) k==35
(false / 0
,因为 k 是 50,不是 35)
4.) "\n%d %d %d"
(string literal) 4.) "\n%d %d %d"
(字符串文字)
Then printf
prints its parameters: 0, 50, 0
然后printf
打印它的参数: 0, 50, 0
There are two problems here:这里有两个问题:
printf
) are evaluated.没有规则可以说明在 function 调用中(例如在调用printf
时)对 arguments 的哪个顺序进行评估。 It could be left-to-right, right-to-left, or some other order.它可以是从左到右、从右到左或其他顺序。k
( k = 50
) and use its value ( k == 35
, k > 40
), there's no rule to say whether the old or the new value is used.在这样的表达式中,您既修改了k
( k = 50
)又使用了它的值 ( k == 35
, k > 40
),没有规定是使用旧值还是新值。 (And this uncertainty persists regardless of the order of evaluation.) (无论评估顺序如何,这种不确定性都会持续存在。) Because of the second problem, this expression (this printf
call) is undefined .由于第二个问题,这个表达式(这个printf
调用)是undefined 。 It can do anything, even something wildly inexplicable.它可以做任何事情,甚至是一些非常莫名其妙的事情。
If you're calling printf
(or any function) on arguments which have "side effects" like this (that is, where an argument is something like k = 50
, which not only provides a value to pass to the function, but also makes some other change as well, in this case updating k
's value), you need to break things up so that the behavior becomes predictable.如果您在 arguments 上调用printf
(或任何函数),它具有像这样的“副作用”(也就是说,参数类似于k = 50
,它不仅提供了一个要传递给 ZC1C425268E18385D1ABZ507 的值,而且还使得还有其他一些变化,在这种情况下更新k
的值),您需要分解事物以便行为变得可预测。 In the case of printing several values, it's easy -- just use several, separate printf
calls:在打印多个值的情况下,这很容易——只需使用几个单独printf
调用:
printf("%d ", k == 35);
printf("%d ", k = 50);
printf("%d\n", k > 40);
Now the behavior is well-defined, and will probably be what you expected.现在行为已明确定义,并且可能是您所期望的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.