我不理解后缀和前缀的自增或自减概念。有没有人能给出更好的解释呢?
我不理解后缀和前缀的自增或自减概念。有没有人能给出更好的解释呢?
来自C99标准(C++应该相同,除了奇怪的重载)
6.5.2.4 后缀递增和递减运算符#include<stdio.h>
void main(){
char arr[] ="abcd";
char *p=arr,*q=arr;
char k,temp;
temp = *p++; /* here first it assigns value present in address which
is hold by p and then p points to next address.*/
k = ++*q;/*here increments the value present in address which is
hold by q and assigns to k and also stores the incremented value in the same
address location. that why *q will get 'h'.*/
printf("k is %c\n",k); //output: k is h
printf("temp is %c\n",temp);//output: temp is g
printf("*p is %c\n",*p);//output: *p is e
printf("*q is %c",*q);//output: *q is h
}
指针的后增量与前增量
预增量是在增加值++
之前,例如:
(++v) or 1 + v
后置递增是在增加值++
之后,例如:
(rmv++) or rmv + 1
程序:
int rmv = 10, vivek = 10;
cout << "rmv++ = " << rmv++ << endl; // the value is 10
cout << "++vivek = " << ++vivek; // the value is 11
你还应该知道,在C/C++和Java中,后增量/减量运算符的行为是不同的。
鉴于
int a=1;
a++ + a++ + a++
在JavaScript中,它的值为3,而在Java中它的值为6。猜猜为什么...
这个例子更加令人困惑:
cout << a++ + a++ + a++ << "<->" << a++ + a++ ;
打印出 9<->2 !! 这是因为上述表达式等同于:
operator<<(
operator<<(
operator<<( cout, a++ + a++ ),
"<->"
),
a++ + a++ + a++
)