printf() Write formatted output to stdout
printf() Write formatted output to stdout
printf() writes formatted output to stdout and returns the character count, excluding the null terminator. Type mismatches cause undefined behavior.
| Category | stdio.h I/O |
|---|---|
| Kind | Library function |
| Header | <stdio.h> |
| C standard | C89 / C90 |
📝 Syntax
int printf(const char *format, ...);
⚙️ Parameters
| format Required | A format string containing ordinary characters and conversion specifiers introduced by %. |
|---|---|
| ... Optional | Variable arguments matching the conversion specifiers in order and type. |
Returns: Returns the number of characters written, excluding the terminating null character, or a negative value if an output or encoding error occurs.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
n = 42
pi = 3.14
hex = 0x2a
⚠️ Warning Each conversion specifier must match the promoted argument type: for example, use %d for int and %f for double. A mismatch causes undefined behavior.
💡 Tip Use field width and precision to control layout: %5d sets a minimum width, %.2f prints two fractional digits, and %-10s left-aligns text.
🏷️ Related stdio.h functions
📚 Related Tutorials
❓ FAQ
QHow do I print a literal percent sign with printf?
AWrite %% in the format string. A single % introduces a conversion specifier.
QIs there a difference between %d and %i in printf, and what should I use for long?
AThey are equivalent for printf and both print an int. Use %ld for long and %lu for unsigned long. In scanf, %i additionally detects the integer base.
QHow can I tell whether printf succeeded?
ACheck the return value: a negative result indicates an output or encoding error, while a nonnegative result is the number of characters written, excluding the null terminator. For buffered streams, success here does not guarantee a later device write; critical file output should also check fflush() or fclose().