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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With