/

C Conversion Specifiers and Modifiers: A Handy Reference

C Conversion Specifiers and Modifiers: A Handy Reference

In this blog post, we will provide a helpful reference for all the C conversion specifiers commonly used with functions like printf(), scanf(), and other I/O functions.

Specifier Meaning
%d / %i Signed decimal integer
%u Unsigned decimal integer
%c Unsigned char
%s String
%p Pointer in hexadecimal form
%o Unsigned octal integer
%x / %X Unsigned hexadecimal number
%e Floating point number in exponential format in e notation
%E Floating point number in exponential format in E notation
%f double number in decimal format
%g / %G double number in decimal format or exponential format, depending on the value

In addition to these specifiers, we have a set of modifiers.

Let’s start with the use of digits as modifiers. By using a digit between % and the format specifier, you can specify the minimum field width. For example, %3d will take up 3 spaces regardless of the number being printed.

The following code:

1
2
3
4
printf("%4d\n", 1);
printf("%4d\n", 12);
printf("%4d\n", 123);
printf("%4d\n", 1234);

will produce the following output:

1
2
3
4
  1
12
123
1234

If you put a dot before the digit, you are indicating the precision, which is the number of decimal digits. This applies to decimal numbers. For example:

1
2
3
4
printf("%4.2f\n", 1.0);
printf("%4.3e\n", 12.232432442);
printf("%4.1e\n", 12.232432442);
printf("%4.1f\n", 123.22);

will print:

1
2
3
4
1.00
1.223e+01
1.2e+01
123.2

In addition to digits, we also have three special letters: h, l, and L.

  • h, when used with integer numbers, indicates a short int (e.g., %hd) or a short unsigned int (e.g., %hu).
  • l, when used with integer numbers, indicates a long int (e.g., %ld) or a long unsigned int (e.g., %lu).
  • L, when used with floating point numbers, indicates a long double (e.g., %Lf).

tags: [“c programming”, “conversion specifiers”, “modifiers”, “printf”, “scanf”]