When the ++ operator appears before a variable, it is
called a prefix increment operator; when it appears
after a variable, it is called postfix increment operator
– k = ++n; is equivalent to
• n = n + 1; // increment n first
• k = n; // assign n’s value to k
– k = n++; is equivalent to
• k = n; // assign n’s value to k
• n = n + 1; // and then increment n
– count1 = 1+ ++count;(不建議如是寫)
– count1 = 1+count++;(不建議如是寫)
也就是說
int k = i++,先傳回i的舊值,再把i加一
int k = ++i,先修改i,再傳回i的新值。
我們來看一個例子
#include <stdio.h>
int main()
{
int a=0;
printf("%d\n",a);
printf("%d\n",a++);
printf("%d\n",++a);
printf("%d\n",a--);
printf("%d\n",--a);
return 0;
}
PS E:\vscode-py\build> cd "e:\vscode-py\build\" ; if ($?) { gcc c.c -o c } ; if ($?) { .\c }
0
0
2
2
0
a的初值是0
第一步我們做了a++,先傳回a的舊值,是以第二個數輸出仍然是0,之後再把a+1,此時i已經變成了1
第二步我們做了++a,是先把a加1,之後再傳回a的新值,是以這次輸出的數是2.
第三步我們做的是a- -,先傳回a的舊值,是以第四個數輸出仍然是2,之後再把a-1,此時a已經變成了1
第四步我們做了–a,是先把a減1,之後再傳回a的新值,是以這次輸出的數是0.