Initialize an array in a struct

Viewed 174

Is there already a way where I can initialize an array directly in a struct? Like this:

struct S
{
  int arr[50] = {5};  
}

I know this only initializes the first element of the array, but is there any way to write something similar with g++ but that can initialize all elements of the array with 5?

I've read that with gcc we can use designated intializers int arr[50] = {[0 ... 49] = 5}; but this won't be possible in C++.

1 Answers

Since a struct object needs to have its constructor called when being initialized you can just perform this assignment inside the constructor, e.g.:

struct S
{
  int arr[50];  
  S() {
    for (int& val : arr) val = 5;
  }
};

Or similarly you can use std::fill from the algorithm header

#include <algorithm>
struct S
{
  int arr[50];  
  S() {
    std::fill(std::begin(arr), std::end(arr), 5);
  }
};
Related