Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array whose size is a compile-time constant to single value

Tags:

c++

c++11

I have a c-style array whose size is defined by a #define and can change based on compiling options, e.g.

#if LINUX
# define SIZE 4
#else
# define SIZE 5
#endif
static int myArr[SIZE] = { /* ??? */ };

How can I initialize the whole array to a non-zero value, for example all 42?

like image 588
Baruch Avatar asked May 30 '19 09:05

Baruch


People also ask

How do you initialize an array with a single value?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

What is the time complexity of initializing an array?

In theory, both have the same time complexity: O(N) , where N is the size of your array. However, the first method should be better, since it's up to the compiler to choose how to initialize as faster as possible (for instance, it could be done through memset ).

Can you initialize array with variable size?

But, unlike the normal arrays, variable sized arrays cannot be initialized.

How do you initialize an entire array with any value in CPP?

Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

What is the use of runtime initialization in C++?

Run time Array initialization Using runtime initialization user can get a chance of accepting or entering different values during different runs of program. It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf () function.

What is the general form of initialization of array in C?

The general form of initialization of array is as follows − Using runtime initialization user can get a chance of accepting or entering different values during different runs of program. It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf () function.

What is a compile time constant in Java?

Compile-Time Constants A Java variable is a compile-time constant if it's of a primitive type or String, declared final, initialized within its declaration, and with a constant expression. Strings are a special case on top of the primitive types because they are immutable and live in a String pool.

What is array in C?

Explain Compile time and Run time initialization in C programming? Let’s take the concept of arrays to about compile time and run time initialization − Array is a collection of items stored at contiguous memory locations and elements can access by using indices. In compile time initialization, user has to enter the details in the program itself.


3 Answers

I don't know a solution for C-style arrays, though with constexpr and C++17 you could do this with std::array.

constexpr std::array<int, SIZE> createFilledArray (int value){
   std::array<int, SIZE> a{0};
   for (auto i = 0; i < SIZE; ++i)
       a[i] = value;
   return a;
}

static constexpr auto myArr = createFilledArray(42);

Code at compiler explorer

The disadvantage of this is that you can't change the array. If you remove the constexpr from the variable, your compiler should be able to optimize this.

From C++20 on, you can force the initialization:

static constinit auto myArr = createFilledArray(42);

Not sure if the proposal is already merged in: see constinit proposal

like image 163
JVApen Avatar answered Oct 18 '22 23:10

JVApen


If you insist on builtin arrays, you can use static variables in functions:

template <std::size_t N, std::size_t... Is>
auto arr_helper2(std::index_sequence<Is...>) -> int (&)[N]
{
    static int arr[N] = {((void)Is, 42)...};
    return arr;
}

template <std::size_t N>
auto arr_helper() -> int (&)[N]
{
    return arr_helper2<N>(std::make_index_sequence<N>{});
}

static int (&arr)[SIZE] = arr_helper<SIZE>();

For example:

int main()
{
    for (std::size_t i = 0; i < SIZE; ++i)
        std::cout << arr[i] << " ";
}

live demo

like image 3
L. F. Avatar answered Oct 19 '22 00:10

L. F.


For the poor souls who are still limited to C++14, here's a C++14 solution that allows you to fill the C array according to a function fill:

#include <iostream>

constexpr int SIZE = 5;
constexpr int fill(std::size_t index){ return 42; }

template <int INDEX = 0, int... Values>
struct Helper : Helper<INDEX + 1, Values..., fill(INDEX)> {};

template <int... Values>
struct Helper<SIZE, Values...>{
    static constexpr int table[SIZE] = { Values... };
};

template <int... Values>
constexpr int Helper<SIZE, Values...>::table[SIZE];

int main() {
    auto constexpr arr = Helper<0>::table;
    for(int i = 0; i < SIZE; ++i){
        std::cout << arr[i] << '\n';
    }
}

However, note that this only works for integral types.

like image 1
joni Avatar answered Oct 18 '22 23:10

joni