简体   繁体   English

如何从外部函数更改本地静态变量值

[英]How to change local static variable value from outside function

#include <stdio.h>

void func() {
   static int x = 0;  // x is initialized only once across three calls of
                      //     func()
   printf("%d\n", x); // outputs the value of x
   x = x + 1;
}

int main(int argc, char * const argv[]) {
   func(); // prints 0
   func(); // prints 1
   func(); // prints 2

   // Here I want to reinitialize x value to 0, how to do that ? <-- this line
   return 0;
}

In the above code, after calling func() 3 times I want to re-initialize x to zero. 在上面的代码中,在调用func()3次之后,我想将x重新初始化为零。 Is there any method to reinitialize it to 0? 有没有方法将它重新初始化为0?

Do you want the function always to reset the counter after three invocations? 在三次调用后,您是否希望函数始终重置计数器? or do you want to the caller to reset the count at arbitrary times? 或者你想让调用者在任意时间重置计数?

If it is the former, you can do it like this: 如果是前者,你可以这样做:

void func() {
  static int x = 0;
  printf("%d\n", x);
  x = (x + 1) % 3;
}

If it is the latter, using a local static variable is probably a bad choice; 如果是后者,使用局部静态变量可能是一个糟糕的选择; you could instead use the following design: 你可以改为使用以下设计:

class Func
{
  int x;
  // disable copying

public:
  Func() : x(0) {}

  void operator() {
    printf("%d\n", x);
    x = x + 1;
  }

  void reset() {
    x = 0;
  }
};

Func func;

You should make it either non-copyable to avoid two objects increasing two different counters (or make it a singleton), or make the counter a static member, so that every object increments the same counter. 您应该使其不可复制以避免两个对象增加两个不同的计数器(或使其成为单个),或使计数器成为静态成员,以便每个对象递增相同的计数器。 Now you use it like this: 现在你像这样使用它:

int main(int argc, char * const argv[]) {
  func(); // prints 0
  func(); // prints 1
  func(); // prints 2

  func.reset();
  return 0;
}

You can't. 你不能。 It's a local static variable which is invisible outside func() . 它是一个局部静态变量,在func()之外是不可见的。

You can either use: 你可以使用:

  1. Global static (not recommended generally). 全局静态(一般不推荐)。
  2. Pass it through reference/pointer parameter, or return by reference. 通过引用/指针参数传递,或通过引用返回。

You can have func() assign the address of the variable to a pointer that's visible from outside func() . 您可以让func()将变量的地址分配给从func()外部可见的指针。

Or you can have a special parameter you can pass to func() to tell it to reset the variable. 或者你可以有一个特殊的参数,你可以传递给func()告诉它重置变量。

But really, the whole point of declaring x inside func() is to make it visible only within the body of func() . 但实际上,在func()中声明x是使其仅在func()体内可见。 If you want to be able to modify x , define it somewhere else. 如果您希望能够修改x ,请在其他位置定义它。 Since you're writing C++, it probably makes sense for x to be a static member of some class. 由于您正在编写C ++,因此将x作为某个类的静态成员可能是有意义的。

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

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