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

Overview

%n is a format specifier used in printf() statement of the c language. It assigns a variable the count of the number of characters used in the print statement before the occurrence of %n.

Note: %n does not print anything. Another print statement is needed to print the value of the variable which has the count.

Explains the use of %n

Example

In the example below, the %n is used to count the characters. The word Learning is not counted as it is placed after %n. However, the characters placed before %n are counted, and a count of 14 is then stored in e and returned through the next printf() statement.

#include<stdio.h>
int main()
{
int e;
printf("Educative for %nLearning ", &e);
printf("\nCount: %d", e);
return 0;
}

Explanation

  • Line 5: We declare an integer e for the count to be stored.
  • Line 6: We print the string and use %n to count the characters before it and store them into e.
  • Line 7: We print e to show the count stored in it.