2010-06-22 270 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()之前已经在特定的数据段中(与函数内声明的静态变量一起)被初始化为零。