I am trying to init a static array in a function.
int query(int x, int y) {
static int res[100][100]; // need to
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, 100> init_query_array()
{
std::array, 100> r{};
for (auto& line : r)
for (auto& e : line)
e = -1;
return r;
}
int query(int x, int y) {
static std::array, 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, 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];
}