Search code examples
c++functionstructstatic

How to reset a static struct inside a function


So let's say I have a function

struct coinTypes {
    int tenP = 0;
    int twentyP = 0;
    int fiftyP = 0;
};

coinTypes numberOfCoins(int coins)
{

    static coinTypes types;

    // incrementing structs values
}

Let's say I have used this function for some time, and values in coinTypes struct are no longer 0. Then I decided to use this function for another purpose and I need the values to be 0 again. Is there any way to reset coinTypes struct?


Solution

  • Unless you are just misunderstanding what the keyword static does (you probably are), this is what you are asking for:

    run online

    #include <iostream>
    
    struct britishCoins {
        int tenP;
        int twentyP;
        int fiftyP;
    };
    
    britishCoins& getCoins () {
        static britishCoins coins {0, 0, 0};
        return coins;
    }
    
    void resetCoins () {
        getCoins() = {0, 0, 0};
    }
    
    britishCoins numberOfCoins(int coins)
    {
        britishCoins& result = getCoins();
        result.tenP += coins / 10;
        //...
        return result;
    }
    
    int main () {
        std::cout << numberOfCoins(0).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        resetCoins();
        std::cout << numberOfCoins(0).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        std::cout << numberOfCoins(10).tenP << std::endl;
        return 0;
    }
    

    Prints:

    0
    1
    2
    3
    4
    0
    1
    2
    3
    4
    

    If you just want to convert int coins into britishCoins without storing it's value inside the function it's simple:

    run online

    #include <iostream>
    
    struct britishCoins {
        int tenP;
        int twentyP;
        int fiftyP;
    };
    
    britishCoins numberOfCoins(int coins)
    {
        britishCoins result;
        result.fiftyP = coins / 50;
        coins %= 50;
        result.twentyP = coins / 20;
        coins %= 20;
        result.tenP = coins / 10;
        return result;
    }
    
    int main () {
        for (int i = 0; i < 3; ++i) {
            britishCoins coins = numberOfCoins(130);
            std::cout << coins.fiftyP << "*50 + " << coins.twentyP << "*20 + " << coins.tenP << "*10" << std::endl;
        }
        return 0;
    }
    

    output:

    2*50 + 1*20 + 1*10
    2*50 + 1*20 + 1*10
    2*50 + 1*20 + 1*10