An escape sequence in C is used to conveniently format the strings and outputs of a program.
The escape sequence does not appear in the output when written in a character or string literal, rather it is represented through its functionality. The escape sequence consists of a backslash and any other character from the C character set.
Below are the 15 types of escape sequences that C provides:
Escape Sequence | Meaning | Description |
---|---|---|
\a |
Alarm or Beep | Generates a beep that alerts the user when the program is executed. |
\n |
New Line | Starts a new line in the output/string. |
\t |
Horizonal Tab | Adds a horizontal tab in the output/string. |
\r |
Carriage Return | Places the cursor at the start of the current line. |
\f |
Form Feed | Places the cursor at the start of the next page. |
\v |
Vertical Tab | Adds a vertical tab in the output/string. |
\\ |
Backslash | Displays a backslash in the output/string. |
\' |
Single Quote | Displays a single quote in the output/string. |
\" |
Double Quote | Displays a double quote in the output/string. |
\nnn |
Octal Number | Represents an octal number. |
\xhh |
Hexadecimal number | Represents a hexadecimal number. |
\0 |
Null | Adds a 0 character and usually denotes the termination of a string. |
\b |
Backspace | Backspaces a single character. |
\? |
Question Mark | Displays a question mark. |
The following code demonstrates the use of various C escape sequences such as \n
, \t
, \?
, and \"
:
#include <stdio.h>int main() {printf("---\\n---\n");// Example 1printf("What are escape sequences in C\nEducative.io");printf("\n");printf("---\\t---\n");//Example 2printf("What are escape sequences in C\tEducative.io");printf("\n");printf("---\\?---\n");// Example 3printf("What are escape sequences in C \? Educative.io");printf("\n");printf("---\\\"---\n");// Example 4printf("What are escape sequences in C \" Educative.io");printf("\n");printf("---\\\'---\n");// Example 5printf("What are escape sequences in C \' Educative.io");printf("\n");printf("---\\xhh---\n");// Example 6printf("What are escape sequences in C \x3a Educative.io");printf("\n");printf("---\\nnn---\n");// Example 7printf("What are escape sequences in C \123 Educative.io");printf("\n");}
\n
will display the string following that character in next line.
\t
will add a horizontal tab where it is written.
\?
will display a ? where it is written.
\"
will display a " where it is written.
\'
will display a ’ where it is written.
\xhh
will take the hexadecimal value and convert it to decimal, then it will display the corresponding ASCII character. In this example, x3a is 58 in decimal, and the corresponding ASCII character is :
.
\nnn
will take the octal value and convert it to decimal; then, it will display the corresponding ASCII character. In this example, 123 is 83 in decimal, and the corresponding ASCII character is S
.
Free Resources