Re: Question on Operator Precedence



Sac <sacindia2000@xxxxxxxxx> writes:

As per my understanding given a C expression higher
precedence operators are evaluated first.

Ah, no. Precedence determines how an expression is parsed.

For example X=Y*3+Z*3;
As * has higher precedence Y*3 and Z*3 gets evaluated 1st
followed by +.

All the precedence rules say is that this means X = (Y*3) + (Z*3); The
compiler can generate code to evaluate this in any order it likes.
Yes, there is (in this case) an obvious one but the compiler need not
do this. In fact, if it knows the value of Y and Z there may be no
multiplication or addition at all. If the compiler can tell that the
result is the same, it is also permitted to add Y and Z and then
multiply by 3.

However when I tried the following example
++x || ++y && ++z;
Y and Z never got incremented.
As ++ operator is of higher precedence I think all
variables should be incremented first followed by || operator.
Please let me know if there are other rules in C while
evaluating an expression other than precedence and associativity.

Precedence and associativity tell us only that this means:

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

The operators || and && are special -- they are two of a very small
set of operators that define the order in which things happen. In
this case, first the left operand is evaluated and only if the result
compares equal to zero is the right and side evaluated.

--
Ben.
.



Relevant Pages

  • Re: Function call evaluation order
    ... How do you propose to explain in terms of precedence and associativity the ... Your expectations have been tuned to match what your compiler does! ... Undefined behavior is behavior that is not defined by the C++ standard. ...
    (microsoft.public.vc.language)
  • Re: short-circuit evaluation and assignment operators
    ... Are you guys saying that whether short-circuit evaluation is ... I get what you're saying. ... and that's because the <<= operator has lower precedence. ... the first value and only evaluating the second value if needed - so ...
    (comp.lang.c)
  • Re: Function order of execution
    ... "An operator with higher precedence is evaluated before an operator ... precedence rules: Let A, B, and C be real variables, like: ... evaluating the operands, not the order in which they are combined. ...
    (borland.public.delphi.language.objectpascal)
  • Re: Operator precedence
    ... When list operators such as print have other operators to their right, ... the list operators have very low precedence relative to the subsequent ... in fact, only the word-based logical operators (not, and, or, ... coincidence that evaluating || first produces the same result; ...
    (comp.lang.perl.misc)
  • Re: precedence of negation and times
    ... about multiplicaiton and negation? ... Negation conventionally has a higher precedence than ... that there are two stages to evaluating such expressions: ...
    (sci.math)