gpt4 book ai didi

c - 为什么用 C 中的 && 对值和条件进行位移后表达式为真

转载 作者:行者123 更新时间:2023-12-05 01:05:20 24 4
gpt4 key购买 nike

看一下例子:

unsigned char c = 64; /* 0100 0000 */
c = (c << 2 && 512); /* 512: 10 0000 0000 */

如果我将 c 向左移动两次,我应该从 0100 0000 (64) 到这个 0001 0000 0000 (256)。所以我的 8 位字符 c只有零。最后,我想知道为什么表达式 (c << 2 && 512)是真 (1) 而不是假 (0),因为我的 c 只有零。

最佳答案

来自 C 标准(6.5.7 位移位运算符)

3 The integer promotions are performed on each of the operands. Thetype of the result is that of the promoted left operand.

所以在这个表达式中

c << 2

对象 c 被提升为 int 类型,结果也具有 int 类型。

由于逻辑与运算符的两个操作数都不等于0,因此整个表达式的计算结果为1

来自 C 标准(6.5.13 逻辑与运算符)

3 The && operator shall yield 1 if both of its operands compareunequal to 0; otherwise, it yields 0. The result has type int.

您似乎将逻辑运算符 AND && 与按位运算符 AND & 混淆了。

如果你会写

c = (c << 2 & 512);

那么变量 c 的值为 0。

关于c - 为什么用 C 中的 && 对值和条件进行位移后表达式为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70701193/

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