c - 多字符字符常量在 C 中有效吗?也许在 MS VC 中?

标签 c visual-c++ char

在查看一些旨在在 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/

相关文章:

c++ - 没有将 char 数组作为输出?

c - strcpy() 将字符串从一个结构复制到另一个结构

c++ - 调用头文件中声明的函数

c++ - MFC:嵌入式子对话框未显示在父对话框中

c++ - 在模板函数中声明依赖于未知类型的变量

Java Switch 语句 - "or"/"and"可能吗?

c - "Indexed"C 中的数组函数参数

c - 如何从 Linux 存储库调用此方法?

c - 如何求 1,2,..... 直到 n(输入编号)的阶乘总和

C++ 从一个字符中获取指定的部分