为什么这个带有 '1234' 的代码在 C++ 中编译? [英] Why does this code with '1234' compile in C++?

查看:12
本文介绍了为什么这个带有 '1234' 的代码在 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.

这篇关于为什么这个带有 '1234' 的代码在 C++ 中编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆