c - 隐式类型转换 : If one operand is short & the other is char, 将 char 转换为 short?

标签 c char type-conversion short

K&R 指出,如果其中一个操作数是 int,则另一个操作数将被转换为 int。当然,这只是在遵循所有其他规则(如 long doublefloatunsigned int 等)之后。

根据该逻辑,如果另一个操作数是 int,则 char 将转换为 int。但是,如果操作中的最高整数类型是 short 怎么办?

现在,显然我不需要将 char 显式转换为更大的整数,但我确实想知道,ANSI-C 是否处理 charshort 背后是什么? K&R 对此未作任何说明。

比如说,我有以下几行代码:

char x = 'x';
short y = 42;
short z = x + y;

x 会被转换成short吗?还是根本就没有转化?

澄清一下:我不是在询问是否或如何将 char 转换为 short。我只想知道关于隐式类型转换会发生什么。

最佳答案

“整数提升”将在添加之前将它们都转换为 int:

The following may be used in an expression wherever an int or unsigned int may be used:

— An object or expression with an integer type whose integer conversion rank is less than the rank of int and unsigned int.

[...] If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

(ISO/IEC ISO/IEC 9899:1999 (E),§6.3.1.1)

关于c - 隐式类型转换 : If one operand is short & the other is char, 将 char 转换为 short?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7442081/

相关文章:

c - 使用读/写函数在 C 中调整哈希表大小

c - 如何仅区分源文件?

c - C 中的字符串内存分配

java - 如何在 charArray 中的确切位置插入空格 [Java]

reflection - 从 Golang 类型中提取未导出字段的正确方法是什么?

c - 使用 ubuntu 编译 C 源代码时何时使用 -std=c 11

c - 在 Char 数组中查找字符串值

c++ - 是否可以将常规指针转换为指向类字段的指针

java - 将非常大的二进制字符串转换为长字符串

c - 新手 C 程序员如何检测内存泄漏