自增和自減只能用在整數的變量中
-
前自增:++a,在將a用在表達式之前先自加
後自增:a++,在將a用在表達式之後再自加 -
前自減:–a
後自減:a–
-
自加自減無論前後意義都是+1或者-1,單獨使用沒有任何區別。區別主要在於表達式中。
#include<iostream>
using namespace std;
int main(int argc, char* argv[])
{
/*************************自增*************************/
int m = 10;
int n = 30;
cout << m << endl;//10
cout << m++ << endl; //10
cout << m << endl;//11
cout << n << endl;//30
cout << ++n << endl;//31
cout << n << endl;//31
/*************************自減*************************/
int a = 40;
cout << a << endl;//40
cout << a-- << endl;//40
cout << --a << endl;//38
/*************************嘗試1*************************/
int x = 10;
x = 2 * x++ * (2 + --x);//並不建議在表達式中過多地使用++和--
cout << x << endl;
/*************************嘗試2*************************/
for(int i= 0;i<10;i++/* ++i 也是一樣的*/)
{
}
/*************************在指針中使用*************************/
int codes1[] = { 1,2,3 };
int* pCodes = codes1;
cout << *pCodes << endl;
cout << pCodes << endl;
pCodes++;
cout << *pCodes << endl;
cout << pCodes << endl;
/*結果:
1
000000C38056FB98
2
000000C38056FB9C
//int是4個字節,16進制中8+4=C
*/
return 0;
}
- 常用組合賦值操作符:+=,-=,*=,/=,%=