We already met one escape sequence in Hello World!. It was the \n at the end of the first printf. There are several escape sequences in C. Below is a table listing all of them.
| Escape sequence | Name | Meaning | Example |
|---|---|---|---|
\n | Newline | Moves to the next line | Hello\nWorld |
\t | Horizontal tab | Inserts a horizontal tab | Hello\tWorld |
\v | Vertical tab | Inserts a vertical tab | Hello\vWorld |
\b | Backspace | Moves back one character position | Hello\bWorld |
\r | Carriage return | Moves to the start of the current line | Hello\rWorld |
\f | Form feed | Represents a form-feed character | Hello\fWorld |
\a | Alert | Requests an alert signal | \a |
\\ | Backslash | Prints a backslash | \\ → \ |
\' | Single quote | Represents a single quote | \' → ' |
\" | Double quote | Represents a double quote | \" → " |
\? | Question mark | Represents a question mark | \? → ? |
\0 | Null character | Represents a character with value zero | '\0' |
\ooo | Octal escape | Represents a character using octal digits | \101 → A |
\xhh | Hexadecimal escape | Represents a character using hexadecimal digits | \x41 → A |
\uXXXX | Unicode escape | Represents a Unicode character using four hexadecimal digits | \u00A9 → © |
\UXXXXXXXX | Unicode escape | Represents a Unicode character using eight hexadecimal digits | \U0001F600 → 😀 |
Difference Between \n and \r
The \n indicates a new line, while \r means a carriage return. But what does a carriage return mean in C? Consider this example code:
#include <stdio.h>
int main(void) {
printf("ABCDEFGHIJKLMNO\r");
printf("XYZ\n");
return 0;
}The output is
XYZDEFGHIJKLMNOWhen \n is seen, it just moves the cursor to the beginning of a new line, vertically. \r, on the other hand, moves the cursor to the beginning of the current line, horizontally. Below is how it works.
Step 1: Original text
ABCDEFGHIJKLMNO
Step 2: After \r (cursor returns to beginning)
ABCDEFGHIJKLMNO
^
Step 3: Print XYZ (overwrites first 3 characters)
XYZDEFGHIJKLMNO
^
Previous: Hello World!
Next up: Data Types And Variables