简体   繁体   中英

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 ?

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.

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. So after your function call returns, you can inspect i to find that value.

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. 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 . You might as well have put a literal 0 there. (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.)

%n is not written. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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