How to change local static variable value from outside function

后端 未结 3 828
悲&欢浪女
悲&欢浪女 2021-01-26 09:00
#include 

void func() {
   static int x = 0;  // x is initialized only once across three calls of
                      //     func()
   printf(\"%d\\n\"         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-26 09:25

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

提交回复
热议问题