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
16 3960
> 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: -
#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
>Subject: Unions From: "Tim Cambrant" ti*@cambrant.co m.net Date: 9/24/03 4:23 AM Hawaiian Standard Time Message-id: <uN************ *******@newsb.t elia.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?
I've used them to represent multidimensiona l data as both linear and
multi-dimensional arrays.
Stuart
>Subject: Unions From: "Tim Cambrant" ti*@cambrant.co m.net Date: 9/24/03 4:23 AM Hawaiian Standard Time Message-id: <uN************ *******@newsb.t elia.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?
I've used them to represent multidimensiona l data as both linear and
multi-dimensional arrays.
Stuart
Nathan 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?
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:
- #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;
-
-
i isn't used.
-
- 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);
-
-
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.
-
- return 0;
- }
-
--
Tim Hagan
Nathan 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?
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:
- #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;
-
-
i isn't used.
-
- 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);
-
-
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.
-
- return 0;
- }
-
--
Tim Hagan
Fred L. Kleinschmidt <fr************ *****@boeing.co m> wrote:
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 */ }
....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.
On Wed, 24 Sep 2003 15:40:43 GMT, "Fred L. Kleinschmidt"
<fr************ *****@boeing.co m> wrote in comp.lang.c:
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 {
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.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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?
|
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...
|
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;
};
|
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...
|
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;
};
| |
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.
...
|
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)
|
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...
|
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...
|
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...
|
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...
| |
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |