当我将 short 分配给 char 时会发生什么类型转换?

What type conversion happen when I assign a short to a char?

如果我有以下情况会发生什么类型转换:

short s = 1234;
char c = s;

是否会先将 s 转换为 int,然后将此 int 转换为 char 并分配给 c?或者 s 会直接转换为 char 并分配给 c 吗?

s 不会转换为 int.

此处1 我们正在使用 char 范围之外的值初始化 c。 Plain char 可以是有符号的也可以是无符号的(大多数编译器都有一个开关来切换它)。如果 char 已签名,则相关标准文本位于 [conv.integral]/3:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

"implementation-defined" 意味着你的编译器必须记录这里发生的事情。现代系统的一个常见实现是多余的位将被截断,从最重要的一端开始。

重写此代码使其不依赖于实现定义的行为是个好主意;这样当您在不同的系统上编译它时,行为不会改变。

如果 char 是未签名的,那么上一段涵盖了这种情况:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

所以生成的 char 值将是 1234 - 1024 = 210


1 此 post 假定您使用的是 8 位字节的系统。有一些专门的芯片不是这种情况,在这些系统上,char 可以保持 1234 的值,不需要更改值。