2

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

5
  • 4
    Why not use a constructor? Commented Feb 13, 2022 at 0:15
  • It's a long story. I'm just asking if it's possible Commented Feb 13, 2022 at 0:17
  • 2
    It is possible by providing your own constructor. You'd need to explain why (you think) that is not good enough if you want a different answer Commented Feb 13, 2022 at 0:20
  • Can you please give me an example how is it possible by providing my own constructor Commented Feb 13, 2022 at 0:26
  • "Creative" alternative: struct S { std::array<int, 50> arr = []{ decltype(arr) rv; rv.fill(5); return rv; }(); }; Commented Feb 13, 2022 at 0:56

1 Answer 1

2

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); } }; 
Sign up to request clarification or add additional context in comments.

1 Comment

Yup - I believe std::fill() is exactly what the OP looking for :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.