howdy all,
Yuck -- what awful code! But in the true spirit of the exam ; )
Anyway, the [ ] has the highest precedence, so on the left hand side of the left-most expression,
a[ a[b]] is really a[0] because that evaluation happens BEFORE the element at a[0] is changed to have a value of 2. In other words, the FIRST thing that happens is all the array index values (the things in the brackets) are evaluated, and THEN we move all the way to the right side to start working on the assignments.
So you can think of it like:
a[0] = a[0] = 2.
So here are the steps in order:
1) a[a[b]] evaluates to a[0]
// because [ ] has highest precedence (much higher than assignment, and b is indeed 0, so the thing at a[0] is 0 at this point, since it has not been initialized to anything other than the default value for an int.
2) a[b] is evaluated to a[0], because b has a value of 0.
3) 2 is assigned to the array element a[0] , this makes the result of that assignment a '2' (remember that the result of any assignment is the value of the thing being assigned, AFTER the assignment takes place.
4) Finally, the left-most a[0] is also given a value of 2, because that's the result of the previous assignment (the one to the right).
Yikes. I probably just made it more confusing.
Bottom line: In an expression with array indexes that are not literal values, FIRST go in and resolve all of them so that you know exactly WHICH array element/position/index you are going to work with. That way, even if other parts of the expression change the values used in those array element expressions, they will have no effect on which array element is being referenced.
Cheers,
Just let me know whenever I can make anything even more confusing than it already is.
I *can* tell you that while precedence is almost never an issue on the exam, because the exam
philosophy is that
you should just use parenthesis and not worry about it, THIS is a special case and you SHOULD understand that the array index is resolved first. In other words, any expression inside an array index [ something in here] will be fully evaluated so that there is an actual, locked down, never-to-change index and THEN we can start doing other things...
-Kathy
"Write your code as if the next guy to maintain it is a homicidal maniac who knows where you live."