简体   繁体   中英

How does operator precedence actually work in this program?

#include<stdio.h>
int main()
{
        int i=-1, j=-1, k=-1, l=2, m;
        m = (i++ && j++ && k++) || (l++);
        printf("%d %d %d %d %d", i, j, k, l, m);
}

I am having confusions about how operator precedence is working in the evaluation of the logical expression in the given program.

The variable m will be assigned 0 or 1 depending on the value of the logical expression that follows it.

The first parenthesis will be evaluated and the overall result of two AND operations will be true or 1 . But, since a short-circuit logical OR is used, the second parenthesis is not getting evaluated.

So, my question is if parentheses have higher precedence that all the other operators in that expression, why is not both the parentheses evaluated first, and then the OR operation performed? That is, why is the output 0 0 0 2 1 and not 0 0 0 3 1 ?

EDIT : What I have asked is somewhat different from this (suggested duplicate) as I am emphasizing on the parentheses enclosing the second operand of OR operator.

Operator precedence comes into effect when there's an ambiguity.

In this case, the spec is quite clear.

The || operator shall yield 1 if either of its operands compare unequal to 0 ; otherwise, it yields 0 . The result has type int .

and, ( emphasis mine )

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.

In your case,

 (i++ && j++ && k++) || (l++);

(i++ && j++ && k++) is the left operand and (l++); is the right operand and the rest should be quite clear. :)

Operator precedence (and associativity) only determines how the expression should be parsed. It is a common mistake to confuse it with order of evaluation of the operands , which is different thing. Operator precedence is rather irrelevant in this example.

For most operators in C, the order of evaluation of the operands is not specified. Had you written true | l++ true | l++ then l++ would have been executed. The "short-circuit evaluation" is the reason why this doesn't happen in your code. The && || operators is a special case, since they explicitly define the order of evaluation. The right operand of || is guaranteed not to be evaluated in case the left operand evaluates to non-zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM