Short circuit evaluation with both && || operator

前端 未结 2 637
小鲜肉
小鲜肉 2020-12-01 20:12

I know what is short circuit evaluation in C.

a && b (operand b is not checked if a = 0)

a || b (operand b is not checked i

相关标签:
2条回答
  • 2020-12-01 20:46

    The expression 5 || 2 && ++x is equivalent to 5 || (2 && ++x) due to operator precedence.

    The run time evaluates the expression 5 || 2 && ++x from left to right.

    As we know in OR if first condition is true it will not check the second condition.
    So here 5 evaluated as true and so (2 && ++x) will not be performed.

    That's why x will remain 0 here.

    0 讨论(0)
  • 2020-12-01 20:49

    Correct. The expression is short circuited. You can test it with this.

    if(5 || ++x) {
      printf("%d\n",x);
    }
    
    0 讨论(0)
提交回复
热议问题