I have a code snippet in Java:
int y = ++x * 5 / x-- + --x;
So my confusion was since x--(postfix) has higher precedence than ++x(prefix) operator so x-- should be executed first then ++x.But a book states otherwise.Am I right in my thinking?
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
In the absence of any structures being indexed using these variables, which is where prefix and postfix operators really come into their own, I'd suggest that this is a largely academic exercise.
Speaking pragmatically; take control of the expression and add brackets to make the order explicit, if only to save your sanity. It also eliminates any possibility of confusion and/or portability issues (new compiler, [slightly] different operator precedence, nasty bug).
Precedence determines which calculations will happen. Evaluation is done left to right among things that could occur "at the same time" in Java.
It is equivalent to the following
int t1 = ++x; int t2 = x--; int t3 = --x; int y = t1 * 5 / t2 + t3;
If you have to care about either of those things, you've got bad code. Change it so that the reader doesn't have to consult their rulebook to know what is happening.