作用域與生命周期是非常重要的編程知識。本篇文章使用C語言講述作用域與生命周期。
一、作用域
在程序設計中,變量并非總是有效的,可以使用的區域就是作用域。
1.1局部變量的作用域
在{}中的都是局部變量,只是作用大小不一樣而已。我們可以簡單地分為兩種。為了方便理解,我們打個比方。將變量的作用域比作自行車。自己家的自行車,爺爺家的自行車。自己家的自行車自己可以使用,但是能夠使用的人比較少:
比如這種:自己家的自行車(局部變量作用域范圍小的)
#include <stdio.h>int main()
{int i = 0;for (i = 0; i < 5; i++){int a = 10;printf("a=%d\n",a);}printf("a=%d\n", a);//error!!!!!!!!!!!!!return 0;
}
運行結果以及結果解釋:
爺爺家的自行車(局部變量作用域范圍大的)?(在main函數中的局部變量):
#include <stdio.h>int main()
{int i = 0;int b = 20;for (i = 0; i < 1; i++)//for循環1次{b = 30;printf("b=%d\n", b);}printf("b=%d\n", b);return 0;
}
運行結果以及結果解釋:
這里定義在主函數中,b是一個局部變量,作用域是主函數的{}中。但是在這里我們不能將其認定為全局變量的作用域。?
?1.2局部變量的作用域
局部變量的作用域好比共享自行車,人人都可以使用。
例如:
#include <stdio.h>int c = 100;//定義全局變量int main()
{int i = 0;c = 50;printf("c=%d\n", c);for (i = 0; i < 1; i++)//for循環1次{c = 25;printf("c=%d\n", c);}return 0;
}
運行結果以及結果解釋:
二、生命周期
生命周期指的變量的創建(申請內存)到變量的銷毀(內存的回收)的過程。
2.1局部變量的生命周期
例如:
#include <stdio.h>int main()
{{int a = 10;printf("a=%d\n",a);}printf("a=%d\n", a);//errorreturn 0;
}
運行結果以及結果解釋:
2.2全局變量的生命周期
全局變量的生命周期是整個程序的生命周期,即main函數開始與結束之間。
例如:
#include <stdio.h>int a = 100;
void test(void)
{printf("test->a=%d\n",a);
}int main()
{test();printf("maint->a=%d\n", a);return 0;printf("after-return->a=%d\n", a);
}
運行結果以及結果解釋: