TOC:
printf Format Specifiers
Specifier | Description | Example Output |
%d | Signed decimal integer | printf("%d", 42); // 42 |
%i | Signed decimal integer (same as %d) | printf("%i", 42); // 42 |
%u | Unsigned decimal integer | printf("%u", 42); // 42 |
%x | Unsigned hexadecimal integer (lowercase) | printf("%x", 42); // 2a |
%X | Unsigned hexadecimal integer (uppercase) | printf("%X", 42); // 2A |
%o | Unsigned octal integer | printf("%o", 42); // 52 |
%f | Decimal floating-point | printf("%f", 3.14159); // 3.141590 |
%e | Scientific notation (lowercase) | printf("%e", 314.159); // 3.141590e+02 |
%E | Scientific notation (uppercase) | printf("%E", 314.159); // 3.141590E+02 |
%g | Shortest representation (%f or %e) | printf("%g", 3.14); // 3.14 |
%G | Shortest representation (%f or %E) | printf("%G", 3.14); // 3.14 |
%c | Single character | printf("%c", 'A'); // A |
%s | String of characters | printf("%s", "Hello"); // Hello |
%p | Pointer address | printf("%p", ptr); // 0x7ffee4b78e0c |
%% | Literal % character | printf("%%"); // % |
Flags
Flag | Description | Example Output |
- | Left-justify within the given field width | printf("%-10d", 42); // '42 ' |
+ | Forces a sign (+ or -) for numbers | printf("%+d", 42); // +42 |
0 | Pad with leading zeros | printf("%05d", 42); // 00042 |
ㅤ | Print a space before positive numbers | printf("% d", 42); // 42 |
# | Alternate form (useful with o, x, X, f, etc.) | printf("%#x", 42); // 0x2a |
Width and Precision
Syntax | Description | Example Output |
%10d | Minimum width of 10 characters | printf("%10d", 42); // ' 42' |
%.2f | Precision for floating-point numbers (2 decimals) | printf("%.2f", 3.14159); // 3.14 |
%10.2f | Minimum width and precision | printf("%10.2f", 3.14159); // ' 3.14' |
Length Modifiers
Modifier | Description | Example Output |
h | Short integer | printf("%hd", (short)42); // 42 |
l | Long integer | printf("%ld", 42L); // 42 |
ll | Long long integer | printf("%lld", 42LL); // 42 |
z | Size type (for size_t) | printf("%zu", (size_t)42); // 42 |
L | Long double (for %Lf) | printf("%Lf", 3.14159L); // 3.141590 |