Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

c++ - What is the difference between 'a' and "a"?

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';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

'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 chars with values 'a' and ''. 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 '') -- 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)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...