Reputation: 51
I have code
int a[5];
for (int i = 0; i < 5; i++){
a[i] = i * i;
}
Is there a way to make this array constant so that other code can use it but not change it.
Upvotes: 0
Views: 538
Reputation: 5222
Using modern C++ (array
and an Immediately Invoked Lambda (IIL)), this can be achieved:
const auto a = []()
{
std::array< int, 5 > x;
for (int i = 0; i < 5; i++)
{
x[i] = i * i;
}
return x;
}(); // IIL
Using a lambda has benefits over a function call, that you can capture the local variables into the lambda and use them without the values passing through parameters ([&]
or [=]
instead of []
).
Just like a function the lambda can easily be inlined into your code, so there can be no overhead.
Upvotes: 0
Reputation: 62563
Easiest way is to use constexpr
function and the std::array
:
constexpr std::array<int, 5> make_array() {
std::array<int, 5> a{};
for (int i = 0; i < 5; i++){
a[i] = i * i;
}
return a;
}
//...
const std::array<int, 5> a = make_array();
NB. As noted by @M.M, this code is only valid for C++17, as pre-C++17 the operator[]
on array wasn't constexpr
.
Upvotes: 1