When to use Single quote and double quote in C programming ?
Single quotes are characters (char
), double quotes are null-terminated strings (char *
).
char c = 'x';
char *s = "Hello World";
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).
Note that in C, the type of a character literal is int
, and not char
, that is sizeof 'a'
is 4 in an architecture where ints are 32bit (and CHAR_BIT is 8), while sizeof(char)
is 1 everywhere.
In C single quotes such as 'a' indicate character constants whereas "a" is an array of characters, always terminated with the 0 character
Double quotes are for string literals, e.g.:
char str[] = "Hello world";
Single quotes are for single character literals, e.g.:
char c = 'x';
EDIT As David stated in another answer, the type of a character literal is int
.
Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.
char myChar = 'A';
char myString[] = "Hello Mum";
char myOtherString[] = { 'H','e','l','l','o','\0' };
Use single quote with single char as:
char ch = 'a';
here 'a'
is a char constant and is equal to the ASCII
value of char a.
Use double quote with strings as:
char str[] = "foo";
here "foo"
is a string literal.
Its okay to use "a"
but its not okay to use 'foo'
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 in platform-independent code.