What is the use of %n in printf()?

CProgrammingServer Side Programming

In C language, %n is a special format specifier. It cause printf() to load the variable pointed by corresponding argument. The loading is done with a value which is equal to the number of characters printed by printf() before the occurrence of %n.

Note − It does not print anything. Another printf() function is used to print the statement.

Here is an example of %n in C language,

Example

 Live Demo

#include<stdio.h>
int main() {
   int s;
   printf("The value of %ns : ", &s);
   printf("%d", s);
   getchar();
   return 0;
}

Output

The value of s : 13

Even if we give the value to the identifier, it will not consider the value given by us. It counts the characters used before the use of %n in the statement. It will not count %n as a character.

Here is an example if we pass the value,

Example

 Live Demo

#include<stdio.h>
int main() {
   int s;
   int m = 28;
   int val;
   printf("The value of %ns and %nm %nval : ", &s, &m, &val);
   printf("%d\t%d\t%d", s, m, val);
   return 0;
}

Output

The value of s and m val : 131921
raja
Published on 08-Oct-2018 09:57:13
Advertisements