473,785 Members | 2,807 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
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:

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 #11
>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
Nov 13 '05 #12
>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
Nov 13 '05 #13
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:

Expand|Select|Wrap|Line Numbers
  1.  #include <stdio.h>
  2.  struct bitfield_s
  3.  {
  4.    unsigned int b0:1;
  5.    unsigned int b1:1;
  6.    unsigned int b2:1;
  7.    unsigned int b3:1;
  8.    unsigned int b4:1;
  9.    unsigned int b5:1;
  10.    unsigned int b6:1;
  11.    unsigned int b7:1;
  12.  };
  13.  union bitfield_e
  14.  {
  15.    unsigned char c;
  16.    struct bitfield_s s;
  17.  };
  18.  int main ()
  19.  {
  20.    union bitfield_e b;
  21.    unsigned char c = 0x12;
  22.    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
    Nov 13 '05 #14
    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:

    Expand|Select|Wrap|Line Numbers
    1.  #include <stdio.h>
    2.  struct bitfield_s
    3.  {
    4.    unsigned int b0:1;
    5.    unsigned int b1:1;
    6.    unsigned int b2:1;
    7.    unsigned int b3:1;
    8.    unsigned int b4:1;
    9.    unsigned int b5:1;
    10.    unsigned int b6:1;
    11.    unsigned int b7:1;
    12.  };
    13.  union bitfield_e
    14.  {
    15.    unsigned char c;
    16.    struct bitfield_s s;
    17.  };
    18.  int main ()
    19.  {
    20.    union bitfield_e b;
    21.    unsigned char c = 0x12;
    22.    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
    Nov 13 '05 #15
    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.

    Nov 13 '05 #16
    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
    Nov 13 '05 #17

    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
    13386
    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
    2837
    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
    1767
    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
    3374
    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
    1929
    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
    2025
    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
    10336
    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
    10155
    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
    8978
    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
    6741
    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
    5383
    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...
    0
    5513
    by: adsilva | last post by:
    A Windows Forms form does not have the event Unload, like VB6. What one acts like?
    1
    4054
    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
    3655
    muto222
    by: muto222 | last post by:
    How can i add a mobile payment intergratation into php mysql website.
    3
    2881
    bsmnconsultancy
    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...

    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.