Format Specifiers and Escape Sequence in C

Posted on October 24, 2023 by Vishesh Namdev
Python C C++ Java
C Programming Language

Format specifiers in C are used to specify the data type of the value that you want to print or read using functions like printf and scanf. They provide a way to format and interpret the data correctly. Each format specifier corresponds to a specific data type.

Here's a table of commonly used format specifiers in C programming language:
Format Specifier Data Type
%d Integer
%i Integer (alternative)
%u Unsigned Integer
%ld Long Integer
%lu Long Unsigned Integer
%lld Long Long Integer
%llu Long Long Unsigned Integer
%x Hexadecimal Integer
%X Hexadecimal Integer (Uppercase)
%o Octal Integer
%f Float
%lf Double
%c Character
%s String
%p Pointer Address
Here's an example so that you can use Format Specifiers in C:
#include <stdio.h> Copy Code
int main()
{
int num = 42;
float pi = 3.14;
char letter = 'L';

printf("Integer = %d\n",num);
printf("Float = %f\n",pi);
printf("Character = %c\n",letter);
return 0;
}
Output:
Integer = 42
Float = 3.141592
Character = L

Escape Sequences

In C, an escape sequence is a combination of characters that begins with a backslash \ and is used to represent special characters and control codes within strings. These sequences are interpreted by the C compiler to produce specific characters or actions.

Escape Sequence Meaning Example Output
\\ Backslash "This is a backslash: \\\\n" This is a backslash: \
\' Single Quote '\'' '
\" Double Quote "\"Quoted text\"" "Quoted text"
\n Newline "Line 1\\nLine 2" Line 1
Line 2
\t Tab "Column 1\\tColumn 2" Column 1    Column 2
\r Carriage Return "AB\\rCD" CD
\b Backspace "ABC\\bD" ABD
\f Form Feed "Page 1\\fPage 2" Page 1
Page 2 (may not be visible in all environments)
\a Bell "\\aBeep!" (beeping sound or visual notification)
\v Vertical Tab "Line 1\\vLine 2" (may not be visible in all environments)

Format specifiers and escape sequences make it possible to manipulate and display data in a controlled and predictable manner in C programs. They are essential for input and output operations and for generating formatted output.