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
From Operators:
Applying this to your expression
++x - x++, we can see that first++xis evaluated, thenx++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++xbinds more tightly than the-operator, and thex++operator binds more tightly than the-operator, so this is parsed as(++x) - (x++). If the-operator had higher precedence than the++xorx++operators, this expression would be parsed as++(x - x)++(which wouldn't make much sense).The fact that
++xhas higher precedence thanx++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 operatorx++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.