[英]printf(): When is %n written?
Consider the following code: 请考虑以下代码:
#include <stdio.h>
int main() {
int i = 0;
printf("hello%n%d\n", &i, i);
}
Why does it print hello0
and not hello5
? 为什么打印
hello0
而不是hello5
?
When you call a function, the function arguments are copied into the scope of the called function. 调用函数时,函数参数将复制到被调用函数的范围内。 Since
i
is 0
, the value 0
is copied into the scope of printf
and used to print in the %d
conversion. 由于
i
为0
,因此将值0
复制到printf
的范围内并用于在%d
转换中进行打印。
Additionally, the value &i
is copied into the scope of the function, and the function uses that value to populate the variable at that address with the number of output bytes so far. 此外,值
&i
被复制到函数的范围内,并且函数使用该值来填充该地址处的变量以及到目前为止的输出字节数。 So after your function call returns, you can inspect i
to find that value. 因此,在函数调用返回后,您可以检查
i
以查找该值。
The fact that you used the same variable to both produce a value for the %d
argument and to produce an address for the %n
argument is pure coincidence. 您使用相同的变量既为
%d
参数生成值又为%n
参数生成地址这一事实纯属巧合。 In fact, the last i
argument is really a bit misleading, since it is not the identity of i
that matters here, but only its value . 事实上,过去的
i
的说法实在是有点误导,因为它不是身份i
是这里的问题,但只有它的价值 。 You might as well have put a literal 0
there. 你可能会在那里放一个字面值
0
。 (Technically, the expression i
undergoes "lvalue conversion", which is just a fancy way of saying that you don't care about the variable, only the value.) (从技术上讲,表达式
i
经历了“左值转换”,这只是一种说法,你不关心变量,只关注价值。)
%n is not written. %n未写入。 It means "nothing printed."
这意味着“什么都不打印”。
From the fine manual : 从精细手册 :
Nothing printed.
The corresponding argument must be a pointer to a signed int.
The number of characters written so far is stored in the pointed location.
In other words, after printf returns, i
will contain the value 5. But not until printf returns - that is why you're seeing 0 instead of 5. 换句话说,在printf返回之后,
i
将包含值5.但是直到printf返回 - 这就是为什么你看到0而不是5。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.