Sequence of operations when using pointers and auto-incrementing operators in C Language
In the C language, when the pointer operator and ++ or-are combined, it is easy to tell the unclear operation order. Here, we will summarize the following six combinations: * p ++, (* p) ++, * (p ++), ++ * p, ++ (* p), * (++ p ).
First look at the code and output:
#include
int main(){ int a[3]={1,3,5}; int *p=a; printf(----------------1----------------); printf(%d,*p++); printf(%d,*p); int i; for(i=0;i<3;i++) printf(%d ,a[i]); printf(); printf(----------------2----------------); p=a;//reset data printf(%d,(*p)++); printf(%d,*p); for(i=0;i<3;i++) printf(%d ,a[i]); printf(); printf(----------------3----------------); a[0]=1;//reset data p=a; printf(%d,*(p++)); printf(%d,*p); for(i=0;i<3;i++) printf(%d ,a[i]); printf(); printf(----------------4----------------); p=a; printf(%d,++*p); printf(%d,*p); for(i=0;i<3;i++) printf(%d ,a[i]); printf(); printf(----------------5----------------); p=a; a[0]=1; printf(%d,++(*p)); printf(%d,*p); for(i=0;i<3;i++) printf(%d ,a[i]); printf(); printf(----------------6----------------); p=a; a[0]=1; printf(%d,*(++p)); printf(%d,*p); for(i=0;i<3;i++) printf(%d ,a[i]); printf(); return 0;}
The output result is as follows:
First group: * p ++. The operation sequence is to first return the value of * p, and then p ++.
The second group: (* p) ++. the operation order is to first return the value of * p, then the value of * p Plus ++, this can be seen from the value of array a after calculation.
Group 3: * (p ++). the operation order is to first return the value of * p, and then p ++, that is, it is the same as the operation order of * p ++.
All three groups return the value of * p first. The difference is whether the value of * p is p ++ or * p ++.
Group 4: + + * p. Set the value of * p to + +, and then return the value of * p.
Group 5: ++ (* p), first convert the value of * p to ++, and then return the value of * p, so it is the same as ++ * p.
Group 6: * (++ p). First, the value of p is ++, and then the value of * p is returned, which is equivalent to * ++ p.
These three groups are characterized by * p values returned at the end, with the difference being * p ++ or p ++.