Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Programming Lecture-14 Unions

Similar presentations


Presentation on theme: "C Programming Lecture-14 Unions"— Presentation transcript:

1 C Programming Lecture-14 Unions
$p!derLabWeb C Programming Lecture-14 Unions

2 Defining Union Union is also the collection of data of different datatypes. To define union we use the keyword union. Syntax:- union union_name{ // list of variables of different datatypes }; Eg. union student{ int roll_no; char[80] name; };

3 Declaration of variable of defined union
Its all same as structure but difference is that we have replace the struct keyword with union keyword. Syntax:- union union_name var_name; Eg. union student s; union student s[5]; union student *s;

4 Initializing the variables of defined union
Syntax:- union union_name var_name = {list of values}; Eg. union student s1={1,”jacob”}; union student s2={2,”shane”}; union student s3={3,”xiang”};

5 Accessing the Union Members
To access the variables or members of union, we have to two ways :- -> when the variable of union is trying to access the members of union then we use the dot operator ( . ) Eg. union student s1; s1.roll_no = 4; s1.name = “edward”;

6 -> when the pointer to union is trying to access the members of union then we use the arrow operator ( -> ). Eg. union student *stu; stu->roll_no = 5; stu->name = “bella”;

7 Difference between Structure and Union
Both provide almost same purpose but the difference lies in the storage memory both take to execute. The memory assigned to the variable of structure is the sum of memory of variables declared in the structure. On the other hand, memory assigned to the variable of union is the memory of that variable which takes up most memory among them.

8 Thank you!


Download ppt "C Programming Lecture-14 Unions"

Similar presentations


Ads by Google