简体   繁体   English

C ++中的静态变量

[英]Static variables in C++

I ran into a interesting issue today. 我今天遇到了一个有趣的问题。 Check out this pseudo-code: 看看这个伪代码:

void Loop()
{
   static int x = 1;
   printf("%d", x);
   x++;
}

void main(void)
{
    while(true)
    {
       Loop();
    }
}

Even though x is static, why doesn't this code just print "1" every time? 即使x是静态的,为什么这段代码每次只打印“1”? I am reinitializing x to 1 on every iteration before I print it. 在打印之前,我在每次迭代时将x重新初始化为1。 But for whatever reason, x increments as expected. 但无论出于何种原因,x按预期递增。

The initialization of a static variable only happens the first time. 静态变量的初始化仅在第一次发生。 After that, the instance is shared across all calls to the function. 之后,实例将在函数的所有调用中共享。

I am reinitializing x to 1 on every iteration 我在每次迭代时将x重新初始化为1

No, you're not: you're initializing it to 1, but it only gets initialized once. 不,你不是:你把它初始化为1,但它只被初始化一次。

static doesn't mean const . static并不意味着const

From MSDN: 来自MSDN:

When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. 修改变量时,static关键字指定变量具有静态持续时间(在程序开始时分配,在程序结束时释放)并将其初始化为0,除非指定了另一个值。 When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared). 在文件范围内修改变量或函数时,static关键字指定变量或函数具有内部链接(其名称在声明它的文件外部不可见)。

A variable declared static in a function retains its state between calls to that function. 函数中声明为static的变量在对该函数的调用之间保持其状态。

When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. 在类声明中修改数据成员时,static关键字指定该类的所有实例共享该成员的一个副本。 When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members. 在类声明中修改成员函数时,static关键字指定该函数仅访问静态成员。

The value of static is retained between each function call , so for example (from MSDN again): 每个函数调用之间保留静态值,例如(再次从MSDN):

// static1.cpp
// compile with: /EHsc
#include <iostream>

using namespace std;
void showstat( int curr ) {
   static int nStatic;    // Value of nStatic is retained
                          // between each function call
   nStatic += curr;
   cout << "nStatic is " << nStatic << endl;
}

int main() {
   for ( int i = 0; i < 5; i++ )
      showstat( i );
}

In your example, x will increment as expected because the value is retained . 在您的示例中,x将按预期递增,因为该值将保留

static in this context means that value should be retained between calls to the function. static在此上下文中表示应该在函数调用之间保留值。 the initialization is done only once. 初始化只完成一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM