Output with printf()
printf(), declared in <stdio.h>, is the workhorse function for producing formatted output in C. It takes a format string describing what to print, followed by zero or more additional arguments whose values get substituted into placeholders (format specifiers) within that string.C
#include <stdio.h>
int main(void) {
int age = 25;
double price = 19.99;
char grade = 'A';
printf("Age: %d, Price: %.2f, Grade: %c\n", age, price, grade);
return 0;
}Format Specifiers
Each
%-prefixed placeholder in the format string (like %d, %f, %s, %c) must match the type of the corresponding argument. A full reference of the available specifiers lives on the Format Specifiers page — this page focuses on how printf itself works.printf Returns a Value
The return value is rarely used, but it exists
printf() returns an int: the number of characters successfully printed, or a negative value if an output error occurred. Most beginner code ignores this return value, but it is occasionally useful for error checking or for computing how much text was written.C
int charsPrinted = printf("Hello, World!\n");
printf("That printed %d characters\n", charsPrinted); // 14 (includes the newline)Format-String Mismatches Are Undefined Behavior
The types must match — the compiler usually cannot fully check this
printf is a variadic function: it has no way of knowing at runtime how many arguments were actually passed or what their real types are. It trusts the format string completely. If you write %d but pass a double, or you provide fewer arguments than the format string expects, the behavior is undefined — it may print garbage, crash, or appear to work by coincidence. Modern GCC/Clang can catch many of these mistakes at compile time with -Wall -Wformat, but the language itself does not enforce it.C
double price = 9.99;
printf("%d\n", price); // UNDEFINED BEHAVIOR: %d expects an int, not a double
/* Correct */
printf("%f\n", price);Printing a Literal Percent Sign
Since
% introduces a format specifier, printing a literal percent character requires doubling it: %%.C
printf("Discount: 20%%\n"); // prints: Discount: 20%printf(format, ...)substitutes arguments into%-prefixed placeholders in the format stringIt returns the number of characters printed (or negative on error) — rarely checked, but available
Format specifiers must match argument types exactly; mismatches are undefined behavior
Compile with
-Wall -Wformatso the compiler flags obvious specifier/argument mismatchesUse
%%to print a literal%character