C Format Specifiers

Beginner
6 min read
Updated: Nov 2026
1 example

What Is Format Specifiers?

A format specifier starts with % and tells printf/scanf the type of the matching argument. Flags, width, and precision fine-tune the output, for example %5d, %08.3f, or %-10s.

Remember
%d  int          %u  unsigned     %ld long
%f  double       %c  char         %s  string
%x  hex          %p  pointer      %zu size_t
%%  a literal percent sign

Cheat Sheet

Keep these facts handy while you work with Format Specifiers in C.

TopicDetail
Width%5d pads to at least 5 characters
Precision%.2f two decimals; %.3s first 3 chars
Left align%-8s pads on the right
Zero pad%05d prints 00042

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Escape Sequences.

Example 1 — Formatting a small report

Width, precision, and flags produce aligned columns.

C
#include <stdio.h>

int main(void) {
    printf("%-8s|%6s\n", "Item", "Price");
    printf("%-8s|%6.2f\n", "Pen", 1.5);
    printf("%-8s|%6.2f\n", "Notebook", 12.0);
    printf("id=%05d hex=%x char=%c\n", 42, 255, 'Z');
    printf("100%%\n");
    return 0;
}

How It Works

  1. %-8s left-aligns a string in 8 columns.
  2. %6.2f uses width 6 and 2 decimals.
  3. %05d pads with zeros; %x prints hexadecimal.
  4. %% prints one percent sign.

Edge Cases & Pitfalls

Check these before relying on Format Specifiers in real programs.

type

Mismatched type

printf("%d", 3.5) is undefined behavior. Enable -Wall so GCC flags mismatches.

f/lf

%f versus %lf

In printf both mean double, but scanf needs %lf for double and %f for float.

Key Takeaways

  • Match: specifier must fit the argument type.
  • Format: width, precision, and flags control layout.
  • Escape: write %% for a percent sign.

One line: A format specifier starts with % and tells printf/scanf the type of the matching argument.

Frequently Asked Questions

Use %zu. It is portable on 32-bit and 64-bit systems, unlike %lu or %d.
Cast to void * and use %p: printf("%p", (void *)ptr).
Continue with "C Escape Sequences" next. Backslash codes for newlines, tabs, quotes, and special characters. The C Fundamentals hub lists every topic in order.

Next: Escape Sequences

Backslash codes for newlines, tabs, quotes, and special characters.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful