Escape sequences in C are special character combinations used to represent characters that are difficult or impossible to type directly in a string. They are typically used in formatting output, representing special characters, and controlling text display.
\
) followed by a specific character.Escape Sequence | Description | Example Output |
---|---|---|
\n | Newline (Moves cursor to next line) | "Hello\nWorld" → Hello (new line) World |
\t | Horizontal Tab (Adds tab space) | "A\tB" → A B |
\\ | Backslash (Prints \ ) | "C:\\Program Files" → C:\Program Files |
\' | Single Quote | '\'A\'' → ‘A’ |
\" | Double Quote | "He said \"Hello\"" → He said “Hello” |
\r | Carriage Return (Moves cursor to start of line) | "Hello\rHi" → Hilo |
\b | Backspace (Deletes previous character) | "AB\bC" → AC |
\f | Form Feed (Page break) | Rarely used |
\v | Vertical Tab | Rarely used |
\0 | Null Character (Indicates string termination) | Used to end strings |
\n
(Newline) and \t
(Tab)#include <stdio.h>
int main() {
printf("Hello\nWorld!\n");
printf("Name:\tJohn\nAge:\t25\n");
return 0;
}
Hello
World!
Name: John
Age: 25
\\
, \'
, and \"
#include <stdio.h>
int main() {
printf("C:\\Program Files\\MyApp\n");
printf("He said, \"Hello!\"\n");
printf("It\'s a great day!\n");
return 0;
}
C:\Program Files\MyApp
He said, "Hello!"
It's a great day!
\b
(Backspace) and \r
(Carriage Return)cCopyEdit#include <stdio.h>
int main() {
printf("Hello\b World!\n"); // Backspace removes 'o'
printf("Start\rEnd\n"); // Moves cursor to the beginning
return 0;
}
Hell World!
End
\0
(Null Character) in Strings#include <stdio.h>
int main() {
char str[] = "Hello\0World!";
printf("%s\n", str); // Only prints "Hello"
return 0;
}
Hello
Escape sequences in C enhance text formatting and allow special characters to be used in strings. Mastering them will help you write cleaner and more readable C programs.