IDL also supports a union type, which is a cross between the C union
and switch statements. The syntax of a union type declaration
is as follows: union identifier switch ( switch-type
)
{ case+ }
The "identifier" following the union keyword defines a new legal type. (Union types may also be named using a typedef declaration.) The "switch-type" specifies an integral, character, boolean, or enumeration type, or the name of a previously defined integral, boolean, character, or enumeration type. Each "case" of the union is specified with the following syntax:
case-label+ type-spec declarator ;
where "type-spec" is any valid type specification; "declarator" is an identifier, an array declarator (such as, foo[3][5]), or a pointer declarator (such as, *foo); and each "case-label" has one of the following forms:
case const-expr:
default:
The "const-expr" is a constant expression that must match or be automatically castable to the "switch-type". A default case can appear no more than once.
Unions are mapped onto C/C++ structs. For example, the following IDL declaration:
union Foo switch (long) { case 1: long x; case 2: float y; default: char z; };
is mapped onto the following C struct:
typedef Hello_struct { long _d; union { long x; float y; char z; } _u; } Hello_foo;
The discriminator is referred to as "_d", and the union in the struct is referred to as "_u". Hence, elements of the union are referenced just as in C:
Foo v; /* get a pointer to Foo in v: */ switch(v->_d) { case 1: printf("x = %ld\n", v->_u.x); break; case 2: printf("y = %f\n", v->_u.y); break; default: printf("z = %c\n", v->_u.z); break; }
Note: This example is from The Common Object Request Broker: Architecture and Specification, revision 1.1, page 90.