This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Casting to a union type without using a dummy variable

Hi all,

I am trying to find a way to cast a value to a union type without the use of a dummy variable. My union definition is something like

typedef union _MY_UNION {
    unsigned long u32;
    unsigned int  u16;
    unsigned char u8;
    signed long s32;
    signed int  s16;
    signed char s8;
    float fl;
} my_union;


I have discovered that I can assign a value to the union at initialization using a line like

my_union z = { 0 };

which works fine. It assumes the first union member as the type of the assignment, so ends up doing the same thing as

my_union z;
z.u32 = 0;

except in a much cleaner fashion.

Now for the tricky part -- I have a function that accepts this union type, i.e.

void do_union(my_union u) { ... }

and I would like to be able to call this function without having to pass through a dummy variable first, i.e.

do_union(z);              // works as expected, given the definition of z above
do_union(0);              // C193 incompatible operand
do_union((my_union)0);    // C215 illegal type conversion
do_union((my_union){0});  // C141 syntax error near '{' (as expected; this is initialization syntax)


I get the exact same errors if I use a variable of any member type (including the first) instead of the constant 0. The only way I have been able to get this to work is to use a dummy union variable, i.e.

unsigned long i;
my_union t;
[...]
t.u32 = i;
do_union(t);


Is there any way to get around this, and let me call the function directly without the use of a dummy variable?

Regards,
-Scott