1. Technology

C Programming Tutorial - Low Level Operations


9 of 10

Where would you use a Union?
The uses of union are few and far between. 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.
 union intptr {
   int i;
   int * p;
 union intptr x;
 x.i = 1000;
 *(x.p)=90; /* puts 90 at location 1000 */ 
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..
 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;
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.
 union messagetype ackmsg;
 ackmsg.fixed.size = sizeof(msgack) ; /* 16 */

On the next page - Packing Bits with Bit Fields

  1. About.com
  2. Technology
  3. C / C++ / C#
  4. C Programming
  5. C Tutorials
  6. Where would you use a Union?

©2014 About.com. All rights reserved.