Tuesday, July 16, 2013

Format Specifiers in C

In C, we use the format specifiers in both the printf and scanf functions for specifying the type of the variable. Format specifiers are the part which we should be careful in using. We have to specify the exact format specifier for the data type we are using for the variable. If we don't use the appropriate one, it may result in the unexpected results.

The following table represents the most commonly needed format specifiers in C.


Specifier
Meaning
Types Converted
%c
Single character
char
%d, %i
Signed decimal integer
int, short
%ld
Signed long decimal integer
long
%f, %e, %E, %g, %G
Decimal floating-point number
float, double
%s
Character String
Char arrays
%u
Unsigned decimal integer
unsigned int, unsigned short
%lu
Unsigned long decimal integer
unsigned long

All these are the generally used format specifiers in C. 

What is the difference between %d and %i?

Both %d and %i are same when used in the output function. But if we use them for taking input, then %d takes only signed integer values where as, %i also takes octal and hexadecimal numbers, if we specify "0" and "0x" respectively before the number.

What is the difference between %f, %e and %g?

All the three are used for representing the floating point numbers. But the difference lies with the way they represent the values.
  • %f prints a value 3.4 as 3.400000
  • %g prints it as 3.4
  • %e prints the value as 3.400000E+00
I hope you understood the difference well. If you have any doubts, feel free to contact me.