【C/C++】局部變量作用域

編譯器

VC++ 2010 win32/64

 

代碼

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{
	//局部變量1,作用域爲整個main()函數(除14-22行)
	int					i;

	i = 5;				
	
	{
		//局部變量2,局部作用域(14-22行)
		int i;
		
		i = 7;

		//輸出7
		cout << i << endl;
	}
	
	//輸出5
	cout << i << endl;
	
	system("Pause");
	
	return 0;
}

 

調試結果

 

心得

1、在同一個函數中聲明兩個重名局部變量i(如代碼所示),不會未引發C2086錯誤。

2、兩個變量作用域不同,在C/C++中大括號指明瞭變量的作用域。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章