为什么这个带有 '1234' 的代码在 C++ 中编译?

2022-01-12 00:00:00 char c++

为什么会编译:

char ch = '1234'; //no error

但不能超过 4 个 chars :

But not anything more than 4 chars :

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 chars 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 letter L, as in L’x’. A character literal that does not begin with L 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 type int and implementation-defined value.

相关文章