Union is a space saver construct.
A discriminated union must be declared in a struct, and must use an integral expression as the discriminator. The C switch statement syntax is used to select from the choices, as shown in this example,
struct primitive_t
{
char choice;
union switch( choice )
{
case 'i': int ival;
case 'c': char cval;
case 'd': double dval;
} value;
};
A discriminated union must be defined without a tag name, to prevent it
from being used outside of the struct.
The corresponding C declaration of the above is,
struct primitive_t
{
char choice;
union
{
int ival;
char cval;
double dval;
} value;
};
To use the type primitive_t, you must assign the choice field, and the corresponding union member, as shown in the following example,
struct primitive_t aprim;
/* we are using it as a double */
aprim.choice = 'd';
aprim.value.dval = 9.9 ;
/* now we can use aprim in an RPC */
Sometime we may want to use a union to represent optional data. To do this,
we simply set the discriminator to a case not listed in the ``switch
statement". Thus, if we set the choice to a undefined case,
aprim.choice = -1;no data will be transfered when aprim is later used in an RPC argument.
A usual C union declaration is also allowed. However, it will be treated as opaque data in powerRPC, that is the raw bytes (non-portable) of the union will be transfered across the network.