变量作用域的问题
test1函数中的a是作用域本来是整个test1函数,但后面a没人使用,所以调试器认为作用域提前结束了
test2局部变量加了static,声明这是一个需要长久保持的局部变量,他的作用域虽限制在函数内,但生命周期和全局变量相同
test3直接用全局变量,作用域和声明周期,和整个程序相同
test4因为a在后面的if语句会用到,所以a的声明周期延续到if语句,没执行if语句前a仍有效
编译器把变量声明周期最短化,是为了尽可能的使多个变量使用同一个RAM存储,变量重叠
- int fun( int n)
- {
- return n + 3;
- }
- void test1()
- {
- int a;
- a = fun(4);
- }
- void test2()
- {
- static int a;
- a = fun(4);
- }
- int a_test3;
- void test3()
- {
- a_test2 = fun(4);
- }
- void test4()
- {
- int a;
- a = fun(4);
- if(a)
- {
- Gpio_SetHigh();
- }
- }
|