Use of unions in C!!

Hi all,
I am puzzled by this little detail.

I know what is a structure, a union, their difference et all.
And I also know that structures are very important, they are used in every data structure (list, stack,queue etc..).

Now, where are unions used in C? Why is there a thing called union??

Replies

  • ms_cs
    ms_cs
    Union is...A less used but a powerful feature of C
    WHAT IS A UNION

    A union, is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time.

    You can picture a union as like a chunk of memory that is used to store variables of different types. Once a new value is assigned to a field, the existing data is wiped over with the new data.

    A union can also be viewed as a variable type that can contain many different variables (like a structure), but only actually holds one of them at a time (not like a structure). This can save memory if you have a group of data where only one of the types is used at a time. The size of a union is equal to the size of it's largest data member. In other words, the C compiler allocates just enough space for the largest member. This is because only one member can be used at a time, so the size of the largest, is the most you will need. Here is an example:

    ...
    union time
    {
    long simpleDate;
    double perciseDate;
    }mytime;
    ....
    The union above could be used to either store the current time (in seconds) to hold time accurate to a second. Or it could be used to hold time accurate to a millisecond. Presumably there are times when you would want one or the other, but not both. This declaration should look familiar
  • Saandeep Sreerambatla
    Saandeep Sreerambatla
    yep.. we can save memory using unions.
    if we want to declare an integer and a float then we declare only float and use as an integer and float where ever applicable using unions.
  • slashfear
    slashfear
    Hi Silver,

    Yes we can save memory using a union

    Here is where unions are used:

    Union may be useful when it is necessary to work with different representation of same binary data.
    For example, you need to store color data as four 8-bit unsigned char numbers. At the same time, you have to store this color data as one 32-bit unsigned integer. Union allows to use both representation(struct with 4 unsigned char and unsigned integer) at the same time, using same block of computer's memory.

    Union is used in case of libraries which return assorted data's. for example, say a stack library is present which can return an int or double depending on what is on top of stack.In such a case, the application layer should be able to receive from library either int or double. so in application layer we use union.

    On most computers, the size of a pointer and an int are usually the same this is because both usually fit into a register in the CPU. So if you want to do a quick and dirty cast of a pointer to an int or the other way, declare a union.
    [B]    union intptr {
          int i;
          int * p;
        };
    
        union intptr x;
    
        x.i = 1000;
        *(x.p)=90; /* puts 90 at location 1000 */ [/B]
    
    Another use of a union is in a command or message protocol where different size messages are sent and received. Each message type will hold different information but each will have a fixed part (probably a struct) and a variable part bit. This is how you might implement it..
      [B]  struct head {
          int id;
          int response;
          int size;
        };
    
        struct msgstring50 {
           struct head fixed;
           char message[50];
        }
    
        struct struct msgstring80 {
           struct head fixed;
           char message[80];
        }
          
        struct msgint10 {
           struct head fixed;
           int message[10];
        }
    
        struct msgack {
           struct head fixed;
           int ok;
        }
    
        union messagetype {
           struct msgstring50 m50;
           struct msgstring80 m80;
           struct msgint10 i10;
           struct msgack ack;
        }[/B]
    
    In practice, although the unions are the same size, it makes sense to only send the meaningful data and not wasted space. A msgack is just 16 bytes in size while a msgstring80 is 92 bytes. So when a messagetype variable is initialized, it has its size field set according to which type it is. This can then be used by other functions to transfer the correct number of bytes.
       [B] union messagetype ackmsg;
        ackmsg.fixed.size = sizeof(msgack) ; /* 16 */[/B]
    
    Hope this was useful to you and unwrapped your puzzle!!!!! 😉


    -Arvind (slashfear)
  • silverscorpion
    silverscorpion
    whoa, that's nice. Thanks for the explanation.
  • shalini_goel14
    shalini_goel14
    Slashfear is rocking here. We are really glad to have you here on CE Slashfear 😁
  • slashfear
    slashfear
    Thanks shalini its my pleasure to be here!!!!!! 😁

You are reading an archived discussion.

Related Posts

Hi friends Recently i bought Nokia 5800 express music edition Nokia gave some preloaded songs in the memory card which are with .dcf extension Doesn anyone have a software which...
well though this topic is not well related to Electronics but can we relate 4th dimension with electronics and if so then how ? As well uptil date even scientists...
how to find the mean,standard deviation and variance of an image?? i have tried the following code in MATLAB. can i get to know whether it's correct or not?? r_ch=file😀,:,1);...
can anyone share their ideas about some projects that can help solve some of our environmental issues which solutions can be formulated with the aid of concepts of electronics and...
Hello friends,I am prabhath kesav...an engineer from kerala...