In Mughal p56 Review Question 3.7, you are asked to evaluate the following expression with k initialized to 1: ++k + k++ + + k The answer is 7 but I am confused as to how it is obtained. In the answer section Mughal says that it is evaluated as ((2) + (2) + (3)) I assume this means that we just evaluate each component of the expression from left to right. But doesn't this ignore operator precedence as indicated in Table 3.1 on page 42? Specifically, ... expression++ ... ++expression ... +expression ...
I reached the same answer evaluating as follows: 1) postfix ++ operator has highest precedence so k++ is evaluated first so we have (++k + 1 + + k) and k=2 now 2) prefix ++ operator and unary + operator have the same precedence so evaluate left to right. Evaluating k++ first yields (3 + 1 + + k) and k=3 now 3) Finally evaluating +k yields (3 + 1 + 3) = 7 Who is correct? Why? Thank you. Regards, Atif
Atif Faridi
Greenhorn
Joined: Nov 16, 2002
Posts: 7
posted
0
Posting Errata: The second sentence of Step 2 of my solution should read: Evaluating ++k first yields ... Atif
back again with my same old advice... the scjp 1.4 will not be looking for this kind of knowledge - if you're curious about this precedence stuff , well great - but if you're studying for the test - focus on other areas - this stuff isn't on the test.
Eliminate fossil fuel subsidies. (If you're not on the edge, you're taking up too much room.)