CEscape Sequences

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

\n

Newline (line feed)

\t

Horizontal tab

\\

A literal backslash

\'

A literal single quote

\"

A literal double quote

\0

The null character (value zero) — terminates C strings

\r

Carriage return

\a

Alert / bell (produces a beep on many terminals)

\b

Backspace

\f

Form feed

\v

Vertical tab

C
#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:

C
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 */
Forgetting the null terminator is undefined behavior
If you build a character array by hand (rather than from a string literal) and forget to place a `\0` at the end, every string function that touches it will keep reading past the array's actual bounds looking for a terminator that was never written — this is a classic source of buffer over-reads and crashes. The full details of C strings and this rule get their own dedicated pages later.
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):

C
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' */
These are rarely used directly
In everyday code, named escapes like `\n` and `\t` are almost always clearer than their numeric equivalents. Numeric escapes are mostly useful for characters that have no named escape sequence, such as a specific byte in a non-ASCII encoding or a control character used in a binary protocol.