Lec 15- Programming Fundamentals (1) (3)
Lec 15- Programming Fundamentals (1) (3)
Lecture 12
Week 15
Ms. Noor-ul-Huda
Lecturer
Department of Computer Science
College of Computer Science and Information Systems
noor.huda@iobm.edu.pk
Lecture Objectives:
•Structures
•Unions
Structures
• A structure is a collection of variables of different data types grouped
together under a single name.
• Each variable in a structure is assigned its own memory location,
allowing them to hold independent values.
2/25
Structures
• The struct keyword is used to define the structure in the C programming
language.
• The items in the structure are called its member and they can be of any
valid data type.
2/25
Syntax of Structures
• struct structure_name {
• data_type member_name1;
• data_type member_name1;
• ....
• ....
• };
2/25
Intitialize Structure members
• We can initialize structure members in 3 ways which are as follows:
2/25
Intitialize Structure members
• Example of a structure called Employee that stores information about an
employee:
• struct Employee {
• int id;
• char name[50];
• float salary; };
2/25
Structure
• struct Employee emp;
• emp.id = 1;
• emp.salary = 50000.00;
2/25
Union
• union Data {
• int number;
• float decimal;
• };
value.decimal = 3.14; // decimal will now have a value, and number will lose its value
printf("Number: %d\n", value.number); // undefined behavior, as number lost its value when
decimal was assigned 2/25
Key Differences
• Memory allocation: Structures allocate separate memory for each member, while unions share the
same memory for all members.
• Data storage: Structures can hold independent values for each member, while unions can only hold
one value at a time for any of its members.
• Use cases: Structures are used to group related data that needs to be accessed independently, while
unions are used to save memory when only one member needs to be active at a time.
2/25