Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
C Escape Sequences Guide
Lecture 2 of the Elements of C chapter. Newline, tab, backslash, null, octal and hex escapes, whitespace and trigraphs, explained with runnable code in our free embedded systems course.
Some characters cannot be typed into a string: you cannot press a key that means “start a new line” without actually breaking your source file. C escape sequences solve this. A backslash followed by one or more characters stands for a single character the program can use at run time, such as newline, tab or the null terminator. If you work through this free embedded systems course for a product-company interview, expect questions on \0, \r and the hex-escape trap covered below.
We also cover trigraphs, an old three-character notation for keyboards that lacked certain symbols. They are almost extinct, but they still appear in quizzes and can silently change a string in strict compiler modes.
What You Will Learn
- Why escape sequences exist and how the compiler converts them while reading your source.
- Every standard escape: alert, backspace, tab, newline, vertical tab, form feed, carriage return, quotes, question mark and backslash.
- Octal and hexadecimal escapes, and the greedy hex pitfall.
- Why
\0is special and how it changesstrlenandsizeof. - What whitespace is in C and how to count it.
- What trigraphs are, which compilers still honour them, and why you should never write them.
Prerequisites
- You have finished the C character set lecture (cp1_1) or know that characters are small integers.
- You can compile and run a C file with GCC or Clang.
- You know that
printfprints a format string.
What Are C Escape Sequences?
An escape sequence is written as two or more source characters, always starting with a backslash, but it produces exactly one character in the running program. This is the bridge between the source character set and the execution character set that we discussed earlier. The conversion is performed by the compiler, not by printf: by the time your program runs, the two characters \ and n have already become the single byte 10.
Standard C Escape Sequences Reference
| Escape | Name | Decimal code (ASCII) | What a terminal does |
|---|---|---|---|
\a | Alert | 7 | Beep or visual bell |
\b | Backspace | 8 | Moves the cursor one position left |
\t | Horizontal tab | 9 | Jumps to the next tab stop |
\n | Newline | 10 | Moves to the start of the next line (text mode) |
\v | Vertical tab | 11 | Moves down to the next vertical tab position |
\f | Form feed | 12 | Starts a new page on printers; clears or scrolls on some terminals |
\r | Carriage return | 13 | Moves the cursor to the start of the current line |
\" | Double quote | 34 | Prints a quote inside a string |
\' | Single quote | 39 | Prints an apostrophe, needed in '\'' |
\? | Question mark | 63 | Prevents a trigraph from forming |
\\ | Backslash | 92 | Prints one backslash |
\0 | Null character | 0 | Nothing is shown; ends C strings |
Numeric escapes
\ooo takes one to three octal digits, so \101 is the letter A. \xhh takes any number of hex digits, so \x41 is also A. Notice that \0 is really just the octal form with a single digit zero, which is why it fits the same family. GCC also offers \e for the escape character (27), but it is a GNU extension and not standard C.
Alert, Backspace and Carriage Return
These three control characters were designed for mechanical teletypes and still behave that way in a terminal. \r does not erase anything: it only moves the cursor, and the next characters overwrite whatever was there. This is how command-line progress indicators redraw a single line. \b similarly moves left without erasing; to really erase a character you print a backspace, a space, and another backspace.
Newline, Tab and the Text Mode Story
On Linux a newline is the single byte 10. Windows text files store two bytes, 13 and 10, and the C runtime translates for you in text mode. For embedded Linux work you will almost always see plain 10, but when you read a log file copied from Windows, the invisible 13 at the end of each line is the reason for odd comparison failures.
Quotes and Backslash
Inside a string, a plain double quote would end the string, so you write \". Inside a character constant, a plain single quote would end the constant, so you write '\''. A literal backslash must be doubled, which matters in Windows paths and regular expressions: the path C:\embedded\notes is written "C:\\embedded\\notes".
The Null Character and C Strings
C strings have no length field. They are arrays of characters ended by a byte with value 0. Functions such as strlen and printf("%s") stop at the first zero byte. That makes \0 one of the most important escape sequences for any embedded engineer, and also the source of classic bugs: an embedded zero inside data cuts a string short, and forgetting space for the terminator overflows buffers.
Whitespace Characters in C
Whitespace is the family of characters that produce blank space rather than a visible mark: space, horizontal tab, vertical tab, newline, form feed and carriage return. The standard library function isspace recognises exactly these six. In source code the lexer treats them as token separators and otherwise ignores them. Inside strings and character constants they are ordinary data.
C Trigraph Sequences
In the 1980s many national keyboards, built to the ISO 646 standard, had no keys for { } [ ] \ | ~ ^ #. To let programmers on those machines write C, the standard defined trigraphs: sequences of three characters that begin with two question marks and are replaced very early by the compiler, even before it sorts out string literals.
| Trigraph | Replaced by | Name |
|---|---|---|
??= | # | Hash |
??( | [ | Left bracket |
??) | ] | Right bracket |
??< | { | Left brace |
??> | } | Right brace |
??/ | \ | Backslash |
??' | ^ | Caret |
??! | | | Vertical bar |
??- | ~ | Tilde |
Current status: Trigraphs were removed from the language in C23, and C++ dropped them earlier, in C++17. GCC ignores them by default in its GNU modes and only converts them in strict modes such as -std=c11 or when you pass -trigraphs. Do not write them in new code; know them so you can read legacy code and answer interview questions.
The Surprise Inside Innocent Strings
Because the conversion happens before strings are parsed, a harmless-looking message like "What??!" turns into "What|" in strict mode. When you really need two question marks in a row, split the string or escape the second one: "What?\?!". That is the purpose of the \? escape in the table above.
Hands-On Examples: C Escape Sequences in Practice
All programs were compiled with gcc -Wall -Wextra -std=c17 on 64-bit Linux and the outputs are real.
Example 1: A Formatted Table with Tab and Quotes
Goal: use \t, \n, \\, \" and \' in ordinary output.
#include <stdio.h>
int main(void)
{
printf("ID\tName\tScore\n");
printf("1\tAsha\t92\n");
printf("2\tRavi\t88\n");
printf("Path: C:\\embedded\\notes\n");
printf("He said \"hello\" and left\n");
printf("It\'s fine, and what? needs no escape\n");
return 0;
}
gcc -Wall -Wextra -std=c17 escapes.c -o escapes
./escapes
Expected output (tab stops depend on your terminal):
ID Name Score
1 Asha 92
2 Ravi 88
Path: C:\embedded\notes
He said "hello" and left
It's fine, and what? needs no escape
- Each
\tjumps to the next tab stop, which aligns the columns. - The apostrophe in the last line needs no escape inside a double-quoted string; the escape is optional there but harmless.
Try it yourself: print the path /usr/local/bin with backslashes
You need doubled backslashes: printf("\\usr\\local\\bin\n"); prints \usr\local\bin.
Example 2: Carriage Return and Backspace
Goal: see that \r and \b move the cursor rather than erase, and look at the raw bytes.
#include <stdio.h>
int main(void)
{
printf("Progress: 25%%");
fflush(stdout);
printf("\rProgress: 100%%\n");
printf("abc\b\bX\n");
return 0;
}
What a terminal shows:
Progress: 100%
aXc
What the program really wrote, checked with ./escapes2 | od -c:
0000000 P r o g r e s s : 2 5 % \r P r
0000020 o g r e s s : 1 0 0 % \n a b c
0000040 \b \b X \n
0000044
- The first line was drawn as
Progress: 25%, then\rreturned to column one and the longer text overwrote it completely. - If the new text were shorter, leftover characters from the old text would still show. Pad with spaces in that case.
- In the second line, two backspaces moved the cursor back over
candb; printingXreplacedb, givingaXc. - The
fflush(stdout)call forces the first piece out immediately; output to a terminal is normally line-buffered and would otherwise wait for a newline.
Try it yourself: make a countdown from 5 to 1 on one line
Use a loop that prints "\rStarting in %d " with fflush(stdout) and sleep(1) from unistd.h. The trailing space erases any longer previous text.
Example 3: Octal, Hex and the Null Character
Goal: write characters by number and watch \0 shorten a string.
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[] = "AB\0CD";
printf("sizeof = %zu, strlen = %zu\n", sizeof a, strlen(a));
printf("printed with %%s: [%s]\n", a);
printf("\x48\x69 | \110\151 | %c\n", 0x21);
printf("\x41" "BC\n");
printf("codes: bell=%d null=%d\n", '\a', '\0');
return 0;
}
sizeof = 6, strlen = 2
printed with %s: [AB]
Hi | Hi | !
ABC
codes: bell=7 null=0
sizeof ais 6: five visible characters plus the implicit terminator.strlenis 2 because it stops at the embedded zero.\x48\x69and\110\151both spell “Hi”, one in hex and one in octal.0x21passed to%cprints an exclamation mark."\x41" "BC"relies on adjacent string literals being concatenated. Writing"\x41BC"instead would make the hex escape swallow the B and C, since they are valid hex digits, and the compiler would warn that the value is out of range.
Try it yourself: why is “\x41G” safe?
G is not a hexadecimal digit, so the escape ends after 41 and the result is “AG”. Hex escapes consume digits greedily, so they only end at a non-hex character.
Example 4: Counting Whitespace Characters
Goal: identify each kind of whitespace inside one string and compare with isspace.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
const char *s = "a b\tc\nd\ve\ff\rg";
int sp = 0, tab = 0, nl = 0, vt = 0, ff = 0, cr = 0, all = 0;
for (const char *p = s; *p != '\0'; p++) {
switch (*p) {
case ' ': sp++; break;
case '\t': tab++; break;
case '\n': nl++; break;
case '\v': vt++; break;
case '\f': ff++; break;
case '\r': cr++; break;
default: break;
}
if (isspace((unsigned char)*p))
all++;
}
printf("space=%d tab=%d newline=%d vtab=%d formfeed=%d cr=%d\n",
sp, tab, nl, vt, ff, cr);
printf("isspace() counted %d whitespace characters\n", all);
return 0;
}
space=1 tab=1 newline=1 vtab=1 formfeed=1 cr=1
isspace() counted 6 whitespace characters
- The test string is
"a b\tc\nd\ve\ff\rg": it holds a space, tab, newline, vertical tab, form feed and carriage return, one of each. - Notice the text
\ffin the source: the firstfcompletes the escape\f, and the secondfis an ordinary letter. - The two counts agree, which confirms that
isspacecovers exactly the six whitespace characters.
Try it yourself: trim trailing whitespace from a string
Find the end with strlen, then walk backwards while isspace((unsigned char)s[i - 1]) and replace the first trailing whitespace with '\0'. This is the first function many interviewers ask for.
Example 5: What Your Compiler Does with Trigraphs
Goal: compile the same unusual-looking file in several modes. The file below is valid C written entirely with trigraphs.
#include <stdio.h>
int main(void)
??<
int v??(2??) = ??< 10, 20 ??>;
printf("%d??/n", v??(1??));
return 0;
??>
Default GNU mode: the trigraphs are not converted, the compiler only warns, then fails.
gcc -Wall -std=gnu17 trigraph.c -o t
trigraph.c:4:1: warning: trigraph ??< ignored, use -trigraphs to enable [-Wtrigraphs]
Strict C11 mode converts them, so the program builds and prints the second array element:
gcc -std=c11 trigraph.c -o t
./t
20
Asking for them explicitly in GNU mode gives the same result:
gcc -std=gnu17 -trigraphs trigraph.c -o t
./t
20
In the C23 mode of the GCC used here, they are ignored again, consistent with their removal from the standard:
gcc -Wall -std=c2x trigraph.c -o t
trigraph.c:4:1: warning: trigraph ??< ignored, use -trigraphs to enable [-Wtrigraphs]
- The sequence
??/ninside the string became a backslash followed byn, so the final newline was produced by a trigraph. The printed value 20 comes fromv[1]. - Always read compiler warnings: the message “trigraph ignored” is a hint that a legacy file expects different options.
Common Mistakes with C Escape Sequences
| Mistake | What happens | Fix |
|---|---|---|
Writing "C:\new\table" | \n and \t become control characters | Double every backslash |
Greedy hex escape such as "\x41BC" | Out-of-range warning or wrong character | Split the literal: "\x41" "BC" |
Allocating char buf[4] for “four” | No room for the terminating \0 | Reserve one extra byte |
Using \r to erase text | Old characters remain visible | Overwrite with spaces |
Inserting \0 in text data | String functions truncate it | Use length-aware functions such as memcpy |
| Writing two question marks followed by a symbol | Hidden trigraph in strict mode | Escape one: ?\? |
Sending \n to a serial console that expects \r\n | Staircase output | Send both characters, or configure the terminal |
Best Practices, Performance and Security
- Use
\nfor line endings in source and let the platform handle translation. - For embedded serial output, check what the other side expects: many consoles need
\r\n. - Prefer named constants for control bytes in protocols, for example
#define STX 0x02, instead of scattering magic escapes. - Security: strings that contain user-supplied data should never be passed as the format argument of
printf. A user can inject%nor%s. Useprintf("%s", text). - Security: terminal escape codes (byte 27) in log output can hide or fake lines. Strip control characters before logging untrusted text.
- Performance: the compiler resolves all escapes at build time, so they cost nothing at run time.
Summary and Key Takeaways
- An escape sequence is written with a backslash but stored as one character.
- The standard set is
\a \b \t \n \v \f \r \" \' \? \\plus octal and hex numeric forms. \0terminates C strings;strlenandsizeofcan disagree because of it.- Hex escapes are greedy; octal escapes stop after three digits.
- Whitespace means space, tab, newline, vertical tab, form feed and carriage return.
- Trigraphs are obsolete, removed in C23, and active only in strict modes or with
-trigraphs.
Quiz: C Escape Sequences
Question 1
Which escape moves the cursor to the start of the current line without advancing?
Show answer
\r, the carriage return.
Question 2
What are sizeof and strlen for char s[] = "ab\0cd";?
Show answer
sizeof is 6 and strlen is 2.
Question 3
What ASCII value does '\n' have?
Show answer
10.
Question 4
How do you write a string containing a double quote?
Show answer
Use \", for example "say \"hi\"".
Question 5
What does "\101" contain?
Show answer
The letter A. Octal 101 equals decimal 65.
Question 6
How many characters are whitespace in "a\tb\nc "?
Show answer
Three: the tab, the newline and the trailing space.
Question 7
In strict C11 mode, what does the trigraph ??! become?
Show answer
The vertical bar |.
Question 8
True or false: \e is a standard C escape sequence.
Show answer
False. It is a GNU extension for byte 27.
Interview Questions on Escape Sequences
Q1. What is the difference between ‘\0’, ‘0’ and NULL?
Show answer
'\0' is the null character with value 0. '0' is the digit character with value 48. NULL is a null pointer constant, a pointer concept. Mixing them compiles in many cases and fails in subtle ones, for example a loop that tests *p == '0' never stops at the end of a string.
Q2. Why can printf(“%d\n”) crash or leak data?
Show answer
The format asks for an argument that was never passed, so printf reads whatever is on the stack or in a register. It is undefined behaviour and a classic format-string vulnerability when the format comes from user input.
Q3. How do you print a string containing a null byte?
Show answer
Not with %s. Use fwrite(buf, 1, len, stdout) or write with an explicit length so the zero is treated as data.
Q4. What is the type and value of ‘\n’ in C?
Show answer
It has type int in C and value 10. In C++ it has type char.
Q5. Why does “\x41BC” cause trouble?
Show answer
Hex escapes consume every following hex digit. The compiler reads 41BC as one huge value that does not fit in a char. Fix it by concatenating literals.
Q6. What is the difference between \r\n and \n and who adds the extra byte?
Show answer
Windows text mode translates \n to two bytes on output; Linux does not. Network protocols such as HTTP and SMTP require the explicit pair, so protocol code writes \r\n itself.
Frequently Asked Questions
What is an escape sequence in C?
A backslash followed by characters that the compiler replaces with a single character, such as newline or tab.
Why do I need to escape a backslash?
Because the backslash is the escape introducer. Writing two backslashes produces one real backslash.
Are trigraphs still supported?
They were removed in C23. Older standards mode in GCC and Clang still convert them when asked, but they are ignored by default in GNU modes.
What is the difference between \n and \r?
Newline moves to the next line; carriage return moves back to the start of the current line without advancing.
Does \0 end every string automatically?
String literals get a terminating null added by the compiler, and library functions rely on it. Arrays you fill yourself need you to add it.
Can I learn this in a free embedded Linux course?
Yes. This lecture is part of our free embedded Linux and C programming course, with examples you can run on any Linux machine.
Conclusion
Escape sequences let a program use characters that no keyboard can place inside a string, and the null character in particular shapes how every C string works. You saw the full standard table, learned why carriage return and backspace only move the cursor, wrote characters by octal and hex code, and watched a legacy trigraph file behave differently under four compiler modes. In the next lecture we leave characters behind and meet keywords and identifiers, the words that give C programs their meaning, as we continue through this free embedded systems course.
Practise before moving on
Re-type each example, break it on purpose with a greedy hex escape, and compare the compiler messages with what you read here.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments