0

I have a problem with C# operator precedence.

I've read in the docs that postfix increment (x++) has higher precedence than prefix increment (++x), so in this code the result must be 2 but it shows 0.

int x = 10;
int y = ++x - x++;

First x++ executes so we have:

// x = 11;
int y = ++x - 10;

and then ++x executes and we have:

// x = 12;
int y = 12 - 10;

But it shows the result 0.
i read that the left side of - must evaluate first but - has lower precedence than x++. please don't refer to another topic. explain this specific example What is going on?

  • Please don't write code like this. It's never necessary, and if you don't write it, you (and the others who will read your code after you write it) won't have to go through the mental gyrations of trying to figure out how it works. – Robert Harvey Apr 12 '20 at 15:20
  • 2
    `int y = ++x - x++;` means, `y = (x = x + 1) - (x); x = x + 1;` => `y = 11 - 11` and it is as expected. – Oguz Ozgul Apr 12 '20 at 15:21

0 Answers0