2010-06-22 110 views
0

將全局變量聲明爲auto是好的。 例如c聲明和初始化

auto int i; 
static int j; 

int main() 
{ 
    ... 
    return 0; 
} 
+2

您是否正在努力研究它是否合理,或者是否允許? – 2010-06-22 06:20:50

回答

0

基於汽車的這樣的解釋:

http://msdn.microsoft.com/en-us/library/6k3ybftz%28VS.80%29.aspx

它說,自變量是範圍有限,他們的地址是不恆定。由於全局變量既沒有這些屬性,全局變爲自動變量也沒有意義。

+2

這是一個C++參考,誰知道這些傢伙用不好的舊'auto'做了什麼:-) – 2010-06-22 06:31:03

1

C語言中'auto'的含義就是一個變量,它是一個局部變量。 所以說你想聲明一個局部變量爲全局變量是完全矛盾的。

我想你是在談論一個本地化的全球化。如果你想聲明一個變量,這個變量對你正在使用的.c文件是本地的,並且你不希望它在c文件之外被訪問,但是你希望它可以被所有的函數訪問文件,您應該將其聲明爲靜態變量,就像您對變量j所做的那樣。

因此你會有像在example.c如下:

static int i; //localised global within the file example.c 
static int j; //not accessible outside the .c file, but accessible by all functions within this file 


int main() 
{ 
     //do something with i or j here. 
     i = 0 ; 
     j = 1 ; 
} 

void checkFunction() 
{ 
     //you can also access j here. 
     j = j+ 5; 
} 

我想我要補充一點,有多種方法,您可以使用關鍵字static的變量。

的一個,你可能熟悉的是:

1) Declaring a variable static within a function - this ensures the variable retains its value between 
    function invocations. 

    The second one ... 
2) Declaring a variable as static within a module (or a .c file) - this is what I have described  
    above. This ensures a variable is localised within that module or .c file, but it is global so that 
    it can be used by any of the functions defined in that particular file. Hence the name localised 
    global. 

但是,它不會是.c文件外部訪問。

2

你爲什麼不試着在你的問題中編譯代碼片段?如果你有,現在你會知道它給出了一個編譯器錯誤。在海灣合作委員會:

foo.c:3: error: file-scope declaration of 'x' specifies 'auto' 

所以我想你的問題的答案是「不,它不好」。

0

不,這是不可能的。原因是全局變量在調用main()之前已經在特定的數據段中(與函數內聲明的靜態變量一起)被初始化爲零。