Explanation of ++val++ and ++*p++ in C

﹥>﹥吖頭↗ 提交于 2019-11-30 15:32:35

问题


int val = 5;

printf("%d",++val++); //gives compilation error : '++' needs l-value

int *p = &val;
printf("%d",++*p++); //no error

Could someone explain these 2 cases? Thanks.


回答1:


++val++ is the same as ++(val++). Since the result of val++ is not an lvalue, this is illegal. And as Stephen Canon pointed out, if the result of val++ were an lvalue, ++(val++) would be undefined behavior as there is no sequence point between the ++s.

++*p++ is the same as ++(*(p++)). Since the result of *(p++) is an lvalue, this is legal.




回答2:


The expression ++val++ is the same as (++val)++ (or perhaps ++(val++), anyway it's not very relevant). The result of the ++ operator is not the variable, but the value, and you can't apply the operator to a value.

The expression ++*p++ is the same as ++(*(p++)). The result of p++ is the value, but the result of *(p++) is a memory location, which the ++ operator can be applied to.




回答3:


also note that you're changing the address of the pointer by

int k = ++*p++;



回答4:


int j = ++val++; //gives compilation error

That because you cannot pre-increment an rvalue. ++val++ is interpreted as ++(val++) because post-increment operator has higher precedence than pre-increment operator. val++ returns an rvalue and pre-increment operator requires its operand to be an lvalue. :)

int k = ++*p++; //no error

++*p++ is interpreted as ++(*(p++)), which is perfectly valid.



来源:https://stackoverflow.com/questions/3660048/explanation-of-val-and-p-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!