C Format Specifier
The format specifier is a way of telling the compiler what type of data to expect when displaying or reading input. In C language, a format specifier starts with a percentage sign %
, followed by a character that indicates the data type.
Syntax
printf(format, variables);
scanf(format, &variables);
Example
#include <stdio.h>
int main()
{
int i = 150;
float f = 12.3456;
char c = 'A';
printf("Value of i is %d\n", i);
printf("Value of f is %.2f\n", f);
printf("Value of c is %c\n", c);
return 0;
}
Output
The output of the above example will be:
Value of i is 150
Value of f is 12.35
Value of c is A
Explanation
The format specifier starts with a percent sign %
and is followed by a character that represents the format specifier. For example, %d
is used to display integer values, %f
is used to display floating-point values, and %c
is used to display characters.
Use
The use of format specifiers is mainly in input and output functions like printf
and scanf
to format the data that is being displayed or read in. By using format specifiers, the data being displayed or read in can be formatted to look a certain way, such as the number of decimal places displayed for a floating-point value.
Important Points
- If the data type of the variable does not match the format specifier, the output will not be what you expect.
- If the variable is of a type larger than what is expected by the format specifier used, undefined behavior may occur.
- The order of the format specifiers and variables in the argument list of
printf
orscanf
must match.
Summary
In summary, the format specifier allows for the formatting of input and output functions to display and read in data in a certain way. By using format specifiers, we can specify how data should be formatted, such as how many decimal places should be displayed for a floating-point value. It is important to use the correct specifier and to ensure that the data type matches the format specifier in order to avoid unexpected output or undefined behavior.