简体   繁体   English

在C ++中,如果两个不同的函数声明相同的静态变量会发生什么?

[英]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_xbar_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.

相关问题 如何声明两个不同的静态变量? (C ++) - How to declare two different static variables? (C++) 在C ++头文件中声明和定义静态变量? - Declare and define static variable in C++ header? C++ 变量名(可以将 main 声明为变量,但对于其他函数名则不然) - C++ variable names (can declare main as variable however same is not true for other functions name) 声明一个变量并在同一行返回它 C++ - Declare a variable and return it in the same line C++ 是否可以在c ++中声明具有不同类型的变量? - Is it possible declare a variable with different types in c++? 在c ++中抽象两个稍有不同的函数的最佳方法是什么? - What is the best way to abstract two slightly different functions in c++? C ++使用在类定义中声明的变量在同一类定义中声明不同的变量 - C++ Using a variable declared in class definition to declare a different variable in the same class definition 当同一个命名空间中有两个具有相同签名的函数时会发生什么? - What happens when there are two functions with the same signature in the same namespace? C ++中一组函数的静态变量 - Static variable for a group of functions in C++ C ++ Koenig(Argument-Dependent)查找:如果不同名称空间中的两个名称空间函数具有相同的参数类型,该怎么办? - C++ Koenig(Argument-Dependent) Lookup: What if two namespaces functions in different namespaces have the same argument types?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM