### The same to this in a compile time How to have this at compile time instead

 ``123`` `````` for (int i = 0; i < 41; ++i) interval[i] = 0; `````` You mean something like this?
 `` `` ``int interval{};``
Last edited on in
= 99; instead of =0;

? If you don't mind doing it after the array has been created, then you can use a loop as you did, or you could use std::fill.

 ``12345678`` ``````#include #include int main() { int interval; std::fill(std::begin(interval), std::end(interval), 99); }``````

Otherwise I think you'll simply have to repeat the value 99 41 times.

 `` `` ``int interval {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99};``
Last edited on std::array<T,N>::fill() has a constexpr specifier (C++20) https://en.cppreference.com/w/cpp/container/array/fill

 ``1234567891011121314151617181920212223242526`` ``````#include #include template < std::size_t N > requires ( (N>0) == true ) constexpr std::array make_filled_array( int v = 0 ) { std::array arr ; arr.fill(v) ; return arr ; } template < std::size_t N > constexpr long long sum( const std::array& std_array, std::size_t from = 0 ) // invariant: from < N { if( from == (N-1) ) return std_array[from] ; else return std_array[from] + sum( std_array, from+1 ) ; } int main() { constexpr std::size_t N = 41 ; constexpr int VALUE = -19 ; constexpr auto interval = make_filled_array(VALUE) ; static_assert( interval[N/2] == VALUE && sum(interval) == std::ptrdiff_t(N)*VALUE ) ; std::cout << "ok\n" ; }``````

https://coliru.stacked-crooked.com/a/dcac0a3c2d030780 It's worth mentioning that either way the CPU will end up either copying constant data from somewhere onto writable memory, or initializing writable memory in a loop. Just use std::fill() if the value is non-zero. There would be a run-time overhead if and only if the constexpr function is not evaluated at compile-time (its argument is not a constant expression) or if the constexpr result is copied into a non-constexpr variable.

https://godbolt.org/z/G5oKx8hEj There will also be a runtime cost if you use the compile-time-evaluated array to initialize a variable array, which I believe is what OP is doing. And that's what I mean; you can't avoid that cost. JLBorges wrote:
https://godbolt.org/z/G5oKx8hEj

It should be noted that foo() returns an int, not an array.

Using constexpr gives better guarantees but it is possible that the compiler might be able to optimize the code even without it: https://godbolt.org/z/qohG186eY
Last edited on
Registered users can post here. Sign in or register to post.