Re: passing a union's field to a function



Mikhail Teterin wrote:

Adding "-pedantic" does, indeed, elicit warnings you quote. So, is there a
way to pass a value to a union-expecting function, without creating a union
and copying the values around, as in:

testunion t;

t.i = i;
testfunc(t);

Why can't I just do:

testfunc(i)

? Is there any kind of ambiguity here?

Think of your union as an object. If you had written

typedef struct { int n; } X;

void testFn( X x ) {}

You wouldn't expect to be able to pass an int to testFn, same when the
parameter is a union.

The reason, I'm so insistant is not only having to copy values around and
create (seemingly) useless local variables.

Why worry? Let the compiler take care of optimising away local variables.

It is also that Purify reports
such passing of unions as a UMR (Uninitialized Memory Read), because other
(longer) fields of the union remain unitilized (such as the s.j field in my
sample union) and putting them onto stack (for a function call)
means "reading" them...

What else did you expect?

Using unions as function parameters is not a good idea in my opinion.
If you do, I'd recommend wrapping them in a simple struct with a member
used to indicate which member of the union is being passed:

typedef union {
int i;
void *p;
struct {
int i;
int j;
} s;
} testunion;


typedef struct {
enum { Int, Void, Struct} key;
testunion value;
} X;

static void testfunc( X* x ){}

int main(void)
{
X x;
x.key = Int;
x.value.i = 42;

testfunc( &x );

return 0;
}

--
Ian Collins.
.



Relevant Pages

  • Re: Pointer to "base" type - what does the Standard say about this?
    ... One such exception is to access equivalent initial members of structs ... that are union members. ... Don't make the base type a struct member, ... struct s {int i; const int ci;}; ...
    (comp.lang.c)
  • gcc, aliasing rules and unions
    ... struct B {int x, y;}; ... A struct pointer can be converted to another ... Also I don't know what the "effective type" of a union member is. ...
    (comp.lang.c)
  • Re: Is this legal ?
    ... I wanted to have a union which has two structures in it. ... b.c:10: warning: ANSI C forbids member declarations with no members ...
    (comp.lang.c)
  • Re: Some issue with pointers
    ... will be used to initialise the first union member. ... typedef struct menu { ... So I assumed I can use both the void pointer and the ... You can continue to use static initialisation. ...
    (comp.lang.c)
  • Re: Is this legal ?
    ... I wanted to have a union which has two structures in it. ... b.c:10: warning: ANSI C forbids member declarations with no members ...
    (comp.lang.c)