Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » C Programming » Unions in C: Syntax and Example Program
Suryateja Pericherla Categories: C Programming. No Comments on Unions in C: Syntax and Example Program
0
(0)

In this article you will learn about Unions in C language. First you will learn what is a Union, its syntax and then an example program demonstrating unions in C language.

 

Unions have the same syntax as that of a structure since both of them are similar. However, there is a major difference between them in terms of memory allocation.

 

A structure is allocated memory for all the members of the structure whereas a union is allocated memory only for largest member of the union. This implies that, although a union may contain many members of different types, it can handle only one member at a time.

 

Like structure, a union can be declared using the union keyword as shown below:

union student
{
	char name[20];
	char grade;
};
union student s1,s2;
C

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


In the above code student is the name of the union. Also s1 and s2 are union variables. Memory is allocated only for name member of the union. So, the limitation on unions is: only one member can be used at a time. Unions can be used in all places where a structure is allowed.

 

Below is a C program to demonstrate a union:

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
    union student
    {
        char name[20];
        char grade;
        int marks;
    };
    union student s1;
    clrscr();
    strcpy(s1.name,"siva kumar");
    s1.grade = 'A';
    s1.marks = 98;
    printf("Name is: %s \n",s1.name);
    printf("Grade is: %c \n",s1.grade);
    printf("Marks are: %d",s1.marks);
    getch();
}
C

 

In the above program we will only get the correct value 98 for the member s1.marks as in a union only one value can b e used and stored at a time. We will get unexpected values for other members: name and grade.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory