In the previous post, we have discussed how to declare and initialize arrays in C/C++. This post will discuss how to initialize all array elements with the same value in C/C++.

1. Using Initializer List

To initialize an array in C/C++ with the same value, the naive way is to provide an initializer list like,

 
The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

2. Using Designated Initializers

With GCC compilers, we can use designated initializers. To initialize a range of elements to the same value, we can write [first ... last] = value.

3. Using Macros

We can’t use the initializer list with large arrays, and designated initializers will only work with the GCC compilers. For initializing a huge array with the same value, we can use macros, as shown below:

Download  Run Code

Output:

The size of the array is 45
The value of any element is 1

4. Using For loop

We can also use for-loop to initialize an array, but the initialization won’t happen in a single line.

5. Using std::fill_n function

Finally, we can use std::fill_n in C++, which assigns a value to the first n array elements.

Download  Run Code

Output:

1

That’s all about initializing all array elements to the same value in C/C++.