为什么postfixed具有比prefixed更高的优先级?

时间:2017-12-08 19:33:08

标签: c operator-precedence

案例1:

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

这里,首先将i的值赋给j,然后将i增加1。

案例2:

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

这里,首先i增加1,然后分配给j。

那么,如果在前缀形式中首先完成增量操作,那么为什么后缀具有比前缀更高的优先级?

2 个答案:

答案 0 :(得分:2)

这与优先级无关。(此处)在预增量中,分配的值是副作用发生之前的值。 对于预增量,它将是副作用后的值。

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

在递增i的值之前是10.在执行这两个语句之后j=10

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

这里的值为11.因为incrementmenet先完成然后分配。

答案 1 :(得分:0)

manual的{​​{1}}个operator页面定义为same priority前/后increment

! ~ ++ -- + - (type) * & sizeof      right to left
首先分配

后增量规则,然后增加

int j = i++;// here first whatever i value is there that will be assigned to j

预增量规则是第一个增量,然后分配

int j = ++i;//++i itself will change i value & then modfied value will assign to j.

例如考虑下面的例子

#include<stdio.h>
int main()
{
        int x = 10;
        int *p = &x;// assume p holds 0x100
        printf("x = %d *p = %d p = %p\n",x,*p,p);
        ++*p++;
        /** in above statement ++ and * having same precedence,then you should check assocaitivity which is R to L
          So start solving from Right to Left, whichever operator came first , solve that one first 
          first *p++ came , again solve p++ first, which is post increment,so address will be same 
         *0x100  means = 10
         now ++10 means = 11
         **/
        printf("x = %d *p = %d p = %p\n",x,*p,p);
}