What a format specifier does
%d and %s are format specifiers. They are placeholders in a format string that tell printf what kind of value to print at that spot. The scanf family uses the same codes to read input. %d is for a signed integer, and %s is for a string.
A format string holds ordinary text plus placeholders that start with %. Each placeholder uses one argument that follows the format string, and the letter after the % says how to show that value:
#include <stdio.h>
int main(void) {
int age = 30;
printf("Age: %d\n", age);
return 0;
}
This prints Age: 30.
%d: signed integers
%d prints an int as a signed decimal number, so negative values show a minus sign. The argument must be an int. Passing a value of another type, such as a double, is undefined behavior.
%i does the same job as %d in printf. Other integer codes match other types: %u for unsigned int, %ld for long, and %zu for size_t.
%s: strings
%s prints a string. In C, a string is a character array or a char pointer that ends with a null character, '\0'. The argument is the address of the first character, and printf prints characters until it reaches the null:
#include <stdio.h>
int main(void) {
char name[] = "Ada";
printf("Hello, %s\n", name);
return 0;
}
This prints Hello, Ada. Passing an int to %s, or a pointer that does not lead to a null-terminated string, is undefined behavior. The usual results are garbage output or a crash.
Other common codes
| Specifier | Argument type |
|---|---|
%d or %i |
int |
%u |
unsigned int |
%ld |
long |
%zu |
size_t |
%f |
double (a float is promoted to double) |
%c |
char |
%s |
pointer to a null-terminated string |
%p |
pointer (void *) |
%% |
a literal percent sign |
Printing a sizeof result
The sizeof operator returns a size_t, so print it with %zu:
#include <stdio.h>
int main(void) {
printf("%zu\n", sizeof(int));
return 0;
}
On a system where int is 4 bytes, this prints 4. Using %d for a size_t is undefined behavior, and it can print the wrong number, so match the specifier to the type.
Common mistakes
- Using %d for a long or size_t value. Match the specifier to the type, such as
%ldor%zu. - Leaving out an argument. Each placeholder needs one argument after the format string, or the output is undefined.
- Forgetting the newline.
printfdoes not add\nfor you, so the next output runs on the same line.
In short
%d prints a signed int, and %s prints a null-terminated string. Use %zu for size_t values such as the result of sizeof, and always pass an argument whose type matches the placeholder.