I am learning C++ and have got a question that I cannot find the answer to.
What is the difference between a char
constant (using single quotes) and a string constant (with double quotes)?
All my search results related to char arrays vs std::string
. I am after the difference between 'a'
and "a"
.
Would there be a difference in doing the following:
cout << "a";
cout << 'a';
While professors control where each plus or minus cut off begins, a typical grading scale, the one I will use throughout this article, follows this pattern: A = 100-93, A- = 92.9-90, B+ = 89.9-87, B = 86.9-83 and so on.
Thus, an A is a 95, halfway between 90 and 100. An A- is a 91.25, halfway between 90 and 92.5. Etc. Grades between these are averages.
'a'
is a character literal. It's of type char
, with the value 97 on most systems (the ASCII/Latin-1/Unicode encoding for the letter a
).
"a"
is a string literal. It's of type const char[2]
, and refers to an array of 2 char
s with values 'a'
and '\0'
. In most, but not all, contexts, a reference to "a"
will be implicitly converted to a pointer to the first character of the string.
Both
cout << 'a';
and
cout << "a";
happen to produce the same output, but for different reasons. The first prints a single character value. The second successively prints all the characters of the string (except for the terminating '\0'
) -- which happens to be the single character 'a'
.
String literals can be arbitrarily long, such as "abcdefg"
. Character literals almost always contain just a single character. (You can have multicharacter literals, such as 'ab'
, but their values are implementation-defined and they're very rarely useful.)
(In C, which you didn't ask about, 'a'
is of type int
, and "a"
is of type char[2]
(no const
)).
"a"
is an array of characters that just happens to only contain one character, or two if you count the \0
at the end. 'a'
is one character. They're not the same thing. For example:
#include <stdio.h>
void test(char c) {
printf("Got character %c\n", c);
}
void test(const char* c) {
printf("Got string %s\n", c);
}
int main() {
test('c');
test("c");
}
This will use two different overloads; see http://codepad.org/okl0UcCN for a demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With