Date: Wed, 11 Nov 2026 09:13:10 +0100
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.
> 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.
Received on 2026-11-11 08:13:17
