Copyright

Unions in C Programming: Definition & Example

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Linked Lists in C Programming: Definition & Example

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:04 Unions in C Programming
  • 0:56 Example
  • 1:26 Union vs Structure Difference
  • 2:21 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor
Meghalee Goswami

Meghalee has a masters of computer science and communication engineering.

Expert Contributor
Elaine Chan

Dr. Chan has a Ph.D. from the U. of California, Berkeley. She has done research and teaching in mathematics and physical sciences.

This lesson defines and demonstrates unions in C programming. It also explains how to allocate memory to unions and how they are different from structures. Code examples are provided for better explanation.

Unions in C programming

Union is a data type in C programming that allows different data types to be stored in the same memory locations. Union provides an efficient way of reusing the memory location, as only one of its members can be accessed at a time. A union is used almost in the same way you would declare and use a structure. Let's see this as an example.

Here's how it works with syntax.


union Record{ 
 int i;
 float f;
 char str[10];
} record;


In this example, we initialized a union named Record which had three data members. A reference to this union is created, which is called as record.

In the earlier declared union, the memory occupied by the union will be the memory required for the largest member of the union. In this case the union will occupy 10 bytes of memory space, as the character string occupies the maximum space. The following shows the total memory size. If you print sizeof(record), this will give you the size of the union, which in this case will be 10.

Example

In this example, we will use the aforementioned union called record. We can access the data members of the union using the '.' operator.


#include <stdio.h>
#include <string.h>
union Record { 
  int i;
  float f;
  char str[20];
};
int main( ) { 
 
  union Record record;
 
  record.i = 10;
  record.f = 220.5;
  strcpy( record.str, "C Programming");
 
  printf( "record.i : %d\n", record.i);
  printf( "record.f : %f\n", record.f);
  printf( "record.str : %s\n", record.str);
 
  return 0;
}



record.i : 1917853763
record.f : 4122360580327794860452759994368.000000
record.str : C Programming

As we see from the output, the value of record.i and record.f is corrupted. This is because the final memory assignment was done to record.str, which is why on printing record.str, it gives the correct value. In order to print the correct values of each data member, it's better to use the printf statement one at a time as follows:


record.i = 10;
printf( 'record.i : %d\n', record.i);
record.f = 220.5;
printf( 'record.f : %f\n', record.f);
strcpy( record.str, 'C Programming');
printf( 'record.str : %s\n', record.str);


Union vs. Structure Difference

The difference between a union and a structure is that:

  • A structure uses all the memory of its data members. A union uses only the largest memory space of the data member.
  • In a structure, all members can be accessed at any time. In case of unions, only one data member can be accessed at a particular time; all the other data members will contain corrupt values.

Let's see how we can use unions as members of structures in this example.


To unlock this lesson you must be a Study.com Member.
Create your account

Additional Activities

Unions in C


Union, is almost like a struct with available memory related to the largest variable in the union. It has been used for communications and to access hardware. If you do use unions to save space, you need to keep track of what variable is being accessed in the union.


Questions


1. Write code to print out the values of U.a, U.S.x and U.S.b in the following program:


#include <stdio.h>

union job

{

    struct data

    {

         int x;

         double b;

    }S;

    int a;

} U;

int main() {

    U.S.b=7;

    U.a=4;

    U.S.x=5;

    

    printf("%d %d %f\n",U.a,U.S.x,U.S.b);

    // U.a is overwitten . Fix the problem.

    // your code

    return 0;

 }


2. Initialize and print the following union variables: 7, and 7.0 using the following program that has a union and a member to track what's in the union inside a structure.


#include <stdio.h>

#include <stdlib.h>

/* code for types in union */

#define FLOAT_TYPE 1

#define CHAR_TYPE 2

#define INT_TYPE 3

struct S{

      int type_in_union;

      union{

              float un_float;

              char un_char;

              int un_int;

      }U;

}S;

void print_vt(void){

      switch(S.type_in_union){

              default:

                    printf("Unknown type in union\n");

                     break;

              case FLOAT_TYPE:

                      printf("%f\n", S.U.un_float);

                      break;

              case CHAR_TYPE:

                      printf("%c\n", S.U.un_char);

                      break;

              case INT_TYPE:

                      printf("%d\n", S.U.un_int);

                      break;

      }

}

int main(){

      S.type_in_union = FLOAT_TYPE;

      S.U.un_float = 3.5;

      print_vt();

      S.type_in_union = CHAR_TYPE;

      S.U.un_char = 'a';

      print_vt();

     

      // Your Code

      return 0;

      

}


Answers


1. Write code to print out the values of U.a, U.S.x and U.S.b in the following program:

Add the lines:


U.S.b=7;

printf("U.S.b= %f\n", U.S.b);

U.a=4;

printf("U.a= %d\n",U.a);

U.S.x=5;

printf("U.S.x= %d\n" ,U.S.x);


2. Initialize and print the following union variables: 7 and 7.0


S.type_in_union = INT_TYPE;

S.U.un_int = 7;

print_vt();

S.type_in_union = FLOAT_TYPE;

S.U.un_float = 7.0;

print_vt();

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support