Unions within unions

In C, is it possible to define a union within another union? If not, why is this not possible? Or, if so, where can it be used?

+5
source share
5 answers

Suppose you want to define:

union myun {
  int x;
  sometype y;
};

where sometypeis typedefdetermined by the library you are using. If the library implemented it as a type of union, then it will be a union in the union, and it will make sense because you cannot (from a good design point of view) break the encapsulation of the type of library.

+6
source

, . , X Y X Y: . ... , ?

R.. answer , : , , , , .


EDIT. , , , , , . , (N1256 §6.5.2.3.5) C:

struct generic {
    unsigned tag;
};
struct smallnum {
    unsigned tag; /*always TAG_SMALLNUM*/
    unsigned value;
};
struct bignum {
    unsigned tag; /*always TAG_BIGNUM*/
    size_t length;
    unsigned *p;
};
struct string {
    unsigned tag; /*always TAG_STRING*/
    size_t length;
    char *p;
};
union number {
    struct bignum bignum;
    struct smallnum smallnum;
};
union object {
    struct generic generic;
    struct bignum bignum;
    struct smallnum smallnum;
    struct string string;
};

union object x, x.generic.tag ( x.bignum.tag ), , . () .

, , union level2 : union level2 union number, number, generic string. , , .

union level2 {
    struct generic generic;
    union number number;
    struct string string;
};
+3

, . . , , . , , , , .

+2

Yes it is possible. I can't think of good use of the top of my head, although it would be easy to come up with a contrived example.

+1
source

Yes, a union may contain another union:

union foo {
  int x;
  double y;
  union bar {
    char blah[10];
    char *blurga;
  } bletch;
};

I cannot think of a situation where this would be useful (or even desirable).

0
source

All Articles