Understanding Escape Sequences in C: Special Character Representations
Learn about escape sequences in C, which provide special meanings to characters following a backslash (\). Discover how they allow the representation of characters that are difficult to type directly, enhancing your programming capabilities.
Escape Sequences in C
Escape sequences in C give special meaning to characters following a backslash (\). They are used to represent characters that are difficult to type directly.
Common Escape Sequences
\\- Backslash\'- Single Quote\"- Double Quote\?- Question Mark\a- Alert/Bell\b- Backspace\f- Form Feed\n- New Line\r- Carriage Return\t- Horizontal Tab\v- Vertical Tab\ooo- Octal Number\xhh- Hexadecimal Number
Examples
New Line Escape Sequence (\n)
Inserts a new line in the output.
Syntax
#include
int main() {
printf("Hello\nWorld");
return 0;
}
Output
Hello
World
Tab Escape Sequence (\t)
Inserts a horizontal tab in the output.
Syntax
#include
int main() {
printf("Name:\tJohn\tMarks:\t90");
return 0;
}
Output
Name: John Marks: 90
Backslash Escape Sequence (\\)
Inserts a backslash in the output.
Syntax
#include
int main() {
printf("C:\\Windows\\System32");
return 0;
}
Output
C:\Windows\System32
Double and Single Quotes Escape Sequences (\" and \')
Inserts double or single quotes in the output.
Syntax
#include
int main() {
printf("He said, \"Hello!\"\n");
printf("It's a beautiful day.");
return 0;
}
Output
He said, "Hello!"
It's a beautiful day.
Backspace Escape Sequence (\b)
Deletes the previous character in the output.
Syntax
#include
int main() {
printf("Hello\b World");
return 0;
}
Output
Hell World
Octal Number Escape Sequence (\ooo)
Inserts a character based on its octal value.
Syntax
#include
int main() {
printf("%c", '\101');
return 0;
}
Output
A
Hexadecimal Number Escape Sequence (\xhh)
Inserts a character based on its hexadecimal value.
Syntax
#include
int main() {
printf("%c", '\x42');
return 0;
}
Output
B
Alert or Bell Escape Sequence (\a)
Produces a sound or visual alert.
Syntax
#include
int main() {
printf("Hello\a world\n");
return 0;
}
Output
Hello world