Course contentsShow
← C
Lesson 47 of 1,2191. FoundationsFree lesson

Escaping the backslash

Escaping the backslash

What you'll learn: How to print a literal backslash character in C without confusing the compiler.

The backslash's secret job

In C, the backslash (\) is a "magic" character. It doesn't usually act like a normal letter; instead, it acts like a signal flare. When the printf function sees a backslash, it stops and thinks, "Okay, the next character isn't a letter—it’s a special command."

You have likely already seen this with \n, which tells C to start a new line. Because the backslash is reserved for these special instructions (called escape sequences), the compiler gets very confused if you try to use it like a regular piece of text. If you type printf("C:\Windows");, C will see the \W and wonder what secret command you are trying to trigger. Since \W isn't a standard command, your program might throw an error or behave unpredictably.

The "Double Up" trick

So, how do you tell C, "I actually want a real, visible backslash on the screen"?

The solution is a bit like a "cancellation" rule in grammar. To print one backslash, you have to type two of them back-to-back: \\.

Think of it like a secret handshake. The first backslash tells the compiler, "Get ready, a special character is coming!" The second backslash says, "The special character is... me! Just print me as a normal symbol." By escaping the backslash with another backslash, you neutralize its magic powers and turn it back into plain text.

Seeing it in code

Here is how you would correctly print a file path or a simple shrug emoticon in C:

#include <stdio.h>

int main() {
    // To show one backslash, we type two
    printf("Folder path: C:\\Users\\Name\n");
    
    // It works the same way for art or symbols
    printf("The backslash looks like this: \\ \n");
    
    return 0;
}

When you run this code, the output will only show a single \ wherever you typed \\. The compiler "consumes" the first one to understand the instruction and outputs the second one to the console.

Key takeaway

To print a literal backslash character, you must use the escape sequence \\.