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(); } 
+7
c ++ function static static-variables
source share
6 answers

They see only their own. A variable cannot be "visible" from outside the scope in which it was declared.

If, on the other hand, you did this:

 static int x; void foo() { static int x; } int main() { foo(); } 

then foo() sees only local x ; global x was "hidden" from it. But changes in one do not affect the meaning of the other.

+20
source share

Variables are different, each function has its own area. Therefore, although both variables are preserved for the life of the process, they do not interfere with each other.

+6
source share

It's fine. In practice, the actual name of the variable at the output of the compiler can be considered as something like function_bar_x , that is, the responsibility of your compiler is to ensure that they do not collide.

+3
source share

Nothing happens, both variables have theri scope and mantain their values ​​for calling in the call

+2
source share

Two static vars are different.

+1
source share

The compiler translates each variable in a unique way, for example foo_x and bar_x in your example, so they are handled differently.

Do not do this, as your code will be difficult to read and maintain after a while, as you will not be able to immediately catch what x you are referring to.

0
source share

All Articles