*(p++)与*(++p)的问题
- C/C++ code
#include<stdio.h>main(){ int a[]={1,2,3,4,5}; int *p; p = a; p++; printf("%d,%d",*(p++),*p);}以上代码执行结果是2,2
- C/C++ code
#include<stdio.h>main(){ int a[]={1,2,3,4,5}; int *p; p = a; p++; printf("%d,%d",*(++p),*p);}以上代码执行结果是3 ,2
实在是想不明白,求高手教育
[解决办法]
printf("%d,%d",*(p++),*p);//先printf("%d,%d",*p,*p);然后p = p+1;
printf("%d,%d",*(p++),*p);//先p = p+1;然后printf("%d,%d",*p,*p);
可以这么理解
[解决办法]
Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). 标准对函数参数的求值顺序未指定,不要写这样的代码即可。
- C/C++ code
int a[]={1,2,3,4,5}; int *p; p = a; p++; int t1 = *p; //2 int t2 = *(++p); //3 printf("%d,%d", t2,t1); //3, 2
[解决办法]
你为什么不把函数参数顺序倒一倒再试试看呢?
其实,按标准来说,函数参数的求值顺序应该是不确定的,写依赖求值顺序的代码也是不可取的
[解决办法]
这不很明显嘛,printf("%d,%d",*(++p),*p)你要看成是一个表达式,其中的p是同一个