Unsigned 和 Signed 在同一个表达式中:适用什么规则?
Unsigned and Signed in same expression: What rules apply?
我对标题中提到的问题感到困惑。有人告诉我,在涉及两种类型变量的表达式中,有符号会转换 to/interpreted 为无符号。但是,如以下代码片段所示,情况并非总是如此。
代码:
unsigned int x = 1;
int y = -20;
printf("Right shift = %x, %d\n", y>>x, y>>x);
printf("If = %x, %d\n", y < x, y < x);
结果:
Right shift = fffffff6, -10
If = 0, 0
if 语句 returns 预期的 0、-20 被转换为一个非常大的无符号整数,但是移位表达式 returns -10,这表明算术移位而不是逻辑移位具有发生在。 x 被解释为有符号而不是 y 被解释为无符号。
谁能帮我解决这个问题?
在这个表达式中
y>>x
(C 标准,6.5.7 移位运算符)
3 The integer promotions are performed on each of the operands.
这意味着 y
的类型为 int
而 x
的类型为 unsigned int
两者都不会发生转换(提升)。并且
- ...The type of the result is that of the promoted left operand.
因此表达式的结果具有类型 int
- 操作数的类型 y
。由于 y
具有负值,因此
- ...IfE1 has a signed type and a negative value, the resulting value is
implementation-defined
至于这个表达
y < x
然后就是常用的算术转换。这两个操作数具有相同的等级,因此类型 int
的操作数 y
被转换为类型 unsigned int
并且其作为类型 unsigned int
的对象的二进制表示更大比操作数 x
的二进制表示。
来自 C 标准 *6.3.1.8 通常的算术转换)
Otherwise, if the operand that has unsigned integer type has rank
greater or equal to the rank of the type of the other operand, then
the operand with signed integer type is converted to the type of the
operand with unsigned integer type.
我对标题中提到的问题感到困惑。有人告诉我,在涉及两种类型变量的表达式中,有符号会转换 to/interpreted 为无符号。但是,如以下代码片段所示,情况并非总是如此。
代码:
unsigned int x = 1;
int y = -20;
printf("Right shift = %x, %d\n", y>>x, y>>x);
printf("If = %x, %d\n", y < x, y < x);
结果:
Right shift = fffffff6, -10
If = 0, 0
if 语句 returns 预期的 0、-20 被转换为一个非常大的无符号整数,但是移位表达式 returns -10,这表明算术移位而不是逻辑移位具有发生在。 x 被解释为有符号而不是 y 被解释为无符号。
谁能帮我解决这个问题?
在这个表达式中
y>>x
(C 标准,6.5.7 移位运算符)
3 The integer promotions are performed on each of the operands.
这意味着 y
的类型为 int
而 x
的类型为 unsigned int
两者都不会发生转换(提升)。并且
- ...The type of the result is that of the promoted left operand.
因此表达式的结果具有类型 int
- 操作数的类型 y
。由于 y
具有负值,因此
- ...IfE1 has a signed type and a negative value, the resulting value is implementation-defined
至于这个表达
y < x
然后就是常用的算术转换。这两个操作数具有相同的等级,因此类型 int
的操作数 y
被转换为类型 unsigned int
并且其作为类型 unsigned int
的对象的二进制表示更大比操作数 x
的二进制表示。
来自 C 标准 *6.3.1.8 通常的算术转换)
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.