“a”和“a”之间的区别是什么? [英] What is the difference between 'a' and "a"?
问题描述
我在学习C ++,有一个问题,我找不到答案。
char
常量(使用单引号)和字符串常量(带双引号)?
所有与char数组相关的搜索结果vs std :: string
。我之后是'a'
和之间的区别
。
执行以下操作会有所不同:
cout< 一个;
cout<< '一个';
'a' code>是字符文字。它是
char
类型,在大多数系统上的值为97(ASCII / Latin-1 / Unicode编码的字母 a
)。
a
是一个字符串文字。它的类型为 const char [2]
,并引用一个数组2 char
c>'a'和'\0'
。在大多数但不是全部的上下文中,对a
的引用将隐式转换为指向字符串第一个字符的指针。
两者
cout< '一个';
和
cout< 一个;
恰好产生相同的输出,但是出于不同的原因。第一个打印单个字符值。第二个依次打印字符串的所有字符(除了结束'\0'
) - 这恰好是单个字符'字符串字面量可以任意长,例如
abcdefg
。
< 。字符文字几乎总是只包含一个字符。 (您可以有多字符文字,例如
'ab'
,但是它们的值是实现定义的,并且很少有用) / p> (在C中,你没有问过,'a'
是 int
和a
的类型为 char [2]
code> const ))。
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';
'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”和“a”之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!