operator precedence

Naresh Gunda

Ranch Hand

Posts: 163

posted 11 years ago

Hi, How to evaluate a boolean expression having '&&' and '||' operators. I know '&&' operator is having more precedence than '||'. In the folloing program first i applied '&&' operator, but the program's output is different. can any one of u explain me pls.

step 3: for any operator to be applied both operands must be first evaluated. so as evaluation is from left to write first 2 + (3 * 4) needs to be evaluated. 2+(3*4)=> 2+12=14 then 14 - (1*7)=> 14 - 7 = 7

so final result is 7.

so in your code the grouping will be as follows (a = true) || (b = true) && (c = true) => ((a=true) || ( (b=true) && (c=true) )) as evaluation will be from left to write (a=true) is evaluated first which results in true and "a" is assigned value true . as || is short hand operator if left operand is true, right operand is not evaluated.

so output will be true, false , false as default values for b and c are false.

manogna edintipal

Ranch Hand

Posts: 51

posted 11 years ago

The && and || are short circuit logical opeartors

these opearators first evaluates the left side expression (i.e., (a = true) || ) .If this is enough to evaluate the result of the whole expression these oparators didn't evaluate the expression which is in right side to the operator(i.e.,( b = true)&& (c = true)

the whole expression is evaluated from left to right

Sanju

Naresh Gunda

Ranch Hand

Posts: 163

posted 11 years ago

Thank You Deepthi

From this, i understood that, we must rewrite the given expression using (),based on the precedence of the operator.

step 3: for any operator to be applied both operands must be first evaluated. so as evaluation is from left to write first 2 + (3 * 4) needs to be evaluated. 2+(3*4)=> 2+12=14 then 14 - (1*7)=> 14 - 7 = 7

so final result is 7.

so in your code the grouping will be as follows (a = true) || (b = true) && (c = true) => ((a=true) || ( (b=true) && (c=true) )) as evaluation will be from left to write (a=true) is evaluated first which results in true and "a" is assigned value true . as || is short hand operator if left operand is true, right operand is not evaluated.

so output will be true, false , false as default values for b and c are false.

Please explain why in KM book there is phrase

The evaluation order also respects any parentheses, and the precedence and associativity rules of operators.

Doesn't this means that operands of && operator must evaluated before operands of || , as && have higher precedence? [ January 12, 2006: Message edited by: Dmitryi Neverov ]