In #1 statement ma[1] will be 1 first, then ma[1] will be incremented.
so, I think ma[1] will be 2. But I got the output 1 from line #2. how the evaluation done here.
Also, as 2+1 = 3, I thought 3 will be the output of #3. But it is 5.

can any body please explain how the compiler evaluates this expression?

The index of array starts from 0. So, ma[0]=1,ma[1]=3,ma[2]=3,ma[4]=4

ma[ma [1] ] = ++ma[1] + (ma[1]=1); // #1

=> ma[3] = ++3 + (1) ; // now ma[1]=1 not 3
=> ma[3] = 4+1=5

Naren
-------------------
SCJP - 90%
SCWCD - 98%

Venkata Saraswathi
Ranch Hand

Joined: Sep 27, 2008
Posts: 55

posted

0

ma[ma [1] ] = ++ma[1] + (ma[1]=1); // #1

=> ma[3] = ++3 + (1) ; // now ma[1]=1 not 3
=> ma[3] = 4+1=5

According to operator precedence rools expression in () will be evaluted fist then ++ will be evaluated.
So, By following that a[1] will be initialized first then its value will be incremented

=> it should be = ++1+(1) // here ma[1]=2 yes?
why should we consider like ++3 + (1) instead of above.

Venkata Saraswathi wrote:
=> it should be = ++1+(1) // here ma[1]=2 yes?
why should we consider like ++3 + (1) instead of above.

Please clarify

First of all let me remind you Big Daddy of all Algebra Rule
LHS = RHS

1. Forget right hand side, first only deal with LHS - you will get ma[3].
2. OK now move to RHS - of course anything with in () is computed first. But who is computing in (). Its only assigning. You know assigning will be last.
3. So now come back to ++ma[1] which will be 4. Now it is time to assign 1 in ma[1] and retrive what is in ma[1], which is 1. Add it to 4 to become 5.