c - 逻辑运算符 | |在 C 中

标签 c

我很难理解以下代码的行为:

#include <stdio.h>

int main(void)
{
    int i;
    int j;
    int k;

    i = 7;
    j = 8;
    k = 9;
    printf("%d\n", (i = j) || (j = k));
    printf("%d, %d, %d\n", i, j, k);

    return (0);
}

输出:

1
8, 8, 9

问题:

  • 我了解expr1 | |如果 expr1expr2(或两者)具有非零值,则 expr2 具有值 1

  • i的值从7增加到8,因为j 的值被分配给 i 但同样的方式为什么 j 的值没有增加,即使 j = k? 我期待一个

输出

1
8, 9, 9

最佳答案

来自 C 标准(重点是我的):

Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

上述行为通常称为运算符(operator)短路。

在您的示例中,由于 (i = j) 不为零,因此不会评估第二个操作数。

关于c - 逻辑运算符 | |在 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68139943/

相关文章:

c++ - scanf() 是如何工作的?

c++ - libclang/libtooling 处理或关闭所有错误输出

c++ - Valgrind 非法指令 AVX

c - 查找给定字符串的所有可能排列

c - 随机数数组中的变量有问题

ios - 2048 转换为 BOOL 返回 0

c - 判断页面是否在内存中?

c - 在 C 宏中的字符串化之前进行标记串联

c - 将 c 数组作为可变大小的矩阵传递给 fortran

c - 对受我系统的字节序影响的单个整数感到恐惧