I want to store a calculated const array such that a[i] = i*i -3;
Here is what I was thinking, but I'm not sure:
constexpr int fun(int x) {
return x * x - 3;
}
template<int N>
struct A {
constexpr A() : array() {
for (auto i = 0; i != N; ++i) array[i] = fun(i);
}
int array[N];
};
const A<4> array1{};
const int array2[] = {-3, -2, 1, 6};
I think array1 is initialized, not stored in the executable like array2.
Is it possible to do this without using a macro?
.rodatasection. What you might experience is the compiler removing the variable because it does not detect any reference to it. If you want to make sure it is visible from the outside regardless of being used or not, declare your variable asextern: see gcc.godbolt.org/z/E-M9r5arrayin the initializer list rather than the constructor body.