0
    ListNode odd = head;
    ListNode even = head.next;
    odd = odd.next = even.next;
    even = even.next = odd.next;

With this line: odd = odd.next = even.next; is even.next assigned to odd.next and then odd.next is assigned to odd? or is odd.next assigned to odd and then even.next is assigned to odd.next?

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Bob
  • 71
  • 1
  • 7
  • 2
    run it and see what happens – denvercoder9 Feb 13 '20 at 23:19
  • Have you tried it? What did you discover? – Jason Feb 13 '20 at 23:19
  • Probably undefined or compiler specific behavior, so you should *not* write your program to depend on it assigning in an order (same thing with function parameter evaluation order). Not worth obsessing about compressing your code so much. Write your code to be SUPER clear, obvious and unambiguous always, and will save you a immense in general. Ultimately it is the functionality and *maintainability* that are the most important. If you rely on non obvious behaviors, you or someone trying to figure out it out later will be inconvenienced at best or unexpected behavior changes or bugs at worst. – clearlight Feb 14 '20 at 03:17
  • Once your code is working you won't be going back and looking at it much anyway, so wasting cycles nuancing something like that to get it all on one line is seldom worth it. But if you're just curious, you'll have to devise a test, or compile it with the flag to show you the assembly language and see how the compiler does it yourself. – clearlight Feb 14 '20 at 03:22

2 Answers2

4

Assignment is right associative. This means the statement is interpreted as:

odd = (odd.next = even.next);

This is different to many operators. For instance subtraction, 1 - 2 - 3 is (1 - 2) - 3 not 1 - (2 - 3).

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
3

Java has right to left associativity for = assignemnts

Note there are different precedence and associativities for different operators. Worth reading about: https://www.w3adda.com/java-tutorial/java-operator-precedence-and-associativity

... or use brackets for complete clarity

user207421
  • 305,947
  • 44
  • 307
  • 483
tomgeraghty3
  • 1,234
  • 6
  • 10