[英]In C++, what happens if two different functions declare the same static variable?
void foo() {
static int x;
}
void bar() {
static int x;
}
int main() {
foo();
bar();
}
They each see only their own one. 他们每个人只能看到自己的一个。 A variable cannot be "seen" from outside the scope that it's declared in. 不能从声明的范围之外“看到”变量。
If, on the other hand, you did this: 另一方面,如果您这样做:
static int x;
void foo() {
static int x;
}
int main() {
foo();
}
then foo()
only sees its local x
; 然后foo()
仅看到其本地x
; the global x
has been "hidden" by it. 全局x
已被它“隐藏”。 But changes to one don't affect the value of the other. 但是更改一个不会影响另一个的价值。
The variables are distinct, each function has it's own scope. 变量是不同的,每个函数都有自己的作用域。 So although both variables last for the lifetime of the process, they do not interfere with each other. 因此,尽管这两个变量在整个过程的生命周期中都持续存在,但它们不会相互干扰。
This is perfectly fine. 很好 In practice the actual name of the variable in the output of the compiler can be thought of as something like function_bar_x
, ie it is the responsibility of your compiler to ensure that these do not clash. 实际上,可以将编译器输出中变量的实际名称视为类似于function_bar_x
,即,确保这些变量不冲突是编译器的责任。
什么都没发生,两个变量都具有theri范围并保留其值以在call中调用
这两个静态变量不同。
The compilator translates each variable in a unique manner, such as foo_x
and bar_x
in your example, so they are threated differently. 编译器以独特的方式转换每个变量,例如您的示例中的foo_x
和bar_x
,因此它们受到不同的威胁。
Don't do this as your code will be hard to read and maintain after some time since you will not able to catch at once of what x
are you referring to. 不要这样做,因为一段时间后您的代码将难以阅读和维护,因为您将无法立即捕获所指的x
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.