Purge and preset over again a static variable

How to purge and preset again a static local variable in function from an initiative outside of it?
I don't know what you think "purging" a variable is, but maybe this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

void f(bool reset = false)
{
    static int n = 0;
    if (reset)
        n = 0;
    else
        std::cout << n++ << '\n';
}

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

Alternatively, you can use a function object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

class Func
{
    int n = 0;
public:
    void reset() { n = 0; }
    void operator()()
    {
        std::cout << n++ << '\n';
    }
};

int main()
{
    Func f;
    for (int i = 0; i < 5; ++i) f();
    f.reset();
    for (int i = 0; i < 5; ++i) f();
}

Last edited on
Topic archived. No new replies allowed.