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:
%ndoes not print anything. Another print statement is needed to print the value of the variable which has the count.
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
efor the count to be stored. - Line 6: We print the string and use
%nto count the characters before it and store them intoe. - Line 7: We print
eto show the count stored in it.