如何从外部函数更改局部静态变量值 [英] How to change local static variable value from outside function

查看:81
本文介绍了如何从外部函数更改局部静态变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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;
}

在上面的代码中,在调用func()3次之后,我想将 x 初始化为零.有什么方法可以将其重新初始化为0吗?

In the above code, after calling func() 3 times I want to re-initialize x to zero. Is there any method to reinitialize it to 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;
}

这篇关于如何从外部函数更改局部静态变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆