Re: passing a union's field to a function
- From: Ian Collins <ian-news@xxxxxxxxxxx>
- Date: Sat, 12 Aug 2006 10:14:33 +1200
Mikhail Teterin wrote:
Think of your union as an object. If you had written
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?
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 reportsWhat else did you expect?
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...
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.
.
- Follow-Ups:
- Re: passing a union's field to a function
- From: Mikhail Teterin
- Re: passing a union's field to a function
- References:
- passing a union's field to a function
- From: Mikhail Teterin
- Re: passing a union's field to a function
- From: Richard Heathfield
- Re: passing a union's field to a function
- From: Mikhail Teterin
- Re: passing a union's field to a function
- From: Richard Heathfield
- Re: passing a union's field to a function
- From: Mikhail Teterin
- Re: passing a union's field to a function
- From: Ian Collins
- Re: passing a union's field to a function
- From: Mikhail Teterin
- passing a union's field to a function
- Prev by Date: Re: Need Help Declaring a Pointer to an Array of Structures
- Next by Date: Re: need def for conio.h
- Previous by thread: Re: passing a union's field to a function
- Next by thread: Re: passing a union's field to a function
- Index(es):
Relevant Pages
|