4

Possible Duplicate:
Can a union be initialized in the declaration?

I've looked all over the internet and can't find an example of how to set the value of a union within a struct at compile time and I'm hoping that you guys and gals can help me out. For instance, a simple struct would be :

typedef enum {
     typeFloat,
     typeInt
} Type;

typedef struct myStruct { 
     Type     elementType;
     int      valueInt;
     float    valueFloat;
} myStruct;

and then you could declare a local variable with :

myStruct structEx = {typeInt, 349, 0};

or

myStruct structEx = {typeFloat, 0, 349.349};

How would you do the same if the struct was declared as :

typedef struct myStruct {
     Type     elementType;
     union value {
          int     valueInt;
          float   valueFloat;
     } value;   
} myStruct;

The "value" will be either a float or an int with the "elementType" allowing it to know which it was.

I know you can set it during runtime with :

myStruct structEx;
structEx.elementType = typeInt;
structEx.value.valueInt = 349;

but I haven't found a way to do it as above with the struct.

Thanks in advance.

Edit : This is duplicate. I should've been using the word "initialization" and it would've taken me straight to that one. My Google-Fu must be weak today. Thanks.

Community
  • 1
  • 1

1 Answers1

3

How about:

myStruct structEx = {
    .elementType = 0,
    .value = {
        .valueInt = 42
    }
};

Or maybe

myStruct structEx = {
    .elementType = 0,
    .value.valueInt = 42
};
cnicutar
  • 178,505
  • 25
  • 365
  • 392