声明和放置静态变量

时间:2014-02-06 15:00:32

标签: c operator-precedence

第一次执行该函数时,XY初始化一次吗?

int foo(int y) {

   static int x = y;
   x = x + 1;
   return x;
}

while(1) {
  y = y+1;
  foo(y);
}

3 个答案:

答案 0 :(得分:1)

不,用局部变量初始化静态变量是无效的。

例如,

函数中的静态就像这样。

int foo(void)
{
   static int y = 0;
}

以上陈述等同于以下两点:

 1) static int y = 0;
    int foo(void)
    {

    }

 2) And the variable y' should be used only in the function foo(). So you are 
    telling the compiler that I want a variable that is a global(with respect
    to memory and initialization at the compilation time), but the variable
    should be used only inside the function, if it is used outside this function
    let me know. 


 So, dynamic initialization of a static variable(that is actually initialized at
 the time of compilation) is invalid.

答案 1 :(得分:0)

您当前的代码无效,因为您需要使用常量初始化静态变量,而y不是常量。

foo.c:2:20: error: initializer element is not a compile-time constant
    static int x = y;
                   ^

另一方面,如果你的代码看起来像:

int foo() {
   static int x = 0;
   x = x + 1;
   return x;
}

然后我希望foo的响应每次调用一个更大。因此,第一个调用将返回1,第二个调用将返回2,依此类推。

答案 2 :(得分:0)

要修正foo(),以便仅在x第一次调用中将静态y设置为参数foo() (并使其成为合法的C代码),您需要执行以下操作:

int foo(int y) {
   static int init;
   static int x;
   if (!init) {
      init = 1;
      x = y;
   }
   x = x + 1;
   return x;
}