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
; the global x
has been "hidden" by it. 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
, i.e. it is the responsibility of your compiler to ensure that these do not clash.
Nothing happen, both variables have theri scope and mantain their values to call in call
The two static vars are different.
The compilator translates each variable in a unique manner, such as foo_x
and bar_x
in your example, so they are threated differently.
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.
精彩评论