Search code examples
c#javapythonoperator-keywordoperator-precedence

Operator precedence


Consider this C# class:

class Node
{
    public Node Next;
}

And consider these 2 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 produce the same results!?
(A)->(B)->Null

I thought the 2nd case would produce a node pointing to itself because of operator precedence...

Is that the case in Java and Python too? Thanks


Solution

  • This behavior is not a result of operator precedence, but of rules in Java, Python, and C# which define the order of evaluation of expressions. Specifically, in Java, Python, and C#, expressions are evaluated left to right. This isn't true, for example, in C and C++, where the result of what you wrote would have been undefined.

    You might be familiar with this C puzzle:

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

    In C, the result is not defined. It could be 1, 3, it could be 2, 2, or even something else. In Java C#, and Python, the result is always 1, 3 (except of course that Python does not have a pre- or postfix ++ operator).

    Operator precedence is a separate issue. It defines the parse tree, not the order of evaluation.

    Say you had a new language with binary infix operators op1 and op2. And say you had the following piece of code:

    e1 op1 e2 op2 e3
    

    Operator precedence tells you whether this means

    ((e1 op1 e2) op2 e3)
    

    Or whether it means

    (e1 op1 (e2 op2 e3))
    

    It does not tell you the order in which e1, e2, and e3 are evaluated.