Quotes in Text

The double quotes show where a text starts and where it ends. So what if you want to print a quote, for example in a conversation? This doesn't work:

#include <stdio.h>

int main(void) {
    printf("Mum shouted: "Dinner is ready!"\n");
    return 0;
}

The compiler doesn't run the program and shows an error message:

main.c:4:27: error: expected ')'
    4 |     printf("Mum shouted: "Dinner is ready!"\n");
      |                           ^
main.c:4:11: note: to match this '('
    4 |     printf("Mum shouted: "Dinner is ready!"\n");
      |           ^
1 error generated.

You'll learn to read error messages later in this lesson. For now, it's enough to know why this one appeared: the compiler reads the text only up to the second quote, "Mum shouted: ", and thinks that the text ends there. Right after it, it finds the word Dinner, which makes no sense to it.

To put a quote inside a text, write a backslash in front of it: \". The backslash tells the compiler that this quote doesn't end the text; it's just a character to print:

printf("Mum shouted: \"Dinner is ready!\"\n");

This prints:

Mum shouted: "Dinner is ready!"

You already know one pair of characters with a backslash: \n. A backslash always gives the character after it a special meaning. And if you want to print the backslash itself, write it twice, \\:

printf("Hooray! \\o/\n");

This prints:

Hooray! \o/

An apostrophe ' doesn't need a backslash: printf("I'm coming!\n"); works as it is. But don't use single quotes in place of double ones. printf('Hello!\n'); ends with an error, because single quotes mean something else in C: a single character, as you'll see in the next lesson.

Also watch out for curly quotes “ and ”, which word processors make automatically. For C, they are completely different characters from ". Inside a text, you can use them, and they are printed without a backslash, but they can't start or end a text. So be careful when you copy code from a document that turned straight quotes into curly ones: the compiler then reports unexpected character <U+201C>.

Instructions

Run the program. Then put quotes around Dinner is ready!, so that the program prints:

Mum shouted: "Dinner is ready!"

Below it, add Tom's answer with another printf, so that the program prints:

Mum shouted: "Dinner is ready!"
Tom answered: "I'm coming!"

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

3/7