Link to home
Start Free TrialLog in
Avatar of neethu
neethu

asked on

precedence of && and || ,please help

main()
{
        int x,y,z;
        x=y=z=1;
        ++x||++y&&++z;
        printf("x=%d y=%d z=%d \n",x,y,z);


}
the anzwer given by gcc is
x=2 y=1 z=1;
but && has more precedence than || right , so ++y && ++z should be evaluated first and ++x will not be evaluated due to short circuit evaluation therefore anzer shold be
x=1 y=2 z=2 where did i go wrong ,, please help me ,can u give me some links from where i can study these things ,, i am novice to this compiler thing.
love
neethu
ASKER CERTIFIED SOLUTION
Avatar of akshayxx
akshayxx
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of neethu
neethu

ASKER

then what is the use of precedence of && over || ??
i do understand short circuit evaluation. but as u tell what ever be the operator boolean expr will always be evaluated from left to right. then what is the use of && over ||
>>but && has more precedence than || right
i dont think so. both have equal precedence.. the expression is evaluated from left to right
that is true akshayxx.
& means bitwise AND white ! mean bitwise OR.
&& means logical AND while || means logical OR


what this means is that if u use the statement 1 | 2
then

00000001 --> 1
00000010 --> 2

becomes

00000011

while 2 & 3
00000010 --> 2
00000011 --> 3

becomes
00000010

while the logical operators are means of joining statements together to check the validity.
say you wnat o know whether both a and b are greater that 0 then u would say

if a > 0 && b > 0 then
printf("both greater .. DUH!!\n");



»dsine


Avatar of neethu

ASKER

  -                subtract
   ------------------------------------------------------------------
   <<                left shift                                left-to-right
   >>                right shift
   ------------------------------------------------------------------
   <                less than                                left-to-right
   <=                less than or equal
   >                greater than
   >=                greater than or equal
   ------------------------------------------------------------------
   ==                equal left-to-right
   !=                not equal
   ------------------------------------------------------------------
   &                bitwise AND                                left-to-right
   ------------------------------------------------------------------
   ^                bitwise XOR                                left-to-right
   ------------------------------------------------------------------
   |                bitwise OR                                left-to-right
   ------------------------------------------------------------------
   &&                logical AND                                left-to-right
   ------------------------------------------------------------------
   ||                logical OR                                left-to-right
   ------------------------------------------------------------------
   ?:                conditional                                right-to-left
   ------------------------------------------------------------------
   =                assignment operators                        right-to-left


hai akshay,
 see this
love
neethu
SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Your answer is really good "sunnycoder"

thank you Sys_Prog :o)
neethu : one last (i hope) resonse.
you think of && and || as if they were & and |.
its NOT the same thing.
if you really want to know the difference,just look in the HELP files of C...
i thik you have been given many appropriate answers here...
yair
*****************************
copying from my posts in your other thread
>++x||++y&&++z;

is broken donw to

 ( (++x) || ( (++y) && (++z) ) ) ;
*****************************

IMO as for the compiler is concerned.. the second form is not actually "broken down" form.. its actually more 'complex' form ..more symbols u have more complex the expression is for the compiler to parse and hence evaluate :)..
yes u can always say that its the representation as if it were bracketed according to operator precedence..

ok here is the detailed explaination of  HOW precedence was used..
after that expression is evaluated left to right,, precedence is just used to 'group' variables/expressions together...or say in building up the parse tree.. above parse tree will look like  
     ||
 A      &&
        B    C
so once the tree is built the evaluation goes from left to right.... and due to short circuit properties of the || , and since A is true , right subtree of || is not required to be evaluated
 had || had precedence over && , the only difference would have been in the parse tree, which then would look like
            &&
         ||     C
      A    B
again in this case, after the parse tree is built, evaluation will start from A, then  if required B will be evaluated, and C must be evaluated here..
u can 'command' the compiler to generate the above tree by bracketing up the following way
(++x || ++y) && ++z;
result of this would be
x=2, y=1,z=2;

So dont worry operator precedence was very much used in the case mentioned.. had compiler chosen || above &&, the result would have been what i explained in the second case.. So it was combined result of precedence and short circuit stuff both.


also one serious  point to add, in above expression there is no ambiguity, so it seems perfectly safe according to C standards. so dont worry all compilers will  give same results ,

one example of the ambiguity is, when one variable is being modified more than once in the expression.
like x=x++*z++ - k*++x;


hope this cleared ur doubts
akshay
>seems perfectly safe according to C standards.
I agree
>so dont worry all compilers will  give same results ,
I strongly disagree ... the result will be same only as far as value of expression is concerned ... I can have a C standard compilant compiler who will evaluate all the subexpressions before producing the results ... compiler may or may not use short circuit evaluation (most do use it due to efficiency) and yet be C standard compliant as I pointed out above

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Neethu, close the question by accepting the answer.

CleanupPing, What's the policy if the author doesn't come back? does he/she lose the points and no one gets them? just being curious.
jhshukla,

CleanupPing is a robot :o) ... When cleanupPing posts this message. the asker should respond by closing the question. The participating experts should leave recommendations expressing their thoughts about final disposition of the question. 7 days from the day CleanupPing posted, a cleanup volunteer (CV) will post his/her recommendation (taking into account all recommendations from the participating experts)  and 7 days after he/she has posted a recommendation, a moderator will finally close or delete the question (if the asker hasn't done so by then)
aaaaaaaw..... I feel so embarrassed.
it happens to everyone of us ;o) ... so dont feel embarrased ... evaluate the question and leave your recommendations
i would recommend this to be split between the experts involved.
Split is acceptable.
No comment has been added lately and this question is therefore classified abandoned.

If asker wishes to close the question, then refer to
https://www.experts-exchange.com/help/closing.jsp

Otherwise, I will leave a recommendation in the Cleanup topic area that this question is:
PAQed with A grade and 175:75 split between sunnycoder and akshayxx

Please leave any comments here within the next seven days. It is assumed that any participant not responding to this request is no longer interested in its final disposition.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Sunny
EE Cleanup Volunteer
I've been visiting this topic area regularly. This response is to indicate that I AM concerned about the final disposition. The 175:75 split between sunnycoder and akshayxx seems a little ad hoc. Okay, so long as neethu has no comments/opinions, any decision is acceptable.
kjmathew,

I shall be submitting this recommendation for review by a mod, Pls post your recommendation.

Sunny.
as for my opinion, My comment ( the one with some tree explanation..) with the jshukla's comment(Date: 10/05/2003 12:40PM IST)  address the original query more clearly, which was about precedence and accosiativity. and ofcourse the short circuit evaluation, which eveyone made a point of.
also i must say that, that comment from jshukla had as much quality information as the other comparatively longer ones.
my recommendation would be
sunny 100
akshayxx 100
jshukla 50 ( sorry, dear jhukla, u need to explain a bit more.. remember school days, where u need to write 10 lines to explain a simple linear equation solution.  :-P j/k)

or (85,85,80) in that order.

My arguments as a participant:

>that comment from jshukla had as much quality information as the other comparatively longer ones.
>address the original query more clearly, which was about precedence and accosiativity
>>1. precedence is for grouping
>>2. associativity is the order in which they are evaluated (from left or right)
>>3. parentheses can be used to override precedence not associativity
>>&& and || have same associativity. so evaluated from left to right and cosequently the output.
>>x++ is true -> nothing more required -> y,z unchanged

Since I have authored some of the "comparatively longer ones", I think I need to clarify a few things. I fail to see how this comment takes into account the very first point mentioned "precedence" (which incidentally happens to be the subject of the question) .. perhaps my browser is playing some tricks !!!

The correct answer to the question was
"The compiler is free to evaluate such expressions in any order, if the compiler can guarantee a consistent result" for the expression .... the order of evaluation of expression is not strictly bound by precedence and associativity which was pointed out by nobody else except me

and was not
>and ofcourse the short circuit evaluation, which eveyone made a point of.
If it were short circuit evaluation and precedence, the question would not have been asked
from the question itself
"but && has more precedence than || right , so ++y && ++z should be evaluated first and ++x will not be evaluated due to **short circuit evaluation** therefore anzer shold be "

The reason I recommended this split "175:75 split between sunnycoder and akshayxx" was because of the efforts put in by akshayxx for a constructive discussion, else I strongly feel that my answer is more appropriate.

Submitting to mods for review
from sunny:
The correct answer to the question was
"The compiler is free to evaluate such expressions in any order, if the compiler can guarantee a consistent result" for the expression .... the order of evaluation of expression is not strictly bound by precedence and associativity which was pointed out by nobody else except me

sunny,
The order of evaluation is never ever determined by precedence (in practice). Any machine code generated following precedence of order of evaluation would have to perform enough recursion to slow down the program (my wild guess) about 8-10 times. btw, I agree that associativity mere influences the order of evaluation but only in logical expressions. For arithmetic exprs, changing associativity produces different results (pretty easy to see). Every expert (except sys_prog and yabelson) mentioned short circuit evaluation (the correct reason).

kjmathew = 50
jhshukla = 60
akshayxx = 65
sunny = 75
------------
total 250
>The order of evaluation is never ever determined by precedence (in practice). Any machine code generated following
>precedence of order of evaluation would have to perform enough recursion to slow down the program (my wild guess)
>about 8-10 times.
I would like to see some arguments/links to substantiate this

>btw, I agree that associativity mere influences the order of evaluation but only in logical expressions. For arithmetic exprs,
>changing associativity produces different results (pretty easy to see).
I wonder if anyone else made that point

>Every expert (except sys_prog and yabelson) mentioned short circuit evaluation (the correct reason).
take a look at the expression again, keeping in mind the precedence and associativity, apply short circuit evaluation and check the result ... To refresh, from the original question post

"but && has more precedence than || right , so ++y && ++z should be evaluated first and ++x will not be evaluated due to short circuit evaluation therefore anzer shold be
x=1 y=2 z=2 where did i go wrong "

I would like you to figure out the answer to this.
well.. i just wasted last 15 minutes of mine by summing the whole thing up, and then this dial-up connection played its trick on me and i lost whatever i wrote..
anyways i'll try to summarise what i said..

1. Asker's primary concern was that s/he was having a feeling that operator Precedence was not playing its part.
2. your comment highlighted the fact that associativity can be compiler dependent.
3. I clearly described that precedence was very much playing its role...by helping build the unambiguous parse tree needed for evaluation of the expression.

 regarding jshukla's comment that  i pointed out, to be deserving some credit..i dont see anything wrong with any part of it.

>>1. precedence is for grouping
whats wrong with this.
>>2. associativity is the order in which they are evaluated (from left or right)
thats also true again ... notice that he didnt make a rule that it has to be left to right..
>>3. parentheses can be used to override precedence not associativity
this is also perfect..
>>&& and || have same associativity. so evaluated from left to right and cosequently the output.
this again makes sense .. meaning associativity should not vary within a compiler or an expression.. it will be either L2R OR R2L..
putting them all together.. he summarised all the points that are necessary for unambiguous parsing and evaluation of expression..within a given compiler..

so
1. Sunny's comment didnt highlight the use precedence..
2. i erred with assuming associativity to be L2R only..
3. jshukla summarised the points..


hence i believe  it should be distributed more evenly among the experts i mentioned.
akshay



I shall leave it up to mods to review and assign points ... would just like to contend

>1. Sunny's comment didnt highlight the use precedence..
Please see
Comment from sunnycoder
Date: 10/03/2003 12:17PM IST
in that comment(( Date: 10/03/2003 12:17PM IST))
the only thing that you(sunny) said about precendence was .........
<<<", it is a common misperception that precedence and associativity rules dictate (rather than merely influence) order of expression evaluation, the order in which operators are applied to their operands. ">>>

it doesnt say how the asked problem is following the precedence rules...
it doesnt tell whats the role of precedence in evaluating the expression .. and the qeustion under discussion is perfectly following those rules.