Union

Table of contents:

Introduction

Union is a composite type similar to structure. Even though it has members of different data types, it can hold data of only one member at a time.

Program

union marks \ A
{
 float perc; \ B
 char grade; \ C
}
main ( )
{
 union marks student1; \ E
 student1.perc = 98.5; \ F
 printf( "Marks are %f address is %16lu
",
 student1.perc, &student1.perc); \ G
 student1.grade = 'A''; \ H
 printf( "Grade is %c address is %16lu
",
 student1.grade, &student1.grade); \ I
}

Explanation

  1. Statement A declares a union of the type marks. It has two members: perc and grade. These two members are of different data types but they are allocated the same storage. The storage allocated by the union variable is equal to the maximum size of the members. In this case, the member grade occupies 1 byte, while the member perc occupies 4 bytes, so the allocation is 4 bytes. The data is interpreted in bytes depending on which member you are accessing.
  2. Statement E declares the variable student1 of the type union.
  3. Statement F assigns a value to a member of the union. In this case, the data is interpreted as the float data type.
  4. Statement H assigns character ‘A’ to member grade. student1.grade interprets the data as character data.
  5. When you print the value of the member perc, you have to use the placeholder %type. Note that the addresses printed by both printf statements are the same. This means that both members have the same memory location.

Points to Remember

  1. In a union, the different members share the same memory location.
  2. The total memory allocated to the union is equal to the maximum size of the member.
  3. Since multiple members of different data types have the same location, the data is interpreted according to the type of the member.


C & Data Structures
C & Data Structures (Charles River Media Computer Engineering)
ISBN: 1584503386
EAN: 2147483647
Year: 2006
Pages: 232

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net