[英]Declaration and placement of static variable
第一次执行该功能时, 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.
您当前的代码无效,因为您需要使用常量初始化静态变量,而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
,依此类推。
要修复您的foo()
,以便仅在第一次调用foo()
将静态x
设置为参数y
(并使之成为合法的C代码),您将需要执行以下操作:
int foo(int y) {
static int init;
static int x;
if (!init) {
init = 1;
x = y;
}
x = x + 1;
return x;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.