0% found this document useful (0 votes)
13 views

Unit-8 Union Pps

Uploaded by

margi patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit-8 Union Pps

Uploaded by

margi patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

What is Union?

 Union is a user defined data type similar like Structure.


 It holds different data types in the same memory location.
 You can define a union with various members, but only one member can hold a
value at any given time.
 Union provide an efficient way of using the same memory location for multiple-
purpose.

1
Syntax to Define and Access Union
 Declaration of union must start with the keyword union followed by the union
name and union’s member variables are declared within braces.
Syntax
1 union union_name union_name is name of custom type.
2 {
3 member1_declaration;
4 member2_declaration;
memberN_declaration is individual member
5 . . .
declaration.
6 memberN_declaration;
7 };
 Accessing the union members:
 You need to create an object of union to access its members.
 Object is a variable of type union. Union members are accessed using the dot operator(.)
between union’s object and union’s member name.
Syntax
1 union union_name union_variable;

2
Example to Define Union
Example
1 union student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 } student1;

 You must terminate union definition with semicolon ;.


 You cannot assign value to members inside the union definition, it will cause
compilation error.
Example
1 union student
2 {
3 char name[30] = “ABC”; // Student Name
4 . . .
5 } student1;
3
Structure Vs. Union
COMPARISON STRUCTURE UNION
Basic The separate memory location is allotted to All members of the 'union' share the same memory location.
each member of the structure.
keyword 'struct' 'union'
Size Size of Structure = sum of size of all the data Size of Union = size of the largest member.
members.
Store Value Stores distinct values for all the members. Stores same value for all the members.
At a Time A structure stores multiple values, of the A union stores a single value at a time for all members.
different members, of the structure.
Declaration struct ss union uu
{ { 4 bytes
int a; 1 byte for c int a;
float f; float f; c
2 bytes for a a
char c char c f
}; 4 bytes for f };

4
Where Union should be used?
 Mouse Programming
 Embedded Programming
 Low Level System Programming

You might also like