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
Yes --- but that doesn't have anything to do with what you're trying to do here.
Sorry -- I thought you were referring to casting the variable itself as a (void *).
No such thing in C51. You may get lucky for a while --- but there's really _no_ being sure.
This [1] is disconcerting then, since it implies that this process is deterministic.
Have you ever heard of functions like memcpy(), or memcmp()? Why, do you think, is their argument of type (void *)? Why do you think the argument of the Standard C Library's generic "write whatever this is to a file" function, fwrite(), takes its argument as a (void *)?
Sure I have, but they are written to be as generic as possible. I was trying to use some of the specificity I have available to simplify things a bit. By passing a pointer to the variable, I am necessitating that the user of the function have a variable in which their data is stored; using this method, they couldn't do something like:
do_something(load(i)+x);
but would instead need to do something like
y = load(i) + x; do_something(&y);
Certainly this is not the end of the world, I was just trying to make it an easier function to use.
If this is the extent to what I can do with C(x)51, then that answers my question -- you can't do it without a dummy variable. I already have several solutions (that are more appropriate for my particular code) that use these dummy variables.
--- [1] http://www.keil.com/support/man/docs/c51/c51_ap_parampassreg.htm