Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]’)
like image 429
albertgumi Avatar asked Jul 19 '12 10:07

albertgumi


People also ask

How do you initialize a union?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

Can we initialize union in C?

C allows you to initialize a union in two ways: Initialize a union by initializing the first member of a union. Or initialize a union by assigning it to another union with the same type.

How do you initialize an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.


1 Answers

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.

like image 166
unwind Avatar answered Oct 04 '22 11:10

unwind