Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union


2013-10 2013-09 2013-08

C Programming Union

October 2, 2013 Posted by: GPA Views: 28811 0 comments


What are the differences between a union and a structure in C?


Union like a structure stores different types of variables, but it allows you to use one of the elements, because they're all stored at the same spot. Only one member, and thus one data type, can be referenced at a time. A structure has a separate memory location for each of its members and they all can be used at anytime. Unions contain two or more data types.

Structure Definition

A union is declared with keyword union in the same format as a structure.

union car{

    double price; 

   char name[20];  


This union definition indicates that car is a union type with members double price and char name[20]. 

Initializing Union 

In main function or in other function You can declare:

union car car1; 

Accessing Union Members 

One operator are used to access members of unions: 

 - member access operator(.);

There is difference in memory allocation between union and structure. You can see it in example below. All members of structure can be accessed at anytime. But, only one member of union can be accessed at a time in case of union and other members will contain bad values. When You use union, car price will be printed incorrect, but when you use structure all data are printed correct. Why does program print name correct, but price incorrect?  The memory stores a union variable with largest element of an union. The size of name variable is 20 and the size of price variable  is 8 that's why program shows name in correct format.
Let's see this example and you will see difference between union and structure.



#include <stdio.h>
#include <stdlib.h>
union car{
double price;
char name[20];
struct carstruct{
double price;
char name[20];
int main(int argc, char *argv[])
//using union
union car car1;
printf("\nUsing union\n");

//using structure
struct carstruct car2;
printf("\n\nUsing struct\n");

"\n\nSize of union = %d\n",sizeof(car1));
printf("Size of structure = %d\n",sizeof(car2));

printf("\n\nSize of union name = %d\n",sizeof(;
printf("Size of union price = %d\n",sizeof(car1.price));

return 0;



Download this example


Leave a Reply

Please, Sing In to leave a Reply for this material.

Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration


New materials