Unions

T

Tim Cambrant

Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

Thanks.
 
T

Thomas Matthews

Tim said:
Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

Thanks.

One method of using unions is in message formats. Many messages have
a common part and a variable part. A union would help keep the messages
the same length even though their parts vary.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 
K

Kevin Easton

Tim Cambrant said:
Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

One place is where you want a data structure that stores a small set of
different types of objects - for example, if you're writing a
stack-based expression parser, you might want a stack that can hold
Constants, Functions, and Operators. You could implement this as a
stack of nodes containing a union, so that each node can take be of one
of the three possible types.

- Kevin.
 
F

Fred L. Kleinschmidt

Tim said:
Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

Thanks.

One common type of usage of a union is the definition of an XEvent:
typedef union _Xevent {
int type;
XAnyEvent xany;
XButtonEvent xbutton;
XKeyEvent xkey;
/* Many more specific event structs */
} XEvent;

Each of the event structs in this union represents one of the possible X
events.
The programmer can thus use
void myfunction( XEvent *event );
in his code, then check the 'type' field to see what kind of event it
is, then
cast the variable to the appropriate struct within the union. For
example,
if ( event->type == KeyPress ) {
keycode = ((XKeyEvent *)event)->keycode;
/* ... do something based on the keycode */
}
else if ( event->type == ButtonPress ) {
button = ((XButtonEvent *)event)->button;
/* ... do something based on which button was pressed */
}

thus "myfunction" can be used for any type of event.
 
T

Thomas Stegen

Tim Cambrant said:
Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

Sometimes you need a structure where only one field will be filled
at one time but the values are of different types.

For example if you write an interpreter.

struct value
{
int type;
union
{
int ival;
double dval;
char *sval;
} val;
};

Since a value can only have one value :)p) but values can have
different types several fields are needed even though only one
is used at any given time.
 
M

Mike Wahler

Tim Cambrant said:
Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

Admittedly contrived:

#include <stdio.h>


union datum /* A single data entity whose exact
type is not yet known, but is of
the type of one of the members 'i'
or 'd' */
{
int i;
double d;
};

/* a function which receives a union and a 'flag',
which outputs the designated (by the 'flag') type
using printf() with the appropriate type specifier */
void foo(union datum dat, char which)
{
switch(which) /* I just love saying that :) */
{
case 'i': /* is it type 'int'?
printf("%d\n", dat.i); /* use %d */
break;
case 'd': /* is it type 'double'?
case 'f': /* is it type 'float'?
printf("%f\n", dat.d); /* use %f */
break;
default: /* catch unknown 'flag' value */
printf("I don't know what '%c' means\n", which);
}
}

int main()
{
union datum ud; /* an instance of the union */
int ivalue = 42; /* an int */
double dvalue = 3.14; /* a double */

ud.i = ivalue; /* store an int in a union member */
foo(ud, 'i'); /* send to output func */

ud.d = dvalue; /* store a double in a union member */
foo(ud, 'd'); /* send to output func */

foo(ud, 'a'); /* intentional bad 'flag' */

return 0;
}

You'd typically use a union when you want to store
(and/or pass to a function) a single data entity item
whose type might vary. Of course this information
(which type is it really) must also be passed along
to any functions which want to use the stored value
(some designs put the union and the 'flag' inside
a struct, and switch on the struct's' 'flag' member
for desired type dependent behavior ).

(Only the union member whose value was last stored
can be subsequently retrieved. E.g. if I set ud.i
to something, accessing ud.f would give undefined
behavior.

More about unions in a good C text.

-Mike
 
N

Nathan

Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

Another application of unions is the following. Assume you have a
datacommunication application which receives bytes and in your application
you want to access the individual bits in some way. Then you could define a
union in which you have a bitfield of 8 bits and an unsigned char. Now you
can assign incoming bytes to the unsigned char member and access the
individual bits by using the bitfield member.

I've implemented this in the following example:

Code:
#include <stdio.h>

struct bitfield_s
{
  unsigned int b0:1;
  unsigned int b1:1;
  unsigned int b2:1;
  unsigned int b3:1;

  unsigned int b4:1;
  unsigned int b5:1;
  unsigned int b6:1;
  unsigned int b7:1;
};

union bitfield_e
{
  unsigned char c;
  struct bitfield_s s;
};

int main ()
{
  union bitfield_e b;
  unsigned char c = 0x12;
  int i;

  b.c = c;
  printf ("%d%d%d%d%d%d%d%d\n", b.s.b7, b.s.b6, b.s.b5, b.s.b4,
    b.s.b3, b.s.b2, b.s.b1, b.s.b0);

  return 0;
}


Regards,
Nathan
 
T

Tim Hagan

Nathan said:
Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

Another application of unions is the following. Assume you have a
datacommunication application which receives bytes and in your application
you want to access the individual bits in some way. Then you could define a
union in which you have a bitfield of 8 bits and an unsigned char. Now you
can assign incoming bytes to the unsigned char member and access the
individual bits by using the bitfield member.

I've implemented this in the following example:

Code:
#include <stdio.h>

struct bitfield_s
{
unsigned int b0:1;
unsigned int b1:1;
unsigned int b2:1;
unsigned int b3:1;

unsigned int b4:1;
unsigned int b5:1;
unsigned int b6:1;
unsigned int b7:1;
};

union bitfield_e
{
unsigned char c;
struct bitfield_s s;
};

int main ()
{
union bitfield_e b;
unsigned char c = 0x12;
int i;[/QUOTE]

i isn't used.
[QUOTE]
b.c = c;
printf ("%d%d%d%d%d%d%d%d\n", b.s.b7, b.s.b6, b.s.b5, b.s.b4,
b.s.b3, b.s.b2, b.s.b1, b.s.b0);[/QUOTE]

This looks like a lot of b.s. to me. :-)

Isn't this implementation-dependent, i.e. non-portable.
BTW, I get '01001000' on my machine.
[QUOTE]
return 0;
}
 
B

Bigdakine

Subject: Unions
From: "Tim Cambrant" (e-mail address removed)
Date: 9/24/03 4:23 AM Hawaiian Standard Time
Message-id: <[email protected]>

Hi. I was reading up a bit on the features of C I seldom use, and I came
across unions. I understand the concept, and that all the contained
variables etc. share the same memory. Thus, when a new value is declared to
a variable in the union, the existing value is overwritten even though the
new value is declared to a different variable than that of the first value.

Now I'm just wondering what the use of this is. I'm sure there are lots, so
I'm not critizising, but I just don't see a use for unions. Could someone
give me a few concrete examples of when to use unions?

I've used them to represent multidimensional data as both linear and
multi-dimensional arrays.

Stuart
 
K

Kevin Easton

Fred L. Kleinschmidt said:
One common type of usage of a union is the definition of an XEvent:
typedef union _Xevent {
int type;
XAnyEvent xany;
XButtonEvent xbutton;
XKeyEvent xkey;
/* Many more specific event structs */
} XEvent;

Each of the event structs in this union represents one of the possible X
events.
The programmer can thus use
void myfunction( XEvent *event );
in his code, then check the 'type' field to see what kind of event it
is, then
cast the variable to the appropriate struct within the union. For
example,
if ( event->type == KeyPress ) {
keycode = ((XKeyEvent *)event)->keycode;
/* ... do something based on the keycode */
}

....but this isn't using the union-ness of the union at all - you might
as well just be using struct pointers. However, if you write it as:

if (event->xany.type == KeyPress) {
keycode = event->xkey.button;
/* ... do something based on the keycode */

then you're fully using the union (this assumes that XAnyEvent and
XKeyEvent are structs that have a common initial element called "type").

- Kevin.
 
J

Jack Klein

One common type of usage of a union is the definition of an XEvent:
typedef union _Xevent {

Of course this is illegal code and produces undefined behavior,
because all identifiers beginning with an underscore followed by
either another underscore or an upper case letter are reserved for the
implementation in all contexts.
int type;
XAnyEvent xany;
XButtonEvent xbutton;
XKeyEvent xkey;
/* Many more specific event structs */
} XEvent;

Each of the event structs in this union represents one of the possible X
events.
The programmer can thus use
void myfunction( XEvent *event );
in his code, then check the 'type' field to see what kind of event it
is, then
cast the variable to the appropriate struct within the union. For
example,
if ( event->type == KeyPress ) {
keycode = ((XKeyEvent *)event)->keycode;
/* ... do something based on the keycode */
}
else if ( event->type == ButtonPress ) {
button = ((XButtonEvent *)event)->button;
/* ... do something based on which button was pressed */
}

thus "myfunction" can be used for any type of event.

....and the code is wrong, too.

If event->type exists in the union, there is no XKeyEvent there.

What you really mean is:

enum message_type
{
MSG_TYPE_1,
MSG_TYPE_2,
/* ... */
};

union
{
struct event_type_1; /* assume previous definition */
struct event_type_2;
} event_types;

struct event_struct
{
enum message_type type;
union event_type event;
};

I have found that proper coding standards forbid assigning both a
typedef and a tag to a union or struct unless absolutely required for
a forward declaration. 99% of all structure and enumeration types do
not need both.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

unions within an array 10
Arrays of Unions 21
Unions Redux 26
properly using unions. 9
Leading padding in unions 25
gcc, aliasing rules and unions 3
Extending unions and ABI? 12
Unions, storage, ABI's 10

Members online

Forum statistics

Threads
474,082
Messages
2,570,588
Members
47,209
Latest member
Ingeborg61

Latest Threads

Top