Short answer
%d and %f are format specifiers. They are used with printf to say what kind of value goes into a spot in the output and how to show it. %d is for int values, and %f is for floating-point values such as double.
What a format specifier is
The first argument to printf is a format string. Anything that begins with % is a placeholder. The letter after the % says what type of value to expect, and the value that fills the placeholder comes from the arguments after the string:
#include <stdio.h>
int main(void) {
int count = 42;
printf("There are %d items.\n", count); // There are 42 items.
return 0;
}
What %d means
%d prints a signed decimal integer, which means an int. %i works the same way in printf.
A char passed to %d prints its numeric code. The char is promoted to int when it is passed to a variadic function like printf, so printf("%d", 'A'); prints 65 on an ASCII system. The difference between a character and its code is covered in c char to int.
What %f means
%f prints a floating-point number in decimal notation. By default it shows six digits after the decimal point:
#include <stdio.h>
int main(void) {
double price = 3.5;
printf("%f\n", price); // 3.500000
printf("%.2f\n", price); // 3.50
return 0;
}
The .2 sets the precision, so only two digits follow the decimal point. A float passed to printf is promoted to double, so %f also works for float values there.
Reading input with %d and %f
scanf uses the same letters, but it expects a pointer to the variable it should fill in. For a double, scanf needs %lf, not %f:
#include <stdio.h>
int main(void) {
int age;
double height;
scanf("%d", &age);
scanf("%lf", &height);
return 0;
}
Mistakes that cause wrong output
- Using
%dfor adouble.printf("%d", 3.5);does not print 3. The C standard leaves the result undefined. - Using
%finscanffor adouble. Use%lfso the value is stored in the fulldouble. - Leaving out the
&inscanf.scanf("%d", age);passes the value instead of an address, which is undefined behavior.
Compilers can catch many of these mistakes. Running gcc or clang with -Wall usually reports format codes that do not match their arguments.
Other common codes
%cprints a singlechar.%sprints a string, which is passed as acharpointer.%uprints anunsigned int.%xprints anunsigned intin hexadecimal.
The sizes and ranges of int and double are listed in primitive data types in c, which helps when you choose a format code.