Presentation is loading. Please wait.

Presentation is loading. Please wait.

UNION UNIT -II. Unions A union is another compound datatype like a structure. So what is the properties of structure? Eg: Union exam { int roll_no; Char.

Similar presentations


Presentation on theme: "UNION UNIT -II. Unions A union is another compound datatype like a structure. So what is the properties of structure? Eg: Union exam { int roll_no; Char."— Presentation transcript:

1 UNION UNIT -II

2 Unions A union is another compound datatype like a structure. So what is the properties of structure? Eg: Union exam { int roll_no; Char name[15]; int m1,m2,m3; }; Syntax:?

3 Difference is in M/y allocation Union exam { int roll_no; Char name[15]; int m1,m2,m3; }; Which one got higher m/y allocation. Diagram: Fig.M/y allocation All members are allocated in a common place of m/y(share the same m/y location)

4 A union shared the m/y instead of wasting storage on variables that are not being used. The compiler allocates a piece of storage that is larger enough to hold the largest type in the union. Eg: In union member name requires 15 char which is maximum of all members. In structure,the total m\y is 23 i.e 15+2+2+2+2 bytes

5 Implementation -Major difference. -although a union may contain many members of different datatypes,it can handle only one member at a time. -can initialize one member. -if try to initialize more than one the last initialized value will be assigned to all members.

6 Initialization of a union Union exam { int rollno,m1,m2,m3; }u1; void main() {u1.rollno=252; u2.m1=89; Printf(“rollno:%d\n”,u1.rollno); Printf(“m1:%d\n”,u1.m1); Printf(“m2:%d\n”,u1.m2); Printf(“m3:%d\n”,u1.m3); } o/p: Roll no:89 M1:89 M2:89 M3:89

7 Example program Union exam { int rollno; Char name[15]; int m1,m2,m3; }u1; Struct exam1 { int roll_no; char name[15]; int m1,m2,m3; }s1; void main() { Printf(“the size of union is %d”,sizeof(u1)); Printf(“the size of structure is %d\n”,sizeof(s1)); } o/p:The size of union is ? The size of structure is ?


Download ppt "UNION UNIT -II. Unions A union is another compound datatype like a structure. So what is the properties of structure? Eg: Union exam { int roll_no; Char."

Similar presentations


Ads by Google