Course contentsShow
← C
Lesson 108 of 1,2192. Variables and TypesFree lesson

Escape sequences like `\n` and `\t`

Escape sequences like \n and \t

What you'll learn: How to use special backslash codes to represent invisible formatting characters like new lines and tabs within your text.

The problem with "invisible" keys

When you are typing in a word processor, you hit the Enter key to start a new line or the Tab key to indent a paragraph. However, if you try to press Enter inside a pair of quotation marks in C, the compiler will get confused and throw an error. It expects your text strings to stay on one horizontal line in the code editor.

To solve this, C uses "Escape Sequences." These are pairs of characters starting with a backslash (\) that tell the computer, "Don't print these literally; instead, perform a special action." The backslash "escapes" the normal rules of text.

Common formatting escapes

The two most common escape sequences you will use are:

  1. \n (Newline): This acts just like hitting the Enter key. It moves the cursor to the start of the next line.
  2. \t (Tab): This pushes the text over to the next tab stop, creating a consistent gap of white space.

Think of these like invisible stickers you place in your text. When the printf function encounters \n, it stops printing on the current line and jumps down, even though you didn't physically type a line break in your code.

Seeing it in action

Notice how we can create a organized list or a multi-line message using only one set of quotation marks:

#include <stdio.h>

int main() {
    // \n breaks the line, \t creates an indent
    printf("Shopping List:\n");
    printf("\t- Milk\n\t- Eggs\n\t- Bread\n");
    
    printf("Done!\n");
    return 0;
}

In the example above, \t- Milk\n tells the computer: "Indent, print a dash and the word Milk, then jump to a new line." Without these sequences, all your output would be crammed together in one long, unreadable string.

Other useful escapes

Sometimes you need to print a character that C usually uses for syntax. For example, if you want to print a literal backslash, you type \\. If you want to print double quotes inside a string without ending the string early, you type \".

Key takeaway

Escape sequences use a backslash (\) followed by a letter to represent "invisible" formatting like new lines (\n) and tabs (\t).