In C programming, a format specifier is a special code used to specify the type of data that will be printed or read using functions like printf() and scanf().
The format specifier tells the function how to interpret the data passed as an argument, and how to format it for output or input.
Some of the most common format specifiers in C:
Format Specifier | Data Type |
%d | int |
%ld | long int |
%lld | long long int |
%u | unsigned int |
%lu | unsigned long int |
%llu | unsigned long long int |
%f | float |
%lf | double |
%c | char |
%s | char array or string |
%p | pointer |
%x | hexadecimal int or unsigned int |
%o | octal int or unsigned int |
%% | prints a % character |
Format specifier in a printf() statement:
When using a format specifier in a printf() statement, the specifier is preceded by a percent sign (%), and followed by the variable or value to be printed.
For example, to print the value of an integer variable named “count”, you would use the format specifier %d as follows:
int count = 10;
printf("The value of count is %d\n", count);
This will print the message “The value of count is 10” to the console.
Format specifier in a scanf() statement:
Similarly, when using scanf() to read input from the user, the format specifier is used to indicate the type of data to be read.
For example, to read an integer value into a variable named “age”, you would use the format specifier %d as follows:
int age;
scanf("%d", &age);
This will prompt the user to enter an integer value, and store it in the variable “age”.
Note that the address-of operator (&) is used to pass the memory address of the variable to scanf().