ahhhh a classic question from Khalid and Mughal. Definitely check out the links that Anupam posted. BUT... before you get too wrapped up in it -- go study threads or inner classes instead. Operator Precedence isn't tested on the exam (this is according to Bert Bates himself -- and he should know.
++ or -- if placed _before_ a variable increment or decrement the value before it takes part in the "rest of the calculation". If placed _after_ a variable, increment or decrement after it takes part in the "rest of the calculation". What this means is that if a variable is appearing twice in a statement, the second time it appears, it would have the "updated" value. e.g. int i = 5, j = 2, k; k = i++ + j;
i=6, j=2, & k=7, right? Yes. since i is incremented after i++ is executed, but for understanding point of view, value of i is set to 6 not by the end of the statement, but by the end of when i++ is done .. meaning when it gets to the + operator in the middle. so k = i++ + i;
would give us k=11 .. since i++ would evaluate to 5, but before the expression is further evaluated, i is set to 6 .. so when the right side of the + operator is evaluated & value of i is requested, its 6 .. hence 5+6 would give us 11. value of i by the end of expression would still be 6. now to the main course int k = 1; ++k+k++ + +k;// ++k + k++ + +k Evaluating it from left to right step by step ++k yields 2 & sets the value of k = 2 2 + k++ + +k; k++ yields 2 but sets the value of k = 3 2 + 2 + +k; +k is a simple + Unary operator that has no effect in this case so it yields the current value of k i-e 3 2 + 2 + 3;
equals 7. Hope that helps. please correct me if I'm wrong in my crude explanation.
++ or -- if placed _before_ a variable increment or decrement the value before it takes part in the "rest of the calculation". If placed _after_ a variable, increment or decrement after it takes part in the "rest of the calculation". That isn't quite right. If an increment/decrement is before the variable: 1) update the variable 2) return the updated variable If an increment/decrement is after the variable: 1) return the variable 2) update the variable
As far as this extreme example, I have added parenthesis to show operator precendence: (++k)+(k++) + (+k) ++k return 2, k is now 2 2+(k++) + (+k) k++ return 2, k is now 3 2+2 + (+k) 4 + (+3) 4 + 3 7
hey thomas paul , why did u do the pre-increment first...according to the precedence rules u r supposed to do the post-increment first then start with the left- associative equal precedence of ++k &+k .. paul,we are supposed to follow the rules & arrive at the answer but not from the answer to the question is what i feel. thanks