Postfix has high precedence than prefix so value of sml2 in given code should be 2 but it's 0. Why?

76 Views Asked by At
namespace Randomedits
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 2;
            int sml2 = ++x - (x++) ;
            Console.WriteLine(sml2);
            Console.WriteLine(x);
        }
    }
}

Output:

0
4
1

There are 1 best solutions below

0
canton7 On

From Operators:

Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.

Applying this to your expression ++x - x++, we can see that first ++x is evaluated, then x++ is evaluated, then the subtraction is evaluated.

A good way of thinking about operator precedence is that operators with higher precedence bind more tightly than operators with lower precedence. It's used when working out what expressions a sequence of characters should be parsed as, not the order in which things are evaluated.

For example, in the expression ++ x - x ++, the operator ++x binds more tightly than the - operator, and the x++ operator binds more tightly than the - operator, so this is parsed as (++x) - (x++). If the - operator had higher precedence than the ++x or x++ operators, this expression would be parsed as ++(x - x)++ (which wouldn't make much sense).

The fact that ++x has higher precedence than x++ doesn't matter here. It does matter for the expression ++x++, which is parsed as (++x)++ rather than ++(x++) (and raises a compiler error because the operator x++ can't be applied to the expression (++x)).

Once you've used the rules of operator precedence to figure out that ++ x - x ++ should be parsed as (++x) - (x++), the quoted rules above apply, and the operands of the - expression are evaluated left-to-right.