C Format Specifiers
In this page:
What are Format Specifiers?
A format specifier is a placeholder inside printf or scanf's format string that tells the function what data type to expect at that position -- getting it wrong doesn't always crash your program, but it will corrupt or misread the value.
Example: What are Format Specifiers?
#include <stdio.h>
int main() {
int age = 25;
printf("%d", age);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Specifiers for Integers (%d and %i)
%d and %i both format a signed base-10 integer and are interchangeable in printf, though %i is slightly more common in scanf conventions -- either way, the value must actually be an int-sized integer, not a float or a long.
Example: Specifiers for Integers (%d and %i)
#include <stdio.h>
int main() {
int a = 5;
printf("%d %i", a, a);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Specifiers for Decimals (%f and %lf)
%f prints or reads a float, while %lf is required specifically when reading a double with scanf (printf accepts either interchangeably for doubles due to how C promotes float arguments) -- mixing these up with scanf will corrupt your data.
Example: Specifiers for Decimals (%f and %lf)
#include <stdio.h>
int main() {
double price;
sscanf("19.99", "%lf", &price);
printf("%f", price);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Specifiers for Text (%c and %s)
%c reads or prints exactly one character, while %s handles a whole string (a null-terminated array of characters) -- using %c where you meant %s will only capture the first letter and leave the rest of the input unread.
Example: Specifiers for Text (%c and %s)
#include <stdio.h>
int main() {
char letter = 'A';
char word[] = "Hello";
printf("%c %s", letter, word);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Specifiers for Addresses (%p)
%p formats a pointer's value as its raw memory address, typically shown in hexadecimal -- useful mainly for debugging, to confirm where a variable actually lives in memory or that two pointers reference the same location.
Example: Specifiers for Addresses (%p)
#include <stdio.h>
int main() {
int x = 5;
printf("%p", (void*)&x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: