Advantage of unions.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nirmalsingh
    New Member
    • Sep 2006
    • 218

    Advantage of unions.

    What is the advantage of unions in C++?
    What are the situations to use unions?
    With Cheers
    -Nirmal
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    Union are basically used to save space.
    Code:
    struct s {
    int temp1;
    char temp2;
    } s1;
    
    union u {
    int temp1;
    char temp2;
    } u1;
    when you take the size of both then you will see the difference.
    in case of structure sizeof(s1) = 5 whereas in caes of union sizeof(u1) = 4

    Hope this helps! :)

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      This question has been asked here several times. Example .

      Comment

      • docesam
        New Member
        • Sep 2009
        • 1

        #4
        the amount of memory space conserved is so small to the multi-gigabyte computers seen today to the extend that i would like to ask : is the a redundant c++ feature ?

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          No its not redundent, remove the union and all legacy code that suddenly uses it would not only stop working but would require a major rewrite. You can not remove things from the language only add things.

          If on the other hand you mean is there a place for the union in a modern program design then the answer is probably no much. However if you had asked the same question 20 years ago of C programmers then the answer would probably have been the same. The union has always been one of the less used language features in my experience and usage has never been about saving space but rather either an easy way to create a polymorphic pointer or a convenient method for converting binary variables to/from a byte stream.

          Comment

          • DelphiCoder
            New Member
            • Jul 2009
            • 24

            #6
            Unions can be thought of "variants" in other programming languages.

            Comment

            Working...