Search code examples
c++arraysstaticinitialization

How to initialize a static array to certain value in a function in c++?


I am trying to init a static array in a function.

int query(int x, int y) {
    static int res[100][100]; // need to be initialized to -1
    if (res[x][y] == -1) {
        res[x][y] = time_consuming_work(x, y);
    }
    return res[x][y];
}

How can I achieve this?


Solution

  • First of all, I strongly recommend moving from C arrays to std::array. If you do this you can have a function to perform the initialization (otherwise you can't, as a function cannot return C arrays):

    constexpr std::array<std::array<int, 100>, 100> init_query_array()
    {
        std::array<std::array<int, 100>, 100> r{};
        for (auto& line : r)
            for (auto& e : line)
                e = -1;
        return r;
    }
    
    int query(int x, int y) {
        static std::array<std::array<int, 100>, 100> res = init_query_array();
    
        if (res[x][y] == -1) {
            res[x][y] = time_consuming_work(x, y);
        }
        return res[x][y];
    }
    

    Another option, that I actually like more is to perform the init in a lambda:

    int query(int x, int y) {
        static auto res = [] {
            std::array<std::array<int, 100>, 100> r;
            for (auto& line : r)
                for (auto& e : line)
                    e = -1;
            return r;
        }();
    
        if (res[x][y] == -1) {
            res[x][y] = time_consuming_work(x, y);
        }
        return res[x][y];
    }