今天,在寫條件編譯的時候,出現了在函數外部給全局變量賦值的情況,gcc報錯,那么c語言為什么不允許在函數外部給變量賦值呢?為什么聲明變量的時候可以對變量進行賦值?
出錯代碼:
1 /* 2 * ===================================================================================== 3 * 4 * Filename: 2.c 5 * 6 * Description: 7 * 8 * Version: 1.0 9 * Created: 2014年10月30日 16時25分41秒 10 * Revision: none 11 * Compiler: gcc 12 * 13 * Author: 3me (), 14 * Organization: 15 * 16 * ===================================================================================== 17 */ 18 #include <stdlib.h> 19 #include <stdio.h> 20 int i = 0; 21 i = 3; 22 23 /* 24 * === FUNCTION ====================================================================== 25 * Name: main 26 * Description: 27 * ===================================================================================== 28 */ 29 int 30 main ( int argc, char *argv[] ) 31 { 32 printf("%d.\n", i ); 33 34 return EXIT_SUCCESS; 35 } /* ---------- end of function main ---------- */ 36 2.c 1,1 頂端 1 2.c|21 col 1| 警告: 數據定義時沒有類型或存儲類 [默認啟用] 2 2.c|21 col 1| 警告: 在‘i’的聲明中,類型默認為‘int’ [-Wimplicit-int] 3 2.c|21 col 1| 錯誤: ‘i’重定義 4 2.c|20 col 5| 附注: ‘i’的上一個定義在此 ~
思考:
在函數外部對變量的聲明,是為了在編譯階段給程序分配內存空間,因此(在函數外部)聲明變量的時候對變量進行賦值,只是對分配的內存空間進行初始化。但程序的內部,函數的調用順序是無序的(並不是在文件中從上到下依次執行),如下圖,因此,如果c的語法允許在函數外部對變量賦值,則變量的值是不可預測的。
2 * ===================================================================================== 3 * 4 * Filename: 3.c 5 * 6 * Description: 7 * 8 * Version: 1.0 9 * Created: 2014年10月30日 16時50分05秒 10 * Revision: none 11 * Compiler: gcc 12 * 13 * Author: 3me (), 14 * Organization: 15 * 16 * ===================================================================================== 17 */ 18 #include <stdlib.h> 19 #include <stdio.h> 20 int i = 0; 21 i = 1; 22 #include <stdlib.h> 23 /* 24 * === FUNCTION ====================================================================== 25 * Name: main 26 * Description: 27 * ===================================================================================== 28 */ 29 int 30 main ( int argc, char *argv[] ) 31 { 32 i++; 33 fun1(); 34 return EXIT_SUCCESS; 35 } /* ---------- end of function main ---------- */ 36 /* 37 * === FUNCTION ====================================================================== 38 * Name: fun1 39 * Description: 40 * ===================================================================================== 41 */ 42 i = 2; 43 void 44 fun1 ( <+argument list+> ) 45 { 46 i = 3; 47 return <+return value+>; 48 } /* ----- end of function fun1 ----- */ 49 "3.c" 49L, 1215C 已寫入