Escape sequences in C are special character combinations that are used to represent certain characters that cannot be easily typed or displayed directly in a string. They start with a backslash (\
) followed by one or more characters. Escape sequences are commonly used in string literals to format output, insert special characters, and control how strings are displayed.
Here are some of the most commonly used escape sequences in C:
Here’s a simple example that demonstrates the use of escape sequences in C:
#include <stdio.h>
int main() {
printf("Hello, World!\n"); // Newline
printf("Tab\tSpace\n"); // Tab
printf("This is a backslash: \\\n"); // Backslash
printf("He said, 'Hello!'\n"); // Single quote
printf("She said, \"Hi!\"\n"); // Double quote
printf("Hello\bWorld\n"); // Backspace
return 0;
}
Newline (\n
): Moves the cursor to the next line. When printed, "Hello, World!" appears on one line, and the next output begins on a new line.
Tab (\t
): Inserts a horizontal tab space. The output "Tab Space" has a tab space between "Tab" and "Space."
Backslash (\\
): Prints a single backslash in the output. Since the backslash is an escape character, we need to use two to represent one.
Single Quote (\'
): Prints a single quote character inside the output string.
Double Quote (\"
): Prints a double quote character inside the output string.
Backspace (\b
): Moves the cursor one position back, effectively deleting the last character printed. In this case, it prints "Hello" followed by "World" on the same line, but the last "o" in "Hello" is erased.
@aCodeTutorials All Rights Reserved
privacy policy | about