【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++中大括号指明了变量的作用域。

 

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