Difference between single and double quotes in C (Ch. 11)

Hi everyone. My first post here and I thought I’d share something I learned today as I was going through chapter 11.

I wrote out a quick ex_playground.c file to try my hand at doing some of the things Zed did in the book on my own.

#include <stdio.h>

int main(int argc, char *argv[])
        char *name = "Stephen";
        printf("My first name is %s.\n", name);

        char last[9] = { 'a' };

        last[0] = "T";
        last[1] = "a";
        last[2] = "n";
        last[3] = "k";
        last[4] = "s";
        last[5] = "l";
        last[6] = "e";
        last[7] = "y";
        last[8] = "\0";

        printf("My last name is %s.\n", last);

        printf("My full name is %s %s.\n", name, last);

        return 0;

To my chagrin as I tried to compile the work, I got the following error:

ex_playground.c:18:15: warning: incompatible pointer to integer conversion
      assigning to 'char' from 'char [2]' [-Wint-conversion]
        last_name[8] = "\0";

I reviewed what was in the book and compared it to my own code. It looked pretty darn close to what we were being taught in the book, so I had to dig a bit deeper. I noticed that Zed was specifying single characters in single quotes whereas I was adding my single characters in double quotes. I suspected that this might be an issue, so I Googled it and voila, there it was.

In C, a single quote is used to specify a single character whereas a double quote is used to specify a string literal. Ergo I changed all of those double quotes to single quotes and it worked like a charm.

Hopefully this helps someone else.

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.