CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Jul 2005
    Posts
    15

    Unhappy what's the use of union?

    Please, can any one explain me, how/when to use union with examples?
    Thanks in advance.

  2. #2
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

  3. #3
    Join Date
    Jul 2005
    Location
    Germany
    Posts
    1,194

    Re: what's the use of union?

    For example in a MP3 tag (ID3v1) after the year of release you can either store a 30 chars long comment or you store only a 28 chars long comment a terminating zero and the track number. The data structure would look like this:
    Code:
    struct ID3v1
    {
      char cTag[3];             // Always "TAG"
      char cTitle[30];          // Song title
      char cArtist[30];         // Artist name
      char cAlbum[30];        // Album name
      char cYear[4];            // Year of release
      union
      {
        char cCommentTrack[30]; // Comment with 30 chars
        struct
        {
          char cComment[28];    // Comment with 28 chars
          unsigned char nZero;  // Terminating zero
          unsigned char nTrack; // Track number
        };
      };
      unsigned char nGenre;     // Genre
    };
    You can see that in the union you have cCommentTrack for alternative one and the struct for alternative two. The advantage: You don't have to worry about the different data formats when you read it in.
    Please don't forget to rate users who helped you!

  4. #4
    Join Date
    Jan 2001
    Posts
    588

    Re: what's the use of union?

    Edit: Oops, misread the previous post. Carry on.

  5. #5
    Join Date
    Sep 2004
    Posts
    561

    Re: what's the use of union?

    Here is a great use for unions:

    How do I impose a packet scheme?

  6. #6
    Join Date
    Apr 2003
    Location
    kathmandu, nepal
    Posts
    1,570

    Re: what's the use of union?

    Also,

    U can use Unions to represent different types that are not related to one another but wanna use them polymorphically.

    In places where u cannot use inheritance and where u know the exact types and number of types and the types are in actuality not realated to each other u can use Unions.

    For example:

    Code:
    struct MyField
    {
        enum TypeTag { One, Two, Three, 
                  Four, Five } Type;
       
        union
        {
            FirstType TypeOne;
            SecondType TypeTwo;
            ThirdType TypeThree;
            FourthType TypeFour;
            FifthType TypeFive;
        };
      };
    Type contains the current type
    If there is no love sun won't shine

  7. #7
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: what's the use of union?

    Unions can be used for portability.

    For example, it is often useful (for a C program) to pass user data to a callback function.
    And the user may want to pass much data. In that case, a void* parameter as context parameter is good.
    But, the user may also want to pass just a small integer value, because he does not need much data.

    But, there are platforms where sizeof(void*)!=sizeof(int), so the user cannot (if he want to write a portable program) uses static cast to cast the int to void*, and then void* to int back in his callback function.
    So, he would need to allocate memory for this integer variable (dynamically, in some cases), and then free the memory when the callback function is no more needed.
    That is not very efficient, although it is generally not a real problem, and may introduce memory leaks if the programmer is not very attentive.

    That is why, instead of a void* or an integer value, the best, for the library/system developer, is to define an union:
    Code:
    union context_val
    {
    int int_val;
    void* pointer_val;
    };
    A good example, of that usage, can be found in the Realtime Signal Extensions option of the Single UNIX Specification.

    The sigval union is passed as parameter to the signal-notification-handling procedure.
    And sigval contains these fields:
    Code:
    int    sival_int    Integer signal value. 
    void  *sival_ptr    Pointer signal value.
    The user-defined sigevent structure is used to specify how the event signal is raised, and contains a signal number, but also a sigval value.

    On the other side, the Win32 API, which is not bound to the C language, defines an UINT_PTR type instead. The "layout" of this type is defined by microsoft, and any language which wants to use this type must use a header/module which defines this type apropriately and allow to use its layout in a language-independent manner, although the header/module is language-specific.

    OLE's VARIANTs is another example of union usage.

    There are more usage of unions, good... and bad...
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  8. #8
    Join Date
    May 2004
    Posts
    75

    Re: what's the use of union?

    Quote Originally Posted by philkr
    For example in a MP3 tag (ID3v1) after the year of release you can either store a 30 chars long comment or you store only a 28 chars long comment a terminating zero and the track number.
    The terminating null is not required by the ID3v1 tag, just store 29 chars without terminating null. Sorry for being OT.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured