Govt Exam Preparation Guidance & Previous Year Papers, Study Materials & Job Updates - For Engineers
Enter Your Email Address To Get Study Materials & Job Updates In Your Mail :

                             (Please activate subscription from your mail Inbox)  FeedBurner

Submit Your Resume/ CV Directly To Companies HR Trough Us - Free

Home » » What is Union explain with example

What is Union explain with example

What is Union explain with example

A union is a variable which may hold (at different times) objects of different sizes and types. C uses the union statement to create unions, for example:

          union number
                 short shortnumber;
                 long longnumber;
                 double floatnumber;
                 } anumber
defines a union called number and an instance of it called anumber. number is a union tag and acts in the same way as a tag for a structure.
Members can be accessed in the following way:

This clearly displays the value of longnumber.
When the C compiler is allocating memory for unions it will always reserve enough room for the largest member (in the above example this is 8 bytes for the double).
In order that the program can keep track of the type of union variable being used at a given time it is common to have a structure (with union embedded in it) and a variable which flags the union type:
An example is:

  typedef struct
                 { int maxpassengers;
                 } jet;

        typedef struct
                 { int liftcapacity;
                 } helicopter;

        typedef struct
                 { int maxpayload;
                 } cargoplane;

         typedef          union
                 { jet jetu;
                         helicopter helicopteru;
                         cargoplane cargoplaneu;
                 } aircraft;

        typedef          struct
                 { aircrafttype kind;
                         int speed;
                         aircraft description;
                 } an_aircraft;
This example defines a base union aircraft which may either be jet, helicopter, or
In the an_aircraft structure there is a kind member which indicates which structure is being held at the time.
Share this article :


Speak up your mind

Tell us what you're thinking... !

Search - Get Answer Of Your Question

Support : Campusnikalo | Job Search Site | Graduates Freshers Jobs
Copyright © 2011. Campus Nikalo - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger