Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests - Download the BYJU'S Exam Prep App for free GATE/ESE preparation videos & tests -

Introduction to Union in C | GATE Notes For CSE

Introduction to Union in C | GATE Notes For CSE

Union is an important topic belonging to the world of programming and coding languages. And, when it comes to a competitive examination like GATE, you have to read the whole topic quite deeply. In this article, we have covered all the topics relevant to the union. We hope the GATE notes for the CSE topics will help you understand this topic in a better way.

What is Union?

Unions are the user defined data type. They are conceptually similar to structures. The syntax to define a union is also similar to that of a structure. The only difference is in terms of storage. In a structure, each member has its own storage location, whereas all members of a union use a single shared memory location, which is equal to the size of its largest data member.

How to Define a Union?

Syntax:

union student

{

char name[50];

int roll number;

};

How to Create a Union Variable?

When a union is represented, it makes a user-defined type. Nevertheless, in this condition, no memory is assigned. To assign the memory, we ought to build variables.

Let’s see how we can construct variables:

union student

{

char name[50];

int roll number;

};

int main()

{

union student stu1, stu2, *stu3;

return 0;

}

There is one more aspect of creating a union variable:

union student

{

char name[50];

int roll number;

} stu1, stu2, *stu3;

Accessing a Member in Union

Example – Full Program:

#include <stdio.h>

Union School{

float percentage;

int studentNo;

} j;

int main() {

j.percentage = 12.3;

// when j.student No is assigned a value,

// j.percentage will no longer hold 12.3

j.workerNo = 100;

printf(“Percentage = %.1f\n”, j.pPercentage);

printf(“Number of students= %d”, j.studentNo);

return 0;

}

Output of the Above Code:

Percentage= 0.0

Number of Students= 100

Frequently Asked Questions on Union in C

Q1

What is Union?

Union is the user-defined data type, just like structure.

Keep learning and stay tuned to get the latest updates on GATE Exam along with GATE Eligibility Criteria, GATE 2023, GATE Admit Card, GATE Syllabus for CSE (Computer Science Engineering), GATE CSE Notes, GATE CSE Question Paper, and more.

Comments

Leave a Comment

Your Mobile number and Email id will not be published.

*

*