How to initialize a union?

47,296

Solution 1

In C99, you can use a designated union initializer:

union {
      char birthday[9];
      int age;
      float weight;
      } people = { .age = 14 };

In C++, unions can have constructors.

In C89, you have to do it explicitly.

typedef union {
  int x;
  float y;
  void *z;
} thing_t;

thing_t foo;
foo.x = 2;

By the way, are you aware that in C unions, all the members share the same memory space?

int main () 
{
   thing_t foo;
   printf("x: %p  y: %p  z: %p\n",
     &foo.x, &foo.y, &foo.z );
   return 0;
}

output:

x: 0xbfbefebc y: 0xbfbefebc z: 0xbfbefebc

Solution 2

There is difference between initialization and assignment. Initialization is intelligent, while for the assignment you need to resolve proper address.


    Example
    char str[] = "xyz";    // works - initialization 
    char str[10];
    str = "xyz";            // error - assignment
                           // str is a address that can hold char not string

    Similarly
    Ptrlist l = {NULL};    // works - initialization 
    Ptrlist *l;
    l->next = NULL;        // works assignment
    l = {NULL};            // is assignment, don't know the address space error

Share:
47,296

Related videos on Youtube

lexer
Author by

lexer

Updated on July 09, 2022

Comments

  • lexer
    lexer almost 2 years

    If it's a struct then it can be done

    *p = {var1, var2..};
    

    But seems this doesn't work with union:

    union Ptrlist
    {
            Ptrlist *next;
                State *s;
    };
    
    Ptrlist *l;
    l = allocate_space();
    *l = {NULL};
    

    Only to get:

    expected expression before ‘{’ token
    
    • James Wilcox
      James Wilcox almost 13 years
      you have two pointer types in your union. which one are you trying to initialize to null? how do you expect the compiler (or this reader) to know?
    • lexer
      lexer almost 13 years
      @James Wilcox ,I know I can do it by u.field1=NULL;u.field2=NULL but isn't that kind of redundancy?
    • James Wilcox
      James Wilcox almost 13 years
      the question is which field you're trying to initialize in the above code. neither me nor the compiler has any idea if it's supposed to be next or s that you're trying to access.
    • lexer
      lexer almost 13 years
      @James Wilcox,I want to initialize all fields to NULL.
    • James Wilcox
      James Wilcox almost 13 years
      I think you misunderstand what a union is then. only one field may be (safely) used at a time. if you want to be able to access both fields, you need a struct. if you just want to make sure the whole damn thing is nulled out, you can pick either one in this case, since the pointer types (probably) have the same length.
    • M.M
      M.M over 9 years
      *p = {var1, var2..}; does not work for struct either
    • ysap
      ysap over 6 years
      @JamesWilcox - ptr types probably have the same length, and not less important will most probably occupy the same space in memory (i.e., alignment). But, this is not guarantied, so I'd consider your comment as "dangerous". One could use a declaration attribute like "packed" or similar to increase the chances that this is correct, but once you go to the realm of implementation dependent code, then you could verify that the members are aligned even w/o the attribute.