~/C Printf Essential Tips and Tricks

Sep 14, 2021


Use printf for formatted output in C. Here are concise practical tips:

Format Specifiers
Use %d for integers, %f for floats, %s for strings. To print a literal percent sign, use %%.

Field Width and Precision
Set width or precision by numbers in the specifier, like %6d for six spaces or %.2f for two decimals.

Code example:

1
printf("%6d %.2f\n", 42, 3.14159);

Output:

1
    42 3.14

Print Hex and Octal
Use %x or %X for hex and %o for octal (see format specifiers).

Code example:

1
printf("Hex: %x, Octal: %o\n", 255, 255);

Align Output
Use - for left alignment: %-10s will left align a string in 10 characters.

Printing Pointers
Use %p for addresses.

1
2
int x = 5;
printf("%p\n", (void *)&x);

Print Leading Zeros
Use 0 before width for leading zeros, e.g. %05d prints 00042.

Multiple Variables
You can print values in order by passing multiple arguments:

1
printf("x=%d, y=%.1f\n", 7, 2.7);

Important
Always match format specifiers to argument types to avoid bugs or undefined behavior.

For more details, check the C documentation.

Tags: [c] [printf] [programming]