Let us see what we have - we basically have an expression "A || B && C".

We also know the following:

1. "||" and "&&" are both considered sequence points

2. The "&&" has precedence over the "||" operator

3. The C/C++ languages use minimal evaluation principle when evaluating the
logical expressions (see the wiki article for this:
http://en.wikipedia.org/wiki/Short-circuit_evaluation)

 

Now, let us see how the "A || B && C" will be evaluated given all the above.

Since the "&&" has higher priority in the evaluation process, the

"B && C" will be given the priority. But, since the "&&" is a sequence
point,

it means that all the sub expressions on its left will have to be evaluated
first

and their artifacts are complete, i.e. the "A || B". In our case, it is "++i
|| ++j". Here, the "++i" evaluates to true and the "++j" does not

get evaluated at all due to the fact that we already have an expression that
has

already evaluated to true (minimal evaluation principle). And the same
minimal evaluation principle 

will be applied when evaluating the initial expression "B && C", effectively
skipping

the evaluation at all. To recap, we can see that the only actual evaluation
happens

for the expression "A || B", in our case - the "++i || ++j", which in its
turn

short circuits to evaluating the "++i" only.

 

Rgds,

Ashot

From: [email protected] [mailto:[email protected]] On
Behalf Of enchantress
Sent: Sunday, June 17, 2012 11:20 AM
To: [email protected]
Subject: [algogeeks] Precedence or Associativity

 

Consider the following code:

 

int i=0,j=0,k=0;

int x = ++i || ++j && ++k;

 

O/P: x=1,i=1,j=0,k=0

 

Now, the logic operators are evaluated left to right and if the output is
determined by left hand side expression right hand side is not evaluated.

But the precedence of && > || hence ++j&&++k should be dealt with first.The
output says once ++i evaluates to 1 further expression is not considered.

Can anyone explain this anomaly?

As of i know associativity is considered when precedence of operators is the
same eg:

x*y/z will be evaluated left to right.

-- 
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/algogeeks/-/rr41g1Q8q38J.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to