union example program in C

By: Grenfel Emailed: 1598 times Printed: 2044 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. Unions provide a way to manipulate different kinds of data in a single area of storage, without embedding any machine-dependent information in the program. They are analogous to variant records in pascal.

As an example such as might be found in a compiler symbol table manager, suppose that a constant may be an int, a float, or a character pointer. The value of a particular constant must be stored in a variable of the proper type, yet it is most convenient for table management if the value occupies the same amount of storage and is stored in the same place regardless of its type. This is the purpose of a union - a single variable that can legitimately hold any of one of several types. The syntax is based on structures:

   union u_tag {
       int ival;
       float fval;
       char *sval;
   } u;
The variable u will be large enough to hold the largest of the three types; the specific size is implementation-dependent. Any of these types may be assigned to u and then used in expressions, so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another.

Syntactically, members of a union are accessed as

  union-name.member

or

  union-pointer->member

just as for structures. If the variable utype is used to keep track of the current type stored in u, then one might see code such as

   if (utype == INT)
       printf("%d\n", u.ival);
   if (utype == FLOAT)
       printf("%f\n", u.fval);
   if (utype == STRING)
       printf("%s\n", u.sval);
   else
       printf("bad type %d in utype\n", utype);
Unions may occur within structures and arrays, and vice versa. The notation for accessing a member of a union in a structure (or vice versa) is identical to that for nested structures. For example, in the structure array defined by
   struct {
       char *name;
       int flags;
       int utype;
       union {
           int ival;
           float fval;
           char *sval;
       } u;
   } symtab[NSYM];
the member ival is referred to as
   symtab[i].u.ival
and the first character of the string sval by either of
   *symtab[i].u.sval

   symtab[i].u.sval[0]
In effect, a union is a structure in which all members have offset zero from the base, the structure is big enough to hold the ``widest'' member, and the alignment is appropriate for all of the types in the union. The same operations are permitted on unions as on structures: assignment to or copying as a unit, taking the address, and accessing a member.

A union may only be initialized with a value of the type of its first member; thus union u described above can only be initialized with an integer value.

The storage allocator shows how a union can be used to force a variable to be aligned on a particular kind of storage boundary.


C Home | All C Tutorials | Latest C Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(1)


1. View Comment

Nice article...

View Tutorial          By: Sudhanshu at 2012-08-02 06:19:42

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Grenfel
Verifying a Signed JAR File example
Bitwise and Bit Shift Operators example in Java
JavaBeans Basic Concepts
The Differences Between Simple and Classic Tags in JSP
Bitwise Logical Operators in C
DispatchAction in Struts
union example program in C
Comparison operators in JSP
Basics of Structures in C
register Variables in C
Struts and Tiles - Steps to use Struts and Tiles
The if else statement in C
Character Counting sample program in C
Installing JSF
cin.ignore() in C++

More Tutorials in C
Sum of the elements of an array in C
Printing a simple histogram in C
Sorting an integer array in C
Find square and square root for a given number in C
Simple arithmetic calculations in C
Command-line arguments in C
Calculator in C
Passing double value to a function in C
Passing pointer to a function in C
Infix to Prefix And Postfix in C
while, do while and for loops in C
Unicode and UTF-8 in C
Formatting with printf in C
if, if...else and switch statements in C with samples
Statements in C

More Latest News
Most Viewed Articles (in C )
Using memset(), memcpy(), and memmove() in C
Formatting with printf in C
UNIX read and write system calls sample program in C
Constants and escape sequences in C
Table Lookup - hashtab - example program in C
fgets(), fputs() - Line Input and Output - sample program in C
A Storage Allocator sample program in C
Using realloc() Function in C
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
ERRNO.H Header File in C
Writing The First C program
Calculator in C
Passing double value to a function in C
Printing a simple histogram in C
Find square and square root for a given number in C
Most Emailed Articles (in C)
Conditional Expressions in C
fgets(), fputs() - Line Input and Output - sample program in C
Symbolic Constants using #define in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Address Arithmetic and pointers in C
Character Pointers and Functions in C
Initialization of Pointer Arrays in C
Tutorial on Complicated Declarations in C
Pointers to Structures example program in C
Using printf function in C
A Storage Allocator sample program in C
Using free() Function in C
The C Character Set
Writing The First C program
Formatting with printf in C