Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialize an array in a struct

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++.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading