views:

669

answers:

12

Why ++x || ++y && ++z calculate ++x firstly?

However,Operator && is higher than ||?

+2  A: 

++ has highest priority of all, as its pre increment. This means that the value of the result of this operation is passed to binary operators. However the interesting thing is the short circuit of ++x or'ed with the rest. If ++x is true then the rest may not be done at all.

Preet Sangha
+34  A: 

Huh?

If you're saying that && binds tighter than || (which is true), the expression is then equivalent to

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

Since || short-circuits, it needs to evaluate the left-hand side first.

If you mean that it ought to be equivalent to

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

The same is still true, since && also short-circuits, meaning the or needs to be evaluated first, which in turn makes ++ the first thing to evaluate.

unwind
Cedric H.
halfdan
@Cedric: I'm not sure, I parsed it that way first too. It's not well-worded.
unwind
djeidot
JeremyP
John Bode
A: 

It has been a long time since I have worked with C, but if I remember correctly, ++ is a unary operator which always has precedent over binary operators. Makes sense if you think about it.

Hugo Estrada
A: 

You shouldn't rely on perceived operator priority if your operations are order sensitive, as different compilers (and differing versions of the same one) could implement priorities differently.

Eitherway b definition ++x means that x must be incremented BEFORE it is used and so you would expect it to be given high prioroty in execution.

ChrisBD
Irrelevant; there's nothing implementation-defined in this example.
R..
@R: Now that you commented and down voted on everyones posts about that thing you can maybe write your own answer and explain ...
Cedric H.
@Cedric: Except that there are a good many wrong answers here, some of which have been corrected, and R.'s answer is a good one.
David Thornley
@David: I think my comment was before R.'s answer (or at least I didn't see it at that moment).
Cedric H.
+19  A: 

Since && has higher precedence than ||, it means your expression is equivalent to:

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

Thus, before the program even begins evaluating the result of &&, it has to evaluate ++x to determine whether the right-hand operand of || should even be evaluated (logical binary operators are "short-circuiting", meaning they do not evaluate the right-hand side if the left-hand side is sufficient to determine the result). There is nothing fishy or compiler-specific here. The behavior of this expression is specified exactly by the C standard and will be the same on any compiler. It would even work if x, y, and z were all the same variable, since || and && introduce sequence points.

R..
+1 for the sequence point point
jk
Thanks jk. Actually I just changed my whole answer because I had the precedence wrong, but hopefully the new version is at least as detailed and more accurate.
R..
R.., I'm astounded that you got this wrong at first (I expect better of you!), but the new answer is spot on =)
Stephen Canon
Haha thanks Stephen.
R..
A: 
pmg
Those codes don’t do the same thing! They are **not** equivalent.
Konrad Rudolph
The original code deserves to be shot :)
pmg
@pmg: your answer is nevertheless misleading. And while the original code is certainly a no-go, similar problems arise from code that is, in its turn, completely sensible.
Konrad Rudolph
@pmg: yes, the original code is horrible, but in the original case for any non 0 value of x after increment ++y and ++zz wouldn't be executed at all. Even if a code is poorly written it does not mean you can replace it with a code doing something else.
kriss
+11  A: 

There are horribly wrong answers here.

The order of evaluation of this expression is not implementation dependent. It is well-defined!

Since && binds higher than ||, this expression is equivalent to ++x || (++y && ++z). Furthermore, both && and || are short-circuited, so if the left-hand side of the expression suffices to determine the value, the right-hand side is never evaluated.

When is this the case? Well, we know that False && a always resolves to False, no matter the value of a, in particular even if a is not a single value but instead a complex expression. Therefore we don’t evaluate a at all. Likewise, True || a always resolves to True.

This results in a very definite order of evaluation in this example: first ++x, then (if at all) ++y and then (again: if at all) ++z.

Konrad Rudolph
Just a style note on your answer: I was confused at first by your use of "x" in the paragraph beginning "When is this the case?" because "x" is also part of the example, I thought you were referring to the same "x". Had to read that twice.
Jay
@Jay: thanks for the comment. Will fix.
Konrad Rudolph
A: 

hi Thompson this is not just a statement in C, it an expression and you used pre-increment operators. when you use ++ operator in an expression, it will executed before the expression gets execute.

so in your statement ++x || ++y && ++z first x, y, and z gets incremented after that only the as usual operations gets started.

PRS
wrong! - read R.'s answer above
Andy Dent
+8  A: 

Unwind, R, and others have explained what really happens. So let me just add:

The premise of your question is faulty. The fact that the "&&" has higher precedence doesn't mean that operands that surround it must be evaluated before any operands in the expression with lower precedence. Even where the special case short-circuiting of "||" and "&&" this wouldn't necessarily be so.

For example, consider "a=b+c+d*e;" "*" has higher precedence than "+", but that doesn't mean that d*e must be evaluated before b+c. It just means that it must be evaluated before we add the product to the expression as a whole. A compiler could evaluate this expression as temp1=d*e, temp2=a+b, a=temp1+temp2. or it could evaluate temp1=b+c, temp2=d*e, a=temp1+temp2. Both would be equally valid.

With the short-circuiting behavior of || and &&, there are some additional restrictions placed on order of evaluation.

As a side note: In general I would avoid writing code like this. I can easily see another programmer trying to read this code getting confused about just when the increments will happen and when they won't. Well, maybe if you used real variable names it would not look so bizarre.

I do occasionally rely on short-circuiting preventing side effects. Like "if (!eof() && readNextInt()>0". I'm relying on the short-circuit to prevent reading if we're already at end of file. Or "if (confirmDelete==YES && deleteEntry()!=-1)", I'm relying on the first test to short-circuit on false so I don't do the delete when I shouldn't. But these examples seem pretty straightforward to me, I'd hope any competent programmer would see what I'm doing. But when the examples get cryptic, I think it needs to be broken out. Consider "if (customerType==RETAIL || lastDepositAmount()>100.00)". If lastDepositAmount() had a side effect, then if customerType is retail this side effect will never happen. I don't think that would necessarily be obvious to a reader. (Partly because the function name implies that it is retrieving data and not performing any update, and partly because there is no obvious relationship between the customer type and the amount of a deposit -- these sound like two independent things.) Admittedly, this is subjective. But when in doubt, choose simplicity and clarity over a trivial performance improvement. Always choose simplicity and clarity over "hey this is a way cool use of an obscure feature, anyone reading this will be impressed at how smart I must be to understand the language well enough to do this".

Jay
+1 for catching the OP's possible underlying misunderstanding.
R..
+2  A: 

The operators are evaluated using the Polish tree datastructure, as in the diagram, and it's a depth-first evaluation algorithm. Let's give names to the operations: A = ++x B = ++y C = ++z D = B && C E = C || D Evaluation order: A, B, C, D, E. Of course, C has an optimisation and if A is true, then E will be evaluated as true without evaluating B C and D. Similarly, if B is false, then C won't be evaluated to optimize the evaluation speed.

alt text

Lajos Arpad
+1 for fancy diagram :-)
R..
Thank you, I like your answer too. Understanding the Polish tree and optimizations is key to understanding the answer for the question. That's why I've made the diagram. Note that it's not perfect because ++ is a node of the tree and x, y or z is the child of the given operation, but I sacrificed 100% correctness to make sure that we're talking about ++x and not x++.
Lajos Arpad
A: 

Top two answers explain it rather well... I'd point out that || is "OrElse".

Right side doesn't get touched if left side is true. Left side of && (AndAlso) doesn't get touched if right side is false.

If you want both sides to get incremented, use | and &.

http://msdn.microsoft.com/en-us/library/2h9cz2eb(v=VS.80).aspx

A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending on the result of another expression. If the result of the first expression evaluated determines the final result of the operation, there is no need to evaluate the second expression, because it cannot change the final result. Short-circuiting can improve performance if the bypassed expression is complex, or if it involves procedure calls.

MSDN has tables that show how parts are "(not evaluated)".

Why touch part 2, if Part 1 pre-determines the outcome deterministically?

WernerCD
+1  A: 

Precedence and order of evaluation are not the same thing, especially in this case. All precedence tells you is that the expression should be parsed as

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

IOW, it means that the expressions being OR'd together are ++x and (++y && ++z). It does not mean that (++y && ++z) will be evaluated before ++x.

For the logical operators || and &&, evaluation is always left-to-right (Online C Standard, Sections 6.5.13 and 6.5.14). For any expression

a || b

a will be completely evaluated; b will not be evaluated unless the result of a is 0 (think of a standing in for ++x and b standing in for ++y && ++z). Similarly, for any expression

a && b 

a will be completely evaluated; b will not be evaluated unless the result of a is not 0.

So for your case, the expression ++x is evaluated first. If the result is 0, only then will ++y && ++z be evaluated.

|| and && are special in that the order of evaluation is guaranteed to be left-to-right. That is not true of the bitwise or arithmetic operators. For example, in the expression

++x + ++y * ++z

the expressions ++x, ++y, and ++z may be evaluated in any order; all precedence tells you is that the result of (y+1) * (z+1) will be added to the result of x+1.

John Bode