0

We have an expression

int x,y,z;
x=y=z=2;

y=++x || --y;

printf("%d %d",x,y);

It gives x=3 and y=2 as output but i think here we have 4 operators : ++, --, || and =.

We know ++ and -- have the highest priority so they must be evaluated first, followed by || and then =.

Also we know ++ and -- have the same priority so we use associativity, and in this case it is right to left. So I think first --y will be evaluated which gives y=1, then ++x which should give x=3 and then || should be evaluated.

Why am I getting different answer from my machine? Thank You.

nodakai
  • 7,773
  • 3
  • 30
  • 60
Navdeep
  • 823
  • 1
  • 16
  • 35
  • 2
    Precedence has nothing to do with order of evaluation. It's undefined behaviour anyway, if `--y` is evaluated. What you're actually looking for in this case is short-circuit evaluation since `--y` is, in fact, not evaluated here. – chris Aug 28 '14 at 18:27
  • Please stop writing rubbish code with complex, bracketless expressions and dubious behaviour. It will get you fired. – Martin James Aug 28 '14 at 20:58

1 Answers1

1

The precedence of operartor is independent of order of evaluation. Note that Order of evaluation of subexpressions is independent of both associativity and precedence.

The order in which operands in an expression are evaluated is unspecified in C. The only guarantee is that they will all be completely evaluated at the next sequence point.

In your case x++ is evaluated where --y is not evaluated which is creating the problem for you.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • This particular case is not undefined because `++x` is "true". – chris Aug 28 '14 at 18:30
  • @chris:- Yes got that. Thanks for pointing that! – Rahul Tripathi Aug 28 '14 at 18:31
  • please explain it clearly. What is the need of precedence and associativity then? Why they say when operators have equal precedence we need to move Right to left for evaluation?If you can give example then it will b more convenient to understand. – Navdeep Aug 28 '14 at 18:39
  • @Navdeep:- The linked answer has got a very good explanation about the same. No need to reinvent the wheels. Please go through that and if you still face any problem do let me know! – Rahul Tripathi Aug 28 '14 at 18:41
  • @Navdeep:- `Attempting to use a variable to which a pre/post increment/decrement has been applied in any other part of an expression really does give completely undefined behavior. While an actual crash is unlikely, you're definitely not guaranteed to get either the old value or the new one -- you could get something else entirely.` – Rahul Tripathi Aug 28 '14 at 18:42
  • @Navdeep:- Also check this:- http://www.eskimo.com/~scs/readings/precvsooe.960725.html You will find it helpful. – Rahul Tripathi Aug 28 '14 at 18:44