Search code examples
coperator-precedence

Why postfixed has higher precedence than prefixed?


Case 1:

int i = 10;
int j = i++;

Here, first the value of i is assigned to j and than i is increased by 1.

Case 2:

int i = 10;
int j = ++i;

Here, first i is increased by 1 and than it is assigned to j.

So, If the operation of increment is done first in the prefixed form, then why postfixed has higher precedence than prefixed?


Solution

  • This has nothing to do with precedence.(here) In pre-increment the value that is assigned is the value before the side effect takes place. For pre increment it will be the value after the side effect.

    int i = 10;
    int j = i++;
    

    Before incrementing value of i is 10. So j=10 after these 2 statements are executed.

    int i = 10;
    int j = ++i;
    

    Here the value will be 11. because incremenet is done first and then it is assigned.