Operator Priority

Consider this C # class:

class Node
{
    public Node Next;
}

And consider these two cases:

        Node A = new Node();
        Node B = A;
        B=(B.Next = new Node());

and

        Node A = new Node();
        Node B = A;
        B.Next = (B=new Node());

Why do they give the same results !?
(A)->(B)->Null

I thought the second case would trigger a node pointing to itself due to operator priority ...

Is this the case with Java and Python too? Thanks

+3
source share
4 answers

This behavior is not the result of operator precedence, but the rules in Java, Python, and C # that determine the order in which expressions are evaluated. In particular, in Java, Python, and C #, expressions are evaluated from left to right. This is not the case, for example, in C and C ++, where the result of what you wrote would be undefined.

You may be familiar with this C puzzle:

int i = 1;
printf("%d, %d\n", i++, ++i); // what is printed?

C . 1, 3, 2, 2 - . Java # Python 1, 3 ( , Python pre- postfix ++).

- . , .

, op1 op2. , :

e1 op1 e2 op2 e3

,

((e1 op1 e2) op2 e3)

(e1 op1 (e2 op2 e3))

, e1, e2 e3.

+2

Python , . RHS .

>>> a = (b=42)
  File "<stdin>", line 1
    a = (b=42)
          ^
SyntaxError: invalid syntax
>>> a = b = 42

>>> print a,b
42 42
>>> 

>>> class Node():
...     def __init__(self):
...             self.next = self
... 
>>> n = Node()
>>> n = n.next = Node()
>>> n
<__main__.Node instance at 0x7f07c98eb200>
>>> n.next = n = Node()
>>> n
<__main__.Node instance at 0x7f07c98eb290>
+2

# .

, "" LHS (B.Next) , RHS, Next A.

, RHS, . B RHS .

,

B.Next = (B = null)

, , ?

+2

Java , #.

    Node A = new Node();

node ( node 1) A .

    Node B = A;

B node 1.

A ----> [Node 1]---> null
           
B −−−−−−−−−'

. , :

    B.Next = 

node 1 ( B) ...

       (B=new Node());

... node ( node 2), B.

A ----> [Node 1]---> [Node 2]----> null
                         
B −−−−−−−−−−−−−−−−−−−−−−−'

Interestingly, it B.nextis evaluated before the right side of the destination, so it is the same as if you wrote A.nexthere.

+1
source

Source: https://habr.com/ru/post/1795991/


All Articles