char val ='abcd'。使用多字符字符 [英] char val = 'abcd'. Using multi character char

查看:125
本文介绍了char val ='abcd'。使用多字符字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编译器如何处理具有多个字符的char变量感到困惑。我知道char是1个字节,并且可以包含一个像ASCII这样的字符。

I have a confusion of how the compiler handles a char variable with multiple characters. I understand that a char is 1 byte and it can contain one character like ASCII.

但是当我尝试:

char _val = 'ab';
char _val = 'abc';
char _val = 'abcd';

它们编译良好,当我打印_val时,它总是打印最后一个字符。但是当我这样做时

They compiles fine and when I print _val it always prints the last character. But when I did

char _val = 'abcde';

然后我遇到了编译器错误:

Then I got a compiler error:


错误1错误C2015:常量中的字符过多

Error 1 error C2015: too many characters in constant

所以我的问题是:


  1. 为什么使用多个字符时编译器总是采用最后一个字符?在这种情况下,编译器的机制是什么。

  2. 为什么我放5个字符时出现太多字符错误。 2个字符比char所能处理的更多,所以为什么要5个?

我正在使用Visual Studio 2013。

I am using Visual Studio 2013.

谢谢。

推荐答案

[lex.ccon] / 1:

[lex.ccon]/1:


包含多个c-char的普通字符文字是
多字符文字。多字符文字[..] 受条件支持,类型为 int ,而
具有实现定义的值。

An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal [..] is conditionally-supported, has type int, and has an implementation-defined value.








为什么当多个倍数时编译器总是采用最后一个字符使用
个字符?在这种情况下,编译器的机制是什么。

Why does the compiler always takes the last character when multiple characters are used? What is the compiler mechanism in this situation.

大多数编译器只是将字符值按顺序移位:这样,最后一个字符会占用最低有效字节,倒数第二个字符占据最低有效字节旁边的字节,依此类推。

Ie 'abc'等同于'c'+((int)'b')<<<<< 8)+(((int 'a')<< 16) 演示 )。

Most compilers just shift the character values together in order: That way the last character occupies the least significant byte, the penultimate character occupies the byte next to the least significant one, and so forth.
I.e. 'abc' would be equivalent to 'c' + ((int)'b')<<8) + (((int)'a')<<16) (Demo).

将此 int 转换回 char 将具有一个实现定义的值-可能只是通过取 int 模256的值而得出的。这只会为您提供最后一个字符。

Converting this int back to a char will have an implementation defined value - that might just emerge from taking the value of the int modulo 256. That would simply give you the last character.


为什么我放5个字符时出现太多字符错误。 2个
字符比一个char所能处理的更多,所以为什么要5个呢?

Why did I get a too many characters error when I put 5 characters. 2 characters is more than what a char can handle so why 5?

因为在您的计算机上< c> int 可能是四个字节。如果上述确实是您的编译器安排多字符常量的方式,则他不能将五个 char 值放入 int 中。

Because on your machine an int is probably four bytes large. If the above is indeed the way your compiler arranges multicharacter constants in, he cannot put five char values into an int.

这篇关于char val ='abcd'。使用多字符字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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