Initialize union members - using MS visual studio

You need to initialize the member of the union at compile time. Reading some articles, it seems that there is no other way than defining only the first entry in the union. If you are not using C99, you can define each member of the union specifically.

The thing is, I'm using Visual Studio 2010 Prof. it doesn't seem to support C99, or how can I enable ist? Or is there another way to initialize a member of a union?

thank

typedef union {
int a;
char *atxt;
} MY_UNION_t;
typedef struct {
int foo;
MY_UNION_t un;
}GEN_DATA_t;

/* need to do following: */
GEN_DATA_t obj1 = {0,1}; /* Okay works */
GEN_DATA_t obj2 = {0,"bla"}; /* Does not work */

/* ISO C99 allows: */
GEN_DATA_t obj3 = {0,.atext="bla"}; /* However MS VS seem not to support this */
+3
source share
2 answers

When initializing a union, the first named member of the union is the one to be initialized (ISO 9899: 1999 6.7.8 §17).

, C99, , , . C99, -, VS.

, :

typedef union {
char *atxt;
int a;
} MY_UNION_t;

/* make sure that the string "bla" isn't allocated in read-only memory, 
   since you intend to point at it with a non-const pointer */
char bla[] = "bla";  

GEN_DATA_t obj2 = {0, bla}; 
+4

All Articles