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

Escaping double quotes

Escaping double quotes

What you'll learn: How to print a double quote character inside a string without confusing the C compiler.

The Quotation Paradox

In C, double quotes are like bookends. When you type printf("Hello"), the first quote tells the compiler, "A message is starting," and the second one says, "The message is over."

But what happens if you want to print a message that actually includes a quote? For example: The robot said, "Hello".

If you try to write printf("The robot said, "Hello".");, the compiler gets very confused. It sees the quote before Hello and thinks, "Aha! The message is finished!" Then, it sees the word Hello floating around outside of any quotes and treats it like broken code, resulting in a face-palm of error messages.

Meet the Backslash

To solve this, we use a "magic wand" called the escape character: the backslash (\).

When you put a backslash immediately before a double quote (\"), you are telling the compiler: "Hey, don't treat this next quote as a bookend. Just treat it as a normal piece of text to be printed."

Think of the backslash like a stagehand in a play. The stagehand isn't part of the story, but they are there to hold up a sign or move a prop. Once the audience (the user) sees the final result, the stagehand (the backslash) is invisible.

Seeing it in Action

Here is how you properly nest quotes inside a printf statement:

#include <stdio.h>

int main() {
    // The \" tells C to print a literal quote
    printf("The legend says, \"Code every day.\"");
    
    return 0;
}

When you run this code, the output will look exactly like this: The legend says, "Code every day."

Notice that the backslashes vanished in the output. Their only job was to protect those inner quotes from ending the string prematurely.

Why it matters

You will use this constantly when your program needs to display dialogue, cite titles, or output data that requires specific formatting. Without the escape character, your strings are limited to simple, quote-free sentences. With it, you can print any punctuation you like.

Key takeaway

Use \" to include a double quote inside a printf string without ending the message.