Chapter 18 · C Programming Series
Format Specifiers in C
A format specifier in C is a placeholder used within the format string of functions like 'printf', 'scanf', 'sprintf', and 'sscanf'. It specifies how a particular value should be formatted when it is inputted or outputted. Format specifiers begin with a percent sign ('%'') followed by a character that indicates the type of data to be processed.
What is format specifier ?
commonly used format specifier
| format specifier | description |
| %d or %i | Used for signed decimal integer. |
| %u | Used for unsigned decimal integer. |
| %o | Used for unsigned octal integer. |
| %x or %X | Used for unsigned hexadecimal integer |
| %f | Used for decimal floating-point number. |
| %e or %E | Used for scientific notation |
| %c | Used for a single character. |
| %s | Used for a string of characters |
| %p | Used for printing pointer addresses. |
| %% | Used to print a literal percent sign ('%'). |
Examples
C Code
#include<stdio.h>
int main()
{
int b=6;
int c=8;
printf("Value of b is:%d", b);
printf("\nValue of c is:%d",c);
}
Output
Value of b is:6
Value of c is:8
Value of b is:6
Value of c is:8
C Code
#include<stdio.h>
int main()
{
int a=9;
printf("Octal value of a is: %o", a);
printf("\nInteger value of a is: %d",a);
return 0;
}
Output
Octal value of a is: 11
Integer value of a is: 9
Octal value of a is: 11
Integer value of a is: 9
C Code
#include<stdio.h>
int main()
{
float y=3.4;
printf("Floating point value of y is: %f", y);
return 0;
}
Output
Floating point value of y is: 3.400000
Floating point value of y is: 3.400000
conclusion
Properly using format specifiers in C is fundamental to ensuring program correctness, reliability, and security. It helps prevent bugs, undefined behavior, and vulnerabilities that can arise from incorrect data interpretation. Always double-check and verify that the specifier matches the intended data type to avoid runtime issues in your programs.