gpt4 book ai didi

你能解释一下这个—"the rules involving mixed types of operands do not apply to the shift operators"

转载 作者:行者123 更新时间:2023-11-30 15:29:55 25 4
gpt4 key购买 nike

我无法理解以下迈克的 C 书中摘录中的行“移位的结果与移位的结果具有相同的类型(在积分提升之后)”巴纳汉(Section 2.8.2.3)

Importantly, the rules involving mixed types of operands do not apply to the shift operators. The result of the shift has the same type as the thing that got shifted (after the integral promotions), and depends on nothing else.

如果某些东西已经被提升为整数(根据移位运算符使用期间的要求),那么如何将其转换回与原来相同的类型,当然除非它位于赋值的右侧并且是被分配给与整数提升之前相同类型的变量?此外,“涉及混合类型操作数的规则不适用于移位运算符”这句话到底意味着什么?

请阐明问题的两个部分。谢谢。

以下是书中的屏幕截图,分别与使用按位运算符和一般混合表达式期间的提升有关。

enter image description here

enter image description here

最佳答案

这非常简单;移位运算结果的类型是 LHS 操作数的类型。对于大多数二元运算符,结果基于 LHS 和 RHS 操作数,但移位运算符不同。

unsigned char      uc = 0x08;
unsigned short us = 0x0008;
unsigned int ui = 0x00000008;
unsigned long long ul = 0x0000000000000008;

(我假设这个答案是 sizeof(unsigned int) == 4。如果不同,细节就必须改变,但概念保持不变。)

现在考虑一些表达式:

uc + uc;

两种类型都转换为 int结果是int .

us + us;

同样,两种类型都转换为 int结果是int .

us + ui;
ui + us;

us 中的值转换为unsigned int结果是unsigned int (请注意,以前的值已转换为 signed int 又名 int )。

ui + ul;
ul + ui;

这两个表达式都转换 uiunsigned long long结果是unsigned long long 。请注意,这些表达式是对称的;结果的类型(实际上,对于 + 运算符,结果的值)并不取决于哪个值位于运算符的左侧,哪个值位于运算符的右侧。

普通操作就到此为止;现在轮类怎么样?

uc << uc;

LHS 转换为 int通过通常的算术转换,结果是 int .

us << us;

这个结果也是 int .

ui << ui;

此结果是 unsigned int .

ul << ul;

此结果是 unsigned long long 。但是混合类型怎么样?

uc << ul;   // Result: int
ul << uc; // Result: unsigned long long
us << ui; // Result: int
ui << us; // Result: unsigned int
ui << ul; // Result: unsigned int
ul << ui; // Result: unsigned long long

LHS 操作数的提升类型控制结果的类型。对于短于 int 的类型,结果是int ;对于其他类型,类型是 LHS 操作数的类型。

这就是你引用的全部意思。

关于你能解释一下这个—"the rules involving mixed types of operands do not apply to the shift operators",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25962388/

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