unions

8
Programming in C Unions Unions BY BY SHABEER ISMAEEL SHABEER ISMAEEL

Upload: shareb-ismaeel

Post on 21-Feb-2017

16 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: Unions

Programming in C

UnionsUnionsBYBY

SHABEER ISMAEELSHABEER ISMAEEL

Page 2: Unions

Unions

• A A union is a user defined data type that may hold is a user defined data type that may hold different type of members of different sizes, BUT different type of members of different sizes, BUT only one type at a time. only one type at a time.

• All members of the union share the same memory. .

• The compiler assigns enough memory for the largest The compiler assigns enough memory for the largest of the member types.of the member types.

• The syntax for defining a The syntax for defining a union and using its and using its members is the same as the syntax for a members is the same as the syntax for a struct..

Page 3: Unions

Formal Union Definition• The general form of a The general form of a unionunion definition is definition is

union tag{ member1_declaration; member2_declaration; member3_declaration; . . . memberN_declaration; };

where where union is the keyword, is the keyword, tagtag names this kind of names this kind of union, , and and mmember_declarations are variable declarations are variable declarations which define the members.which define the members.

Note that the syntax for defining a Note that the syntax for defining a union is exactly the same is exactly the same as the syntax for a as the syntax for a struct..

Page 4: Unions

EXAMPLE OF UNION

The union of Employee is declared asThe union of Employee is declared as union employeeunion employee{{int emp_id;int emp_id;char name[20];char name[20];float salary;float salary;char address[50];char address[50];int dept_no;int dept_no;int ageint age; ; }; };

Page 5: Unions

MEMORY SPACE ALLOCATION

Page 6: Unions

SIMPLE PROGRAMMING EXAMPLE#include<stdio.h>#include<stdio.h>#include<conio.h>#include<conio.h>union employeeunion employee{{char name[20];char name[20];float salary;float salary;}u;}u;int main()int main(){{clrscr();clrscr();printf(“enter the name\n”);printf(“enter the name\n”);scanf(“%s”,&u.name);scanf(“%s”,&u.name);printf(“enter the salary\n”);printf(“enter the salary\n”);scanf(“%f”,&u.salary);scanf(“%f”,&u.salary);printf(“name: %s\n”,u.name);printf(“name: %s\n”,u.name);printf(“salary: %f”,u.salary);printf(“salary: %f”,u.salary);return 0;return 0;}}

Page 7: Unions

Union vs. Struct

• SimilaritiesSimilarities– Definition syntax virtually identical– Member access syntax identical

• DifferencesDifferences– Members of a struct each have their own address in

memory. – The size of a struct is at least as big as the sum of the

sizes of the members.– Members of a union share the same memory. – The size of a union is the size of the largest member.

Page 8: Unions