Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a union? [duplicate]

Tags:

c

unions

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
like image 771
lexer Avatar asked Aug 10 '11 09:08

lexer


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 ( = ).

How do you declare a union in C++?

In C++17 and later, the std::variant class is a type-safe alternative for a union. A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.

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.

Can unions have constructors?

A union can have member functions (including constructors and destructors), but not virtual functions.


1 Answers

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

like image 89
Crashworks Avatar answered Oct 22 '22 10:10

Crashworks