473,770 Members | 6,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unions

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.

--
Tim Cambrant
<tim at cambrant dot com>
Nov 13 '05 #1
16 3957
Tim Cambrant wrote:
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.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 13 '05 #2
Tim Cambrant <ti*@cambrant.c om.net> wrote:
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.

Nov 13 '05 #3


Tim Cambrant wrote:

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.

--
Tim Cambrant
<tim at cambrant dot com>


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.
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Common User Interface Services
M/S 2R-94 (206)544-5225
Nov 13 '05 #4


Tim Cambrant wrote:

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.

--
Tim Cambrant
<tim at cambrant dot com>


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.
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Common User Interface Services
M/S 2R-94 (206)544-5225
Nov 13 '05 #5

"Tim Cambrant" <ti*@cambrant.c om.net> wrote in message
news:uN******** ***********@new sb.telia.net...
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.

--
Thomas.
Nov 13 '05 #6

"Tim Cambrant" <ti*@cambrant.c om.net> wrote in message
news:uN******** ***********@new sb.telia.net...
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.

--
Thomas.
Nov 13 '05 #7
"Tim Cambrant" <ti*@cambrant.c om.net> wrote in message
news:uN******** ***********@new sb.telia.net...
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
Nov 13 '05 #8
"Tim Cambrant" <ti*@cambrant.c om.net> wrote in message
news:uN******** ***********@new sb.telia.net...
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
Nov 13 '05 #9
> 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
datacommunicati on 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:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. struct bitfield_s
  4. {
  5. unsigned int b0:1;
  6. unsigned int b1:1;
  7. unsigned int b2:1;
  8. unsigned int b3:1;
  9.  
  10. unsigned int b4:1;
  11. unsigned int b5:1;
  12. unsigned int b6:1;
  13. unsigned int b7:1;
  14. };
  15.  
  16. union bitfield_e
  17. {
  18. unsigned char c;
  19. struct bitfield_s s;
  20. };
  21.  
  22. int main ()
  23. {
  24. union bitfield_e b;
  25. unsigned char c = 0x12;
  26. int i;
  27.  
  28. b.c = c;
  29. printf ("%d%d%d%d%d%d%d%d\n", b.s.b7, b.s.b6, b.s.b5, b.s.b4,
  30. b.s.b3, b.s.b2, b.s.b1, b.s.b0);
  31.  
  32. return 0;
  33. }
  34.  

Regards,
Nathan
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
5283
by: David | last post by:
Some developers in my group are using UNIONS to define their data types in a C++ program for an embedded system. Are there any pro and cons in doing this when you can define a CLASS to do the same thing? I guess there might be some additional overhead with CLASSES, but is that really an issue with today's computers?
8
1625
by: SteveM | last post by:
The general consensus I am getting is that nobody really uses unions much (engineers here at work) but this is an academic exercise for me so I am looking for an answer (I know there may be better ways to do this ;-) ). What I need to know is how to write the function prototype and the function definition for a function that returns a union. For example: Here is a class for a double linked list in which variable data is going to be...
6
13385
by: Neil Zanella | last post by:
Hello, I would like to know whether the following C fragment is legal in standard C and behaves as intended under conforming implementations... union foo { char c; double d; };
23
2835
by: rohit | last post by:
Hi, In my couple of years of experience, I have never found a single instance where I needed to use unions and bitfields(though I have used structures).I was just imagining where would these find relevance.Though both of these(bitfields and unions) are used where space is a constraint(so I can assume always in embedded systems,where memory is particularly less)and we want to save space/memory. As far as I have read, there is no...
4
1766
by: uralmutlu | last post by:
Hi, I was wandering if I can have classes in unions? I basically have source code in a format very similar to: union example { ClassA variable1; ClassB variable2; };
67
3372
by: bluejack | last post by:
A recent post asking for help with unions reminded me of this component of the C language that I have only used a couple of times, and those almost entirely out of personal whim -- Unions for the sake of Unions simply because I wanted to see one in action. Granted: it makes it possible to save a few bytes of storage when you have something that can be a chicken or a rooster, but not both, and you're always going to know which it is. ...
26
1926
by: Old Wolf | last post by:
Ok, we've had two long and haphazard threads about unions recently, and I still don't feel any closer to certainty about what is permitted and what isn't. The other thread topics were "Real Life Unions" and "union {unsigned char u; ...} ". Here's a concrete example: #include <stdio.h> int main(void)
11
2022
by: pereges | last post by:
Hello, can some one please guide me a little into using unions. I read about unions in K & R but I am finding it difficult to apply to my problem at hand. I want to save up some space by using unions . My questions are : 1. Is it dangerous to use unions ? Is it worth the trouble if I want to save memory ? Are they error prone ? 2. I read that it is not possible to access more than 1 member at any instant from a union. What does this...
0
9592
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10231
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10059
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8887
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6679
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5452
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3972
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.