在查看一些旨在在 MS Visual C++ 中编译的 WINAPI 代码时,我发现了以下内容(已简化):
char buf[4];
// buf gets filled ...
switch ((buf[0] << 8) + buf[1]) {
case 'CT':
/* ... */
case 'SY':
/* ... */
default:
break;
}
}
假设是 16 位字符,我可以理解为什么要移动 buf[0]
并添加 buf[1]
。我不明白 case 子句中的比较是如何工作的。
我无法访问 Visual C++,当然,那些会在 gcc/MingW 上产生多字符字符常量 [-Wmultichar]
警告。
最佳答案
这是一种非可移植存储多个 char
的方式合二为一int
.最后,比较发生在 int
。值(value)观,一如既往。
注意:考虑每个个体的 ASCII 值的串联表示 char
作为最后的int
值(value)。
在 wiki 之后文章,(强调我的)
[...] Multi-character constants (e.g.
'xy'
) are valid, although rarely useful — they let one store several characters in an integer (e.g. 4 ASCII characters can fit in a 32-bit integer, 8 in a 64-bit one). Since the order in which the characters are packed into an int is not specified, portable use of multi-character constants is difficult.
相关,C11
, 第 §6.4.4.4/p10 章
An integer character constant has type
int
. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g.,'ab'
), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined. [....]
关于c - 多字符字符常量在 C 中有效吗?也许在 MS VC 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40609590/