C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Add array data initialization like in C

From: Robin Savonen Söderholm <robinsavonensoderholm_at_[hidden]>
Date: Wed, 11 Nov 2026 16:11:21 +0100
I personally think that a reason to include these in C++ is for stronger
compatibility with C. Sometimes we want or need to include C-headers into
our code. The more things you can do in C that is illegal or means
something else in C++, the harder such interoperability gets.
 But I am also aware that we are currently not, and probably never will be,
a proper superset of C. And I don't know how often this particular feature
gets used in headerfiles..

// Robin

On Wed, Nov 11, 2026, 09:13 David Brown via Std-Proposals <
std-proposals_at_[hidden]> wrote:

>
> On 10/11/2026 21:03, Comical USA via Std-Proposals wrote:
> > In C you can do
> > int a[5] = {
> > [3] = 2,
> > };
> >
> > which will make the array 0, 0, 2, 0, 0
>
> (It will make { 0, 0, 0, 2, 0 }.)
>
> >
> > but on C++ you can do that only with lambda or like this int a[] = { 0,
> > 0, 2, 0, 0 } or after initializating you must do a[3] = 2; and it's
> > pretty annoying, can we get in C++29 this C feature?
> >
>
> It's not simple to do with lambdas either (AFAIK), since arrays cannot
> be passed around by value - you can't have a lambda that returns an
> array value.
>
> But it is often a good idea to use std::array types rather than C-style
> arrays, if you can do that in your code.
>
> Then you can write :
>
> std::array<int, 5> b = [] consteval {
> std::array<int, 5> x {};
> x[3] = 2;
> return x;
> }();
>
>
> It is obviously not as neat or compact, but it is flexible if you want
> to do more in your initialisation (set a subrange to the same value,
> generate tables, or calculate your initial values in some other way).
> And if you have a pattern that you use a lot, you can write a helper
> function template or two.
>
>
> If the C-style array designated initializers can be added to C++ without
> conflict or ambiguity with lambdas, then I'd like that too.
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2026-11-11 15:11:38