看了小半天的内容,觉得有必要对今天所学做一个总结+延申。
1.首先关于变量
变量就是内存中一段连续的空间。他有一个重要的属性,叫作用域。同时变量也有不同的类型,也就是有不同的作用域。
首先看下 局部变量 和 静态局部变量,通过一段代码解释:
1.1局部变量
#include <iostream>
using namespace std;
void t1();
int main()
{
#if 0
cout << "if you are dog" << endl;
#endif
cout << "if you are cat" << endl;
t1();
t1();
return 0;
}
void t1()
{
int y = 1;
y++;
cout << y << endl;
}
结果 2 2
1.2.静态局部变量
#include <iostream>
using namespace std;
void t1();
int main()
{
#if 0
cout << "if you are dog" << endl;
#endif
cout << "if you are cat" << endl;
t1();
t1();
return 0;
}
void t1()
{
static int y = 1;
y++;
cout << y << endl;
}
结果 2 3
小结:静态局部变量是在内存中有固定地址的,只要程序运行(跳过初始化),其值不会被刷新(局部变量是放在堆栈中的,会自动刷新的)
还有外部变量和寄存器变量(先放着)