I’m porting some C code to C++ and I can’t resolve a particular issue dealing with sub-object inititialization.
The following code is an example of what I mean :
#include <stdio.h>
#define MY_INDEX 1
#define MY_OTHER_INDEX 3
/* Structure declaration */
struct my_struct
{
int a;
int b;
int c;
};
/* Array declaration and initialization */
struct my_struct my_array[] =
{
[0] = (struct my_struct) {0, },
[MY_INDEX] = ((struct my_struct) {
.a = 10,
.b = 20,
.c = 30
}),
[MY_OTHER_INDEX] = ((struct my_struct) {
.a = 42,
.b = 42,
.c = 42
})
};
/** Test code */
int
main(void)
{
unsigned int i;
for (i = 0; i < sizeof(my_array)/sizeof(struct my_struct); i++)
printf("Index %u: a=%d, b=%d, c=%d\n",
i, my_array[i].a, my_array[i].b, my_array[i].c);
return 0;
}
It can be compiled without warnings nor errors with gcc -ansi -Wall, although adding the -pedantic flag will throw some warnings stating that ISO C90 forbids specifying subobject to initialize.
The initialization of my_array will act like if :
- Index 0 will have a,b,c = 0
- Index 1 (
MY_INDEX) will have a=10, b=20, c=30 - Index 2 will also have a,b,c = 0
- Index 3 (
MY_OTHER_INDEX) will have a,b,c = 42
I really like this form of initialization, I find it concise and readable.
Using this syntax with C++ will result in GCC thinking I’m declaring a lambda function because of the [], and even without the index GCC tells me it expected primary-expression before ‘struct’.
What would be an equivalent in C++ (even with the C++11 standard) ? The key point is to be able to specify the structure fields name in the initializer for readability (the real structure have dozen of integer fields and bitfields), being able to also see the index in the initializer would be a plus too.
C++ doesn’t have all the special aggregate initializer syntax that C supports. Instead, say this:
You can’t have “gaps” in arrays (not even in C, I think).