变量作用域(scope of variable)

1、全局变量(Global Variables)
在函数外面定义的变量(没有被花括号括起来)称为全局变量,全局变量的作用域是从变量定义的位置开始到文件结束。
2、局部变量(Local Variables)
在函数内部定义的变量称为局部变量,其作用域只在定义它的函数内有效。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/******************************************************************************
global variable

*******************************************************************************/

#include<iostream> 
using namespace std; 

// global variable 
int global = 5; 

// global variable accessed from within a function 
void display() 
{ 
	cout<<"the global variable in display function: "<<global<<endl; 
} 

// main function 
int main() 
{ 
	display(); 
	
	// changing value of global variable from main function 
	global = 10; 
	cout<<"the global variable in main function: "<<global<<endl; 
	display(); 
} 

3、在代码块中定义的变量,它的存在时间和作用域将被限制在该代码块中。
例如在for(int i;i<n;i++)中,i的存在时间和作用域只在for循环内。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <iostream>
using namespace std;

int main(){
    int a;
    for (int i = 0; i < 10; i++) {
        a+=i;
    }
//  cout<<i;
    cout<<a;

    return 0;
}

4、如果局部变量与全局变量重名,在相同的作用域内,局部变量有效。

5、全局变量在定义时若没有赋初值,其默认值为0;局部变量如果没有赋初值,其默认值随机。

6、static关键字

static 是 C/C++ 中很常用的修饰符,它被用来控制变量的存储方式和可见性。

用static关键字定义的静态变量存储于进程的全局数据区,它的值不随函数的调用或返回而改变。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
using namespace std;
 
void demo(){
    // 用static定义变量 
    static int count = 0;
    cout << count << " ";
    // 变量值更新后被带到下一次函数调用中
    count++;
}
 
int main(){
    for (int i = 0; i < 5; i++)
        demo();
    return 0;
}
Scroll to Top