1. 程式人生 > >C語言 全局變量、靜態全局變量、局部變量、靜態局部變量

C語言 全局變量、靜態全局變量、局部變量、靜態局部變量

code cal 程序 glob i++ 文件 str oba nbsp



 1 //test.c
 2 
 3 #include <stdio.h>
 4 extern int global_var;
 5 
 6 void test_global_var()
 7 {
 8     global_var++;
 9     printf("global_var = %d\n", global_var);
10 }

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <stdlib.h>
 4 
 5 void test_static_local_variable();
6 7 int global_var = 1; //普通全局變量,隨著整個程序的結束而消亡。可以在整個程序方法問 8 //可以在其他.c文件中訪問 9 static int static_global_var = 1; //靜態全局變量,限定只能在本文件內部訪問 10 11 int main(int argc, char** argv) 12 { 13 int a = 3; //
普通局部變量,只能在main函數內部使用,隨著main函數的結束而消亡 14 15 for (int i = 0; i < a; i++) //復合語句中定義,隨著for循環的結束而消亡 16 { 17 printf("i = %d\n", i); 18 } 19 20 test_static_local_variable(); //local_var = 1 21 test_static_local_variable(); //local_var = 2
22 test_static_local_variable(); //local_var = 3 23 24 printf("global_var = %d\n", global_var); //global_var = 1 25 test_global_var(); //global_var = 2 26 test_global_var(); //global_var = 3 27 28 system("pause"); 29 return 0; 30 } 31 32 void test_static_local_variable() 33 { 34 static int local_var = 0; //靜態局部變量,只能在函數test_static_local_variable內部使用 35 //生命周期為整個程序,隨著程序的結束而消亡 36 local_var++; 37 printf("local_var = %d\n", local_var); 38 }

   

C語言 全局變量、靜態全局變量、局部變量、靜態局部變量