The same to this in a compile time

How to have this at compile time instead

1
2
3
 for (int i = 0; i < 41; ++i)
     interval[i] = 0;
You mean something like this?
 
int interval[41]{};
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.

1
2
3
4
5
6
7
8
#include <algorithm>
#include <iterator>

int main()
{
	int interval[41];
	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[41] {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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <array>

template < std::size_t N > requires ( (N>0) == true )
constexpr std::array<int,N> make_filled_array( int v = 0 )
{
    std::array<int,N> arr ;
    arr.fill(v) ;
    return arr ;
}

template < std::size_t N >
constexpr long long sum( const std::array<int,N>& 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<N>(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
Topic archived. No new replies allowed.