1 of 7

Union

{C}

Programming

Programming for Problem Solving (PPS)

GTU # 3110003

USING

Prof. Nilesh Gambhava

Computer Engineering Department,�Darshan Institute of Engineering & Technology, Rajkot

2 of 7

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.

Prof. Nilesh Gambhava

#3110003 (PPS) – Union

2

3 of 7

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.

  • 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.

union union_name

{

    member1_declaration;

    member2_declaration;

. . .

    memberN_declaration;

};

1

2

3

4

5

6

7

Syntax

union_name is name of custom type.

memberN_declaration is individual member declaration.

union union_name union_variable;

1

Syntax

Prof. Nilesh Gambhava

#3110003 (PPS) – Union

3

4 of 7

Example to Define Union

  • You must terminate union definition with semicolon ;.
  • You cannot assign value to members inside the union definition, it will cause compilation error.

union student

{

char name[30]; // Student Name

int roll_no; // Student Roll No

float CPI; // Student CPI

int backlog; // Student Backlog

} student1;

1

2

3

4

5

6

7

union student

{

    char name[30] = “ABC”; // Student Name

. . .

} student1;

1

2

3

4

5

Example

Example

Prof. Nilesh Gambhava

#3110003 (PPS) – Union

4

5 of 7

Structure Vs. Union

COMPARISON

STRUCTURE

UNION

Basic

The separate memory location is allotted to each member of the structure.

All members of the 'union' share the same memory location.

keyword

'struct'

'union'

Size

Size of Structure = sum of size of all the data members.

Size of Union = size of the largest member.

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 different members, of the structure.

A union stores a single value at a time for all members.

Declaration

struct ss

{

    int a;

float f;

char c

};

union uu

{

    int a;

float f;

char c

};

1 byte for c

2 bytes for a

4 bytes for f

4 bytes

f

a

c

Prof. Nilesh Gambhava

#3110003 (PPS) – Union

5

6 of 7

Where Union should be used?

  • Mouse Programming
  • Embedded Programming
  • Low Level System Programming

Prof. Nilesh Gambhava

#3110003 (PPS) – Union

6

7 of 7

Thank you