c - 静态变量的声明和放置

标签 c operator-precedence

X是否只在函数第一次执行时被Y初始化一次?

int foo(int y) {

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

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

最佳答案

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

例如,函数内部的static就是这样。

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.

关于c - 静态变量的声明和放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21606352/

相关文章:

c - 如果大于 0,则将数字设为 1

c++ - 将来自 stdin 的交互式输入与到 stdout 的异步输出相结合

c - 重组后监控碎片数据包

在 C 中更改所有者和组?

Java boolean 优先级与三元运算符的比较

c - 为什么我的程序输出整数而不是 float ?

Python: "import"更喜欢什么——模块还是包?

Scala:可以在不带括号的表达式中使用 "foo match { bar }"吗?

c - 指针算术 :++*ptr or *ptr++?

c++ - () 的优先级不大于 &&