Evaluation of the following expression

后端 未结 3 1404
别跟我提以往
别跟我提以往 2021-01-26 03:25

The following code snippet:

int i=-3,j=2,k=0,m;

m=++i && ++j || ++k;

can be evaluated using two concepts,I believe:

1.Since ++

相关标签:
3条回答
  • 2021-01-26 04:14

    In attempting to be efficient, evaluation of an OR statement (executed from left to right) stops when the LHS is true. There is no need to start evaluating the RHS - there is no concept of "precedence" except within the same group of an expression (when it matters to the value of the expression whether you first do A or B. Example: 5 + 3 * 2 should evaluate to 11. But in evaluating ( 5 + 6 > 3 * 2) it doesn't matter whether you do the addition before the multiplication - it doesn't change the result of the comparison. And in practice this gets evaluated left-to-right. Thus you get the result you observed.

    See also this earlier answer

    0 讨论(0)
  • 2021-01-26 04:17

    Oli is right... You're confusing precedence with evaluation order.

    Precedence means that the expression is interpreted as:

    m = ((((++i) && (++j)) || (++k));
    

    As opposed to, say:

    m = (++(i && ++(j || (++k)))
    

    Precedence doesn't change the fact that the LHS of the || operator will always be evaluated before the RHS.

    0 讨论(0)
  • 2021-01-26 04:25

    The && and || operators force left-to-right evaluation. So i++ is evaluated first. If the result of the expression is not 0, then the expression j++ is evaluated. If the result of i++ && j++ is not 1, then k++ is evaluated.

    The && and || operators both introduce sequence points, so the side effects of the ++ operators are applied before the next expression is evaluated. Note that this is not true in general; in most circumstances, the order in which expressions are evaluated and the order in which side effects are applied is unspecified.

    0 讨论(0)
提交回复
热议问题