4-7.自增(++)、自減(--)和組合賦值操作符(+=、-=)

自增和自減只能用在整數的變量中

  1. 前自增:++a,在將a用在表達式之前先自加
    後自增:a++,在將a用在表達式之後再自加

  2. 前自減:–a

    後自減:a–

  3. 自加自減無論前後意義都是+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;
}
  1. 常用組合賦值操作符:+=,-=,*=,/=,%=
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章