Single quotes vs. double quotes in C or C++

When should I use single quotes and double quotes in C or C++ programming?


Solution 1:

In C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a' is a single a character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array).

In C++ the type of a character literal is char, but note that in C, the type of a character literal is int, that is sizeof 'a' is 4 in an architecture where ints are 32bit (and CHAR_BIT is 8), while sizeof(char) is 1 everywhere.

Solution 2:

Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:

6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."

This could look like this, for instance:

const uint32_t png_ihdr = 'IHDR';

The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.

Solution 3:

Single quotes are characters (char), double quotes are null-terminated strings (char *).

char c = 'x';
char *s = "Hello World";

Solution 4:

  • 'x' is an integer, representing the numerical value of the letter x in the machine’s character set
  • "x" is an array of characters, two characters long, consisting of ‘x’ followed by ‘\0’