Escape Sequences
Some characters — a newline, a tab, a backslash itself, a quote mark that would otherwise end a string — can't be typed directly inside a character or string literal without ambiguity. C solves this with escape sequences: a backslash followed by one or more characters that together represent a single special character.
Common escape sequences
Sequence | Meaning |
|---|---|
| Newline (line feed) |
| Horizontal tab |
| A literal backslash |
| A literal single quote |
| A literal double quote |
| The null character (value zero) — terminates C strings |
| Carriage return |
| Alert / bell (produces a beep on many terminals) |
| Backspace |
| Form feed |
| Vertical tab |
#include <stdio.h>
int main(void) {
printf("Line one\nLine two\n");
printf("Name:\tAda\n");
printf("She said \"hello\"\n");
printf("Path: C:\\Users\\ada\n");
printf("Beep!\a\n");
return 0;
}Line one Line two Name: Ada She said "hello" Path: C:\Users\ada Beep!
The null terminator: \0
The most important escape sequence in all of C is \0, the null character — a single byte with the value zero. C strings are just arrays of char with no separately stored length; every function that works with strings (printf's %s, strlen, strcpy, and so on) finds the end of the string by scanning forward until it hits a \0 byte. String literals get this terminator added automatically:
char name[] = "Ada";
/* name actually contains 4 bytes: {'A', 'd', 'a', '\0'} */
/* sizeof(name) is 4, but strlen(name) is 3 -- strlen doesn't count the terminator */Octal and hex escape sequences
You can also specify a character by its numeric code directly, using an octal escape (\ followed by up to three octal digits) or a hexadecimal escape (\x followed by hex digits):
char letter_a_octal = '\101'; /* octal 101 = decimal 65 = 'A' */ char letter_a_hex = '\x41'; /* hex 41 = decimal 65 = 'A' */ char newline_hex = '\x0A'; /* same as '\n' */