Double quotes vs single quotes in C
By Flavio Copes
Learn the difference between single quotes and double quotes in C: single quotes make a single char like 'a', while double quotes create a string literal.
In C, single quotes and double quotes mean two different things. Single quotes create a character constant, a single char value. Double quotes create a string literal, a sequence of characters terminated by a 0.
In some languages there’s no difference between the two. In C there is, and picking the wrong one gives you compiler warnings or bugs.
Single quotes create a character
Single quotes are used to identify a single character (char value):
char letter = 'a';
A character constant is really a number. 'a' is the code of the letter a in the character set, which is 97 in ASCII:
char letter = 'a';
printf("%c\n", letter); // a
printf("%d\n", letter); // 97
Since it’s a number, you can do math with it. 'a' + 1 gives you 'b':
printf("%c\n", letter + 1); // b
One detail that surprises many people: in C, character constants have type int, not char. So sizeof('a') is 4 on most systems, not 1. The value fits in a char when you assign it, but the constant itself is an int.
Double quotes create a string literal
Double quotes are used to create a string literal:
char *name = "Flavio";
A string is composed by the characters of the string, plus a 0 character at the end, called the null terminator. That’s how C knows where the string ends.
So "Flavio" takes 7 bytes of memory, not 6:
printf("%zu\n", sizeof("Flavio")); // 7
Note that you can create a single-letter string literal:
char *letter = "a";
But this is not the same as 'a'. The string "a" is two bytes (the letter plus the terminator), and it’s a pointer to memory, not a number.
What happens if you mix them up?
If you write this, the compiler warns you:
char letter = "a"; // warning: assigning a pointer to a char
The same goes for comparisons. if (letter == "a") compares a character against a memory address, which is never what you want. Use 'a' to compare single characters, and strcmp() to compare strings.
Want me to talk about your product? You can sponsor this site.