Why does this code with #39;1234#39; compile in C++?(为什么这个带有 1234 的代码在 C++ 中编译?)
问题描述
为什么会编译:
char ch = '1234'; //no error
但不能超过 4 个 char
s :
But not anything more than 4 char
s :
char ch = '12345'; //error: Too many chars in constant
(是的,我知道 ' '
用于一个 char
而 " "
用于字符串;我只是在试验)
(Yes I know ' '
is used for one char
and " "
is for strings; I was just experimenting)
这是否与 char
使用 ASCII 数字表示这一事实有关?
Does this have anything to do with the fact that char
s are represented using ASCII numbers?
推荐答案
它是一个多字符文字,类型为 int
.
It's a multicharacter literal, and has a type of int
.
字符字面量是用单引号括起来的一个或多个字符,如 'x'
,前面可选字母 L
,如 L'x'代码>.不以
L
开头的字符文字是普通字符文字,也称为窄字符文字.包含单个 c-char 的普通字符文字具有 char 类型,其值等于执行字符集中 c-char 编码的数值.包含多个 c-char 的普通字符文字是多字符文字.多字符文字具有 int
类型和实现定义的值.
C++11 §2.13.2 Character literals
A character literal is one or more characters enclosed in single quotes, as in
’x’
, optionally preceded by the letterL
, as inL’x’
. A character literal that does not begin withL
is an ordinary character literal, also referred to as a narrow-character literal. An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set. An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal has typeint
and implementation-defined value.
这篇关于为什么这个带有 '1234' 的代码在 C++ 中编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个带有 '1234' 的代码在 C++ 中编译?


- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 从python回调到c++的选项 2022-11-16