albertgumi
albertgumi

Reputation: 342

initialize a union array at declaration

I'm trying to initialize the following union array at declaration:

typedef union { __m128d m;  float f[4]; } mat;
mat m[2] = { {{30467.14153,5910.1427,15846.23837,7271.22705},
{30467.14153,5910.1427,15846.23837,7271.22705}}};

But I'getting the following error:

matrix.c: In function ‘main’:
matrix.c:21: error: incompatible types in initialization
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[0]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[0]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[0]’)
matrix.c:21: error: incompatible types in initialization
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[1]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[1]’)
matrix.c:21: warning: excess elements in union initializer
matrix.c:21: warning: (near initialization for ‘m[1]’)

Upvotes: 6

Views: 17899

Answers (3)

Dmitry Poroh
Dmitry Poroh

Reputation: 3825

Try to change members:

typedef union {
    float f[4];
    __m128d m;
} mat;
mat m[2] = { { {30467.14153,5910.1427,15846.23837,7271.22705},
               {30467.14153,5910.1427,15846.23837,7271.22705} } };

If you initialize union without member specification like .f = { ... } then first member of union is initialized.

Upvotes: 0

cdhowie
cdhowie

Reputation: 169038

You need to indicate which union field you are initializing. Try using this syntax:

mat m[2] = {
    {.f = {30467.14153,5910.1427,15846.23837,7271.22705}},
    {.f = {30467.14153,5910.1427,15846.23837,7271.22705}}
};

This successfully compiled for me, without any warnings.

Upvotes: 3

unwind
unwind

Reputation: 399871

Quoting this page:

With C89-style initializers, structure members must be initialized in the order declared, and only the first member of a union can be initialized.

So, either put the float array first, or if possible use C99 and write:

mat m[2] = { { .f = { /* and so on */ } }, /* ... */ };

The important thing being the .f.

Upvotes: 15

Related Questions