Learning C/C++ Step-By-Step - Page 11

11. Step-by-Step C/C++ --- C Programming - Unions


 1. Introduction
2. About Union
3. Declaration of a Union
4. Defining a Union Variable
5. Difference Between Structure and Union
6. Operations on Unions
7. Scope of a Union


1. Introduction


/* 81_union.c */
#include <stdio.h>
struct s_emp
            int eno;
            char name[20];
            float sal;
union u_emp
            int eno;
            char name[20];
            float sal;
int main()
            struct s_emp se;
            union u_emp ue;
            printf("\nSize of Employee structure    :  %d", sizeof(se));
            printf("\nSize of Employee Union      :  %d", sizeof(ue));
            return 0;

  Output: Size of Employee Structure : 26
Size of Employee Union : 20


2. About Union

When a large number of variables are requested to use in a program. They were occupies a large amount of memory. Unions provide an easiest way to save memory by using replacement technique. It uses same memory location for all type of variables.

A union is a data type in C, which allows the overlay of more than one variable in the same memory area.

Characteristics of Unions:

 1. Union stores values of different types in a single location in memory.
2. A union may contain one of many different types of values but only one is stored at a time.
3. The union only holds a value for one data type. If a new assignment is made the previous value has no validity.
4. Any number of union members can be present. But union type variable takes the largest memory occupied by its members.


3. Declaration of a Union

Union is a data type through which objects of different types and sizes can be stored at different times. Definition of a Union is same as a Structure. The only change in the declaration is the substitution of the keyword union for the keyword struct.



 union ddate
     int day;
     int month;
     int year;
union student
     int sno;
     char name[20];
     int marks;
     float avg;


4. Defining a Union Variable

Defining a Union variable is the same as structure and that for defining a built-in data type such as int.


int a; /* Valid */
union date d; /* Valid in both C and C++ */

Calculation of Union size

Every data type in C/C++ has a specified size, i.e int has 2 bytes of size, float has 4 bytes of size and so on. Here is the way to find the size of a Union variable.
sizeof :- This function is used to find the size of a given variable.


printf("%d", sizeof(int)); /* 2 */
printf("%d", sizeof(float)); /* 4 */
printf("%d", sizeof(union emp)); /* Displays the size of the emp union */


5. Difference between Structures and Unions

Here is the difference between Structures and Unions



1. It can hold different types (variables) in a single location.

1. It can hold different types (variables) in different locations.

2. It may contain more than one type (variable) but only one is stored at a time.

2. It may contain more than one type (variable) all are stored in memory at a time.

3. Any number of union members can be present. But union type variable takes the largest memory occupied by its member.

3. It requires memory of the size of all its members.

4. On its process only one member can be accessed at any given time.

4. On its process all the members can be access at any time.

5. The scope of union is the function and the scope of its members is also same as the union itself. (They can be accessed directly in the program).

5. The scope of Structure is the function only. Structure members are unable to access directly in the program.


6. Operations on Unions

A union is also similar to structure it can perform all the operations like structures. Operations on Union are listed below.

 • A union variable can be assigned to another union variable.
• A union Variable can be passed to a function as a parameter
• The address of the union variable can be extracted by using the address-of operator (&).
• A function can accept and return a union or a pointer to a union.

/* 82_union.c */
#include <stdio.h>
union u_emp
      int eno;
      char name[20];
      float sal;
int main()
      union u_emp ue;
      printf("Enter Employee Number  : "); scanf("%d", &ue.eno);
      printf("Enter Employee Name   : "); scanf("%s", ue.name);
      printf("Enter Employee Salary  : "); scanf("%f", &ue.sal);
      printf("\n\nEmployee Details are as follows...\n");
      printf("%d %s %f ", ue.eno, ue.name, ue.sal);
      return 0;

 What is the output?
Only ue.sal is correct. What about rest of variables.

At any instant only one of the union variables will have a meaningful value. Only that member, who is last written, can be read. At this point, other variables will contain garbage. It is the responsibility of the programmer to keep track of the active variable (i.e. variable which was last accessed).

Here is the best way to accept and display records of an employee.


/* 83_emp.c */
#include <stdio.h>
union u_emp
      int eno;
      char name[20];
      float sal;
int main()
      union u_emp ue;
      printf("\nEnter Employee Number  : "); scanf("%d", &ue.eno);
      printf("\n%d", ue.eno);
      printf("\nEnter Employee Name : "); scanf("%s", ue.name);
      printf("\n%s", ue.name);
      printf("\nEnter Employee Salary  : "); scanf("%f", &ue.sal);
      return 0;


7. Scope of a Union

The scope of union is different than structure. A structure variable can be accessed by the its functions only. Where as a union and its members can be accessed by its function.

 /* 84_scope.c */
#include <stdio.h>
int main()
          int i;
          char c;
          float f;
     i = 10; c = ‘a’; f = 4.5; /* Union members */
     printf("The value of c is : %c", c);
     return 0;
Share this page:

19 Comment(s)

Add comment


From: at: 2009-01-09 15:11:23

The tutorial looks so great. But I have some doubts. Why do you use "clrscr()" function and conio.h library, if you are using the C/C++ standard? (I found that in the pages number 4 and 5, but that is as far as i got).

From: Shantanu Goel at: 2009-01-08 04:44:05

Great tutorial Ganesh. And here is a link for people who finish your tutorial and want to learn a bit about how to make their code secure and optimized: Safer Code - Secure Coding in C/C++ This has a lot of stuff regularly published to cater to various security and performance related issues with C/C++ and anyone can follow it easily at a gradual pace.

From: at: 2009-01-20 16:25:53

I tried to lead learners from learning C to C++, so the pages 4 and 5 reflects most of the usage of C language, so it introduces users to learn about other header files.

From: Anonymous at: 2010-02-01 06:01:52

Very nice!

From: pickatutorial at: 2010-10-09 12:52:44

Great Work. Keep it up.

From: TodaysTech at: 2011-07-12 21:31:29

If anyone is interested, I have an ongoing blog that is covering the transition from the Business world to the Programming world.  Since it's from my own perspective, I think it can be easy to read and relate to for most first timers.


From: Crosility at: 2012-12-06 23:44:36

In the chart, it says 'vhar', not 'char'.

From: Jason at: 2013-04-16 14:58:31

Why using conio.h ?   It is not part of C standard, C++ standard, nor is it part of any Linux or Unix libraries.  

The inclusions of Microsoft specific libraries in chapters 4 & 5 have me doubting the validity the rest of the tutorial (learning c/cpp on Linux).

The tutorial is well written, however,  but I think it would be more appropriate on a .Net or Msdn blog. 

Thanks Ganesh!

From: Anonymous at: 2009-09-01 11:56:38


\* 0001_hello.c *\ and  \* 0001_hello.cpp *\


/* 0001_hello.c */ and /* 0001_hello.cpp */



From: Scott_R at: 2012-01-03 22:24:55

The numbering for the examples is off by one.

For example:

"10. Write a program to find the total and average marks of a student"

/* 11_stud.c */

From: Erica at: 2012-12-31 19:56:21

In 11_stud.c

avtg = total / 3;

should be

avg = total / 3;

Also the clrscr() function won't compile in g++. If others need you can add // to the start of the line and the line will become a comment.

From: Bob at: 2011-09-09 12:50:09

Ex 13 :

  if ( age >= 13 and age <= 19 ) printf("Teen Age");

  if ( age >= 20 and age <= 35 ) printf("Young Age");

  if ( age >= 36 and age < 50 ) printf("Middle Age");

should read as :

      if ( age >= 13 && age <= 19 ) printf("Teen Age");

      if ( age >= 20 && age <= 35 ) printf("Young Age");

      if ( age >= 36 && age < 50 ) printf("Middle Age");

From: Anonymous at: 2009-06-25 12:57:51

Example 14 would be less ....rectangular and much more triangular if, instead of

for (j=1;j<=5;j++)

one had

for (j=i; j<=5;j++)

From: Snehal at: 2009-06-15 07:00:15

In the difference between union and structure ,the names are misplaced ...means in union , structure points are placed and viceversa... Make it correct

From: bzero in c programming at: 2014-07-30 10:54:51


There is a bug in the number 4 example. You will get compilation error while running this program you will get a compilation error like below:

 binaryover.cpp:31:11: error: expected ‘;’ before ‘t1’

binaryover.cpp:32:6: error: ‘t3’ was not declared in this scope

binaryover.cpp:32:11: error: ‘t1’ was not declared in this scope

binaryover.cpp:32:16: error: ‘t2’ was not declared in this scope

Because you are using "using namespace std;" but in the standard library there is a function named time (). So, to solve the problem, you can change the name of the function time ()  to any other name like time1 (), then you will be able to run your code without any error. 


From: Abhijeet at: 2009-01-11 01:25:52

Though i haven't done it myself, mingw32 can create win32 executables from linux. As its description says "Minimalist GNU win32 (cross) compiler, A Linux hosted, win32 target, cross compiler for C/C++, Freedom through obsolescence. Those who still really need to can now build windows executables from the comfort of Debian." You could check it out.

From: Paul at: 2009-01-07 22:40:39

Thanks, this is a nice tutorial, I'm actually a php programer and I saw a lot similar with php's language, but I have a question:

Can I compile a c++ program under linux to make a .exe to run on windows and viceversa?

And how to do that if it is possible?

From: dbrion at: 2009-06-30 11:58:40

"Can I compile a c++ program under linux to make a .exe to run on windows "

Yes :

I confirm the last post and cross compilers can natively be found with recent Fedora (and any linux distribution, messeems!) The way all the stuff necessary could be downloaded and made working can be found with adaptations of :


(one just has to stop at "make xtools": they are downloaded and put into a proper place).

Else, if you like linux and have "only"  Windows, you can use cygwin (avoids dualbooting or switching to another computer)  with the sources (it is very rare that sources need to be different between both systems, they use the same compiler -gcc/g+++- and almost the same include file names.... ) ...


"and viceversa"

No (not because linux executables do not have a .exe suffix!):

 but you can edit/compile/test your program(s) under cygwin (google search can find it) until it works and port it (i.E the source, the compilation  and test scripts) to Linux (there is almost no effort, apart the efforts linked with different disk nomenclatures, of course).

 Else, unless emulating linux with vmplayer/qemu/vbox -all these emulators are Windows ported-? but it is more complicated than C/C++....

From: Iftekhar Ahmed at: 2010-05-14 19:31:55


Its relly helpful, I have 48 Hrs for my Exams..........................

Thanks for posting ............


Iftekhar Ahmed