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

标签 c logical-operators bit-shift integer-promotion logical-and

看一下例子:

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. The type 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 compare unequal 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/

相关文章:

Ruby 组合比较运算符 (<=>) 和 min/max/minmax 函数

c - 14 位左对齐二进制补码到带符号的短

c# - 为什么 Java 和 C# 中的逻辑运算符和按位运算符之间存在区别?

c - Bitshift 字符数组

c - A/C编译器是否在编译时执行移位操作?

C初始化数组结构错误

c++ - 为什么无限递归会导致段错误

c - 如何使包含在不同类线程中的全局变量在 c 中安全

c - 使用 pthreads 时仍然可以访问的字节数

javascript - react 类型错误: Cannot read property 'length' of undefined