gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:36:49 25 4
gpt4 key购买 nike

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 maybe used:

— An object or expression with an integer type whose integer conversion rank is lessthan 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 integerpromotions.

(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com