6

Consider the following code snippet in Java. I know that the statement temp[index] = index = 0; in the following code snippet is pretty much unacceptable but it may be necessary for some situations:

package arraypkg;

final public class Main
{
    public static void main(String... args)
    {
        int[]temp=new int[]{4,3,2,1};
        int index = 1;

        temp[index] = index = 0;
        System.out.println("temp[0] = "+temp[0]);
        System.out.println("temp[1] = "+temp[1]);
    }
}

It displays the following output on the console.

temp[0] = 4
temp[1] = 0

I do not understand temp[index] = index = 0;.

How does temp[1] contain 0? How does this assignment occur?

3
  • What do you expect temp[1] to be? Commented Dec 15, 2011 at 19:08
  • I think it's pretty clear that he expects index to first become 0 making temp[index] equivalent to temp[0] so that only the first element is modified. Commented Dec 15, 2011 at 19:12
  • 4
    The take home message here should be, don't write code this way. Knowing the fiddly bits of Java is a respectable skill, but mostly useless. Code like this simply shouldn't exist, and where it is found should be eradicated immediately. Commented Dec 15, 2011 at 19:18

4 Answers 4

9

The assignment is done (temp[index] = (index = 0)), right associative.

But first the expression temp[index] is evaluated for the LHS variable. At that time index is still 1. Then the RHS (index = 0) is done.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 - First person to directly address the question the OP is actually asking (about LHS vs. RHS order of evaluation).
1

Your statement assigned zero to it. The statement temp[index] = index = 0 wrote zero into index AND into temp[index]. That's what that meant. Make all variables to the left of an assignment operator 0.

Comments

1

What that line does is say that temp[index] should equal index after index is assigned the value 0.

This is why this syntax is mostly unacceptable. It's hard to read and most people don't understand it.

Comments

1

you assigned both temp[1] and index to '0' it running left to right. think ass temp[index/* */]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.