c声明和初始化

时间:2010-06-22 06:13:25

标签: c

将全局变量声明为auto是没关系的。 例如

auto int i;
static int j;

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

4 个答案:

答案 0 :(得分:2)

为什么你没有尝试在你的问题中编译代码片段?如果你有,你现在就知道它给出了一个编译器错误。在gcc:

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

所以我想你的问题的答案是“不,这不好”。

答案 1 :(得分: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 :(得分:0)

基于对auto的解释:

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

它表示自动变量是范围有限的,并且它们的地址不是常量。由于全局变量都没有这些属性,因此将全局变为auto是没有意义的。

答案 3 :(得分:0)

不,这是不可能的。原因是全局变量在特定数据段(以及在函数内声明的静态变量)中,在调用main()之前一次初始化为零。