C ++ 函数中的静态变量

在函数中的静态变量,只在进入函数的第一次进行初始化,
而动态变量,在每次进入函数的时候,都会被初始化。

//变量的生存期与可见性
#include <iostream>
using namespace std;

int i = 1; //全局变量
void other(){
	static int a = 2;
	static int b; //a、b为静态局部变量,局部可见 有全局寿命
	//只在第一次进入函数的时候被初始化
	int c = 10;
	// c是局部变量,动态生存期
	// 在每次进入函数的时候都会被初始化
	a += 2; i +=32; c += 5;
	cout << "---OTHER---" << endl;
	cout << " i: " << i << " a: " << a
	<< " b: " << b << " c: " << c << endl;
	b = a;
}

int main(){
	static int a;
	int b = -10;
	int c = 0;
	cout << "---MAIN---" << endl;
	cout << " i: " << i << " a: " << a
	<< " b: " << b << " c: " << c << endl;
	c += 8; other();
	cout << "---MAIN---" << endl;
	cout << " i: " << i << " a: " << a
	<< " b: " << b << " c: " << c << endl;
	// main 归 main部分加减 
	i += 10; other(); //other 归 other 部分加减
	return 0;
}
//i 属于全局变量
发布了16 篇原创文章 · 获赞 0 · 访问量 161

猜你喜欢

转载自blog.csdn.net/qq251031557/article/details/104878290
今日推荐