Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Unions Vs Struct.

Unions Vs Struct.

Scheduled Pinned Locked Moved C / C++ / MFC
visual-studioquestion
11 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    Prakash Nadar
    wrote on last edited by
    #1

    I have read in a couple of places that unions should not be used unless its very essential! I do not understand why? sometimes I create unions with many struct in it. Does any one has any idea on why unions should not be prefered ?


    -Prakash

    K V S 3 Replies Last reply
    0
    • P Prakash Nadar

      I have read in a couple of places that unions should not be used unless its very essential! I do not understand why? sometimes I create unions with many struct in it. Does any one has any idea on why unions should not be prefered ?


      -Prakash

      K Offline
      K Offline
      ky_rerun
      wrote on last edited by
      #2

      Unions are not "type" safe since the same data element can be represented by two different types.


      a programmer traped in a thugs body

      P 2 Replies Last reply
      0
      • K ky_rerun

        Unions are not "type" safe since the same data element can be represented by two different types.


        a programmer traped in a thugs body

        P Offline
        P Offline
        Prakash Nadar
        wrote on last edited by
        #3

        ky_rerun wrote:

        Unions are not "type" safe since the same data element can be represented by two different types.

        Well that is whole purpose of unions, plus there are many other data types which are not type safe.


        -Prakash

        1 Reply Last reply
        0
        • P Prakash Nadar

          I have read in a couple of places that unions should not be used unless its very essential! I do not understand why? sometimes I create unions with many struct in it. Does any one has any idea on why unions should not be prefered ?


          -Prakash

          V Offline
          V Offline
          vallikumar
          wrote on last edited by
          #4

          Members of unions cannot have an incomplete type, type void, or function type. Therefore members cannot be an instance of the union but can be pointers to the union type being declared. A union type declaration is a template only. Memory is not reserved until the variable is declared. If a union of two types is declared and one value is stored, but the union is accessed with the other type, the results are unreliable. For example, a union of float and int is declared. A float value is stored, but the program later accesses the value as an int. In such a situation, the value would depend on the internal storage of float values. The integer value would not be reliable.

          C 1 Reply Last reply
          0
          • P Prakash Nadar

            I have read in a couple of places that unions should not be used unless its very essential! I do not understand why? sometimes I create unions with many struct in it. Does any one has any idea on why unions should not be prefered ?


            -Prakash

            S Offline
            S Offline
            Stephen Hewitt
            wrote on last edited by
            #5

            I general, the purpose of a union is to save space. Say you're storing data for a fruit and you have 3 types: Apples, Oranges and Pears. The representaion of these three fruits is distinct and a fruit can only be 1 of these types. Consider a struct that embodies this design:

            struct Fruit
            {
                 Type m_Type; // Tells us if we're and apple, orange or pear.
                 Apple m_Apple;
                 Orange m_Orange;
                 Pear m_Pear;
            };
            

            If we using this to save our fruit data to disc only one of the three types would actually contain valid data - The space occupied by the others is wasted. We can improve on this by using a union.

            struct Fruit
            {
                 Type m_Type; // Tells us if we're and apple, orange or pear.
                 union
                 {
                     Apple m_Apple;
                     Orange m_Orange;
                     Pear m_Pear;
                 } m_Data
            };
            

            With this format we don't waste as much space - the size of the union m_Data is the size of its largest member and all members occupy the same memory. As the previous posters indicated - This saving comes at a price - Danger! Steve

            O Q 2 Replies Last reply
            0
            • S Stephen Hewitt

              I general, the purpose of a union is to save space. Say you're storing data for a fruit and you have 3 types: Apples, Oranges and Pears. The representaion of these three fruits is distinct and a fruit can only be 1 of these types. Consider a struct that embodies this design:

              struct Fruit
              {
                   Type m_Type; // Tells us if we're and apple, orange or pear.
                   Apple m_Apple;
                   Orange m_Orange;
                   Pear m_Pear;
              };
              

              If we using this to save our fruit data to disc only one of the three types would actually contain valid data - The space occupied by the others is wasted. We can improve on this by using a union.

              struct Fruit
              {
                   Type m_Type; // Tells us if we're and apple, orange or pear.
                   union
                   {
                       Apple m_Apple;
                       Orange m_Orange;
                       Pear m_Pear;
                   } m_Data
              };
              

              With this format we don't waste as much space - the size of the union m_Data is the size of its largest member and all members occupy the same memory. As the previous posters indicated - This saving comes at a price - Danger! Steve

              O Offline
              O Offline
              Owner drawn
              wrote on last edited by
              #6

              Stephen Hewitt wrote:

              This saving comes at a price - Danger!

              What Danger!

              Jesus Loves:rose:

              --Owner Drawn:rose: --Nothing special --Defeat is temporary but surrender is permanent --Never say quits --Jesus is Lord:rose:

              S 1 Reply Last reply
              0
              • O Owner drawn

                Stephen Hewitt wrote:

                This saving comes at a price - Danger!

                What Danger!

                Jesus Loves:rose:

                --Owner Drawn:rose: --Nothing special --Defeat is temporary but surrender is permanent --Never say quits --Jesus is Lord:rose:

                S Offline
                S Offline
                Stephen Hewitt
                wrote on last edited by
                #7

                Hard to spot casts:

                union Voodoo
                {
                    int m_Number;
                    IUnknown* m_pUnk;
                };
                
                Voodoo v;
                v.m_Number = 5;
                v.m_pUnk->AddRef(); // Danger!!!!!
                

                What happens here is effectively something like the following:

                reinterpret_cast<IUnknown*>(5)->AddRef();
                

                In fact this is an old "C" trick used to perform casts which are otherwise illegal. Steve

                O 1 Reply Last reply
                0
                • S Stephen Hewitt

                  Hard to spot casts:

                  union Voodoo
                  {
                      int m_Number;
                      IUnknown* m_pUnk;
                  };
                  
                  Voodoo v;
                  v.m_Number = 5;
                  v.m_pUnk->AddRef(); // Danger!!!!!
                  

                  What happens here is effectively something like the following:

                  reinterpret_cast<IUnknown*>(5)->AddRef();
                  

                  In fact this is an old "C" trick used to perform casts which are otherwise illegal. Steve

                  O Offline
                  O Offline
                  Owner drawn
                  wrote on last edited by
                  #8

                  Smoking is injurious to health but still some smoke.

                  Jesus Loves:rose:

                  --Owner Drawn:rose: --Nothing special --Defeat is temporary but surrender is permanent --Never say quits --Jesus is Lord:rose:

                  1 Reply Last reply
                  0
                  • S Stephen Hewitt

                    I general, the purpose of a union is to save space. Say you're storing data for a fruit and you have 3 types: Apples, Oranges and Pears. The representaion of these three fruits is distinct and a fruit can only be 1 of these types. Consider a struct that embodies this design:

                    struct Fruit
                    {
                         Type m_Type; // Tells us if we're and apple, orange or pear.
                         Apple m_Apple;
                         Orange m_Orange;
                         Pear m_Pear;
                    };
                    

                    If we using this to save our fruit data to disc only one of the three types would actually contain valid data - The space occupied by the others is wasted. We can improve on this by using a union.

                    struct Fruit
                    {
                         Type m_Type; // Tells us if we're and apple, orange or pear.
                         union
                         {
                             Apple m_Apple;
                             Orange m_Orange;
                             Pear m_Pear;
                         } m_Data
                    };
                    

                    With this format we don't waste as much space - the size of the union m_Data is the size of its largest member and all members occupy the same memory. As the previous posters indicated - This saving comes at a price - Danger! Steve

                    Q Offline
                    Q Offline
                    QuickDeveloper
                    wrote on last edited by
                    #9

                    the other simple method is u can process the items on the fly...

                    Stephen Hewitt wrote:

                    union { Apple m_Apple; Orange m_Orange; Pear m_Pear; } m_Data

                    for eg as mentioned above u can use 3 types of fruits.... read the quantity of apples for each vendor eg. v1.apple v2.apple and perform the calculations...then v1.orange,v2.orange...(since u don't need v1.apple again)and do the calculations..in that way u can perform computations and re-use the memory this is just one specific instance though hope that helps:)

                    1 Reply Last reply
                    0
                    • V vallikumar

                      Members of unions cannot have an incomplete type, type void, or function type. Therefore members cannot be an instance of the union but can be pointers to the union type being declared. A union type declaration is a template only. Memory is not reserved until the variable is declared. If a union of two types is declared and one value is stored, but the union is accessed with the other type, the results are unreliable. For example, a union of float and int is declared. A float value is stored, but the program later accesses the value as an int. In such a situation, the value would depend on the internal storage of float values. The integer value would not be reliable.

                      C Offline
                      C Offline
                      cmk
                      wrote on last edited by
                      #10

                      vallikumar wrote:

                      A union type declaration is a template only. Memory is not reserved until the variable is declared.

                      ? Not sure what you are trying to say. Memory allocation (actually, setting a new high-water mark for the stack) for all stack variables is deferred until the start of the block they are declared in. It sounds like you are trying to say that mem alloc is different for unions than for int's, struct's, ... The size of a union is known at compile time (just like a struct) - it is the size of the largest member. ...cmk Save the whales - collect the whole set

                      1 Reply Last reply
                      0
                      • K ky_rerun

                        Unions are not "type" safe since the same data element can be represented by two different types.


                        a programmer traped in a thugs body

                        P Offline
                        P Offline
                        Prakash Nadar
                        wrote on last edited by
                        #11

                        ky_rerun wrote:

                        Unions are not "type" safe since the same data element can be represented by two different types.

                        i guess you have a good point check here http://www.weirdrealm.com/prog/cppstds.html[^] it says, Unions Avoid unions, as they defeat strong type-checking and are very difficult to verify in a debugger.


                        -Prakash

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups