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.

Categories: C Programming. No Comments on Unions in C: Syntax and Example Program

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;

 

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();
}

 

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?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Leave a Reply

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